private static void checkMBeansLoadedSuccessfully(Set mbeans) throws ServiceNotFoundException { // MLet.getMBeansFromURL returns a Set containing exceptions if an MBean could not be loaded boolean allLoaded = true; for (Iterator i = mbeans.iterator(); i.hasNext();) { Object mbean = i.next(); if (mbean instanceof Throwable) { ((Throwable)mbean).printStackTrace(); allLoaded = false; // And go on with the next } else { // Ok, the MBean was registered successfully System.out.println("Registered MBean: " + mbean); } } if (!allLoaded) throw new ServiceNotFoundException("Some MBean could not be loaded"); }
private ServiceInfo getServiceInfoByVertx(Consumer<ServiceInfoResult> consumer, Function<ServiceInfo,Boolean> criteria) { // TODO add caching mechanism with TTL to reduce vertx.eventBus().send(GlobalKeyHolder.SERVICE_REGISTRY_GET, "xyz", (AsyncResultHandler<Message<byte[]>>) h -> { if (h.succeeded()) { final List<ServiceInfo> serviceInfos = getServiceInfoFromMessage(h).filter(info -> criteria.apply(info)).collect(Collectors.toList()); if(!serviceInfos.isEmpty()){ consumer.accept(new ServiceInfoResult(serviceInfos.stream(),h.succeeded(),h.cause())); }else { consumer.accept(new ServiceInfoResult(serviceInfos.stream(),false,new ServiceNotFoundException("selected service not found"))); } } else { consumer.accept(new ServiceInfoResult(Stream.<ServiceInfo>empty(),h.succeeded(),h.cause())); } } ); return null; }
/** * Find in the Service Loader a {@link FormToolkit} that returns the required form instance type of rendered forms * * @param implementationClass * The specific implementation class that the form toolkit must return * @return The FormToolkit that build form instances of that its specific implementation returns the given class * @throws ServiceNotFoundException * When a FormToolkit is not found */ @SuppressWarnings("unchecked") public <S> FormToolkit<S> getFormToolkit(Class<S> implementationClass) throws ServiceNotFoundException { Iterator<FormToolkit> it = loader.iterator(); FormToolkit toolkit = null; while (toolkit == null && it.hasNext()) { FormToolkit tl = it.next(); if (implementationClass.isAssignableFrom(tl.getImplementationClass())) { toolkit = tl; } } if (toolkit == null) { throw new ServiceNotFoundException(); } else { return toolkit; } }
@SuppressWarnings({ "unchecked" }) public <S> BFormToolkit<S> getFormToolkit(Class<S> implementationClass) throws ServiceNotFoundException { Iterator<BFormToolkit> it = loader.iterator(); BFormToolkit toolkit = null; while (toolkit == null && it.hasNext()) { BFormToolkit tl = it.next(); if (implementationClass.isAssignableFrom(tl.getImplementationClass())) { toolkit = tl; } } if (toolkit == null) { throw new ServiceNotFoundException(); } else { return toolkit; } }
@Test public void testServiceLoader() throws ServiceNotFoundException { FormToolkit<Component> toolkit = FormService.getInstance().getFormToolkit(Component.class); Form form = new SampleForm(); VaadinFormInstance instance = (VaadinFormInstance) toolkit.buildForm(form); assertNotNull(instance); Component component = instance.getImplementation(); assertThat(component, instanceOf(VerticalLayout.class)); Component cifCode = instance.getComponentById("fCif"); assertThat(cifCode, instanceOf(TextField.class)); Component active = instance.getComponentById("fActive"); assertThat(active, instanceOf(CheckBox.class)); }
/** * Appends the specified URL to the list of URLs to search for classes and * resources. * @exception ServiceNotFoundException The specified URL is malformed. */ public void addURL(String url) throws ServiceNotFoundException { try { URL ur = new URL(url); if (!Arrays.asList(getURLs()).contains(ur)) super.addURL(ur); } catch (MalformedURLException e) { if (MLET_LOGGER.isLoggable(Level.FINEST)) { MLET_LOGGER.logp(Level.FINEST, MLet.class.getName(), "addUrl", "Malformed URL: " + url, e); } throw new ServiceNotFoundException("The specified URL is malformed"); } }
/** * Appends the specified URL to the list of URLs to search for classes and * resources. * @exception ServiceNotFoundException The specified URL is malformed. */ public void addURL(String url) throws ServiceNotFoundException { try { URL ur = new URL(url); if (!Arrays.asList(getURLs()).contains(ur)) super.addURL(ur); } catch (MalformedURLException e) { if (MLET_LOGGER.isLoggable(Level.DEBUG)) { MLET_LOGGER.log(Level.DEBUG, "Malformed URL: " + url, e); } throw new ServiceNotFoundException("The specified URL is malformed"); } }
public Object invoke(String actionName, Object[] params, String[] argTypes) throws MBeanException, ReflectionException { assertNotNull("actionName", actionName); // params argTypes are allowed to be null and mean no-arg method if (params == null) { params = NO_PARAMS; } if (argTypes == null) { argTypes = NO_ARGS; } for (int i = 0; i < argTypes.length; i++) { assertNotNull("argTypes[" + i + "]", argTypes[i]); } Signature signature = new Signature(actionName, argTypes); MBeanOperation operation = operations.get(signature); if (operation == null) { String message = "Operation " + signature + " not found"; throw new MBeanException(new ServiceNotFoundException(message), message); } Object result = operation.invoke(params); return result; }
public ServiceInfo operation(final String name, Consumer<OperationResult> consumer) { final Optional<Operation> first = Stream.of(operations).filter(op -> op.getName().equalsIgnoreCase(name)).findFirst(); if(first.isPresent()){ consumer.accept(new OperationResult(first.get(),true,null)); } else { consumer.accept(new OperationResult(null,false,new ServiceNotFoundException("no operation "+name+" was found"))); } return this; }
@Override public <U> VaadinBindingFormInstance<U> buildForm(BForm<U> form) { try { return buildForm(form, BindingService.getInstance().getBindingToolkit()); } catch (ServiceNotFoundException e) { throw new UnsupportedOperationException("Default binding toolkit not found", e); } }
public BindingToolkit getBindingToolkit() throws ServiceNotFoundException { Iterator<BindingToolkit> it = loader.iterator(); BindingToolkit toolkit = null; while (toolkit == null && it.hasNext()) { BindingToolkit tl = it.next(); toolkit = tl; } if (toolkit == null) { throw new ServiceNotFoundException(); } else { return toolkit; } }
@Test public void testServiceLoader() throws ServiceNotFoundException { FormToolkit<JComponent> toolkit = FormService.getInstance().getFormToolkit(JComponent.class); Form form = new SampleForm(); FormInstance<JComponent> instance = toolkit.buildForm(form); assertNotNull(instance); }
public List<Project> getProjects() throws AuthenticationFailedException, ServiceNotFoundException, Exception { HttpURLConnection con = getServiceConnection("api/projects"); if (con.getResponseCode() == 401) { throw new AuthenticationFailedException(); } else if (con.getResponseCode() == 404) { throw new ServiceNotFoundException(); } JavaType type = CollectionType.construct(ArrayList.class, SimpleType.construct(Project.class)); InputStream in = con.getInputStream(); try { return (List<Project>) objectMapper.readValue(in, type); } finally { in.close(); } }
public static void main(String[] args) throws Exception { boolean error = false; // Instantiate the MBean server // System.out.println("Create the MBean server"); MBeanServer mbs = MBeanServerFactory.createMBeanServer(); // Instantiate an MLet // System.out.println("Create the MLet"); MLet mlet = new MLet(); // Register the MLet MBean with the MBeanServer // System.out.println("Register the MLet MBean"); ObjectName mletObjectName = new ObjectName("Test:type=MLet"); mbs.registerMBean(mlet, mletObjectName); // Call getMBeansFromURL // System.out.println("Call mlet.getMBeansFromURL(<url>)"); String testSrc = System.getProperty("test.src"); System.out.println("test.src = " + testSrc); String urlCodebase; if (testSrc.startsWith("/")) { urlCodebase = "file:" + testSrc.replace(File.separatorChar, '/') + "/"; } else { urlCodebase = "file:/" + testSrc.replace(File.separatorChar, '/') + "/"; } String mletFile = urlCodebase + args[0]; System.out.println("MLet File = " + mletFile); try { mlet.getMBeansFromURL(mletFile); System.out.println( "TEST FAILED: Expected ServiceNotFoundException not thrown"); error = true; } catch (ServiceNotFoundException e) { if (e.getCause() == null) { System.out.println("TEST FAILED: Got unexpected null cause " + "in ServiceNotFoundException"); error = true; } else if (!(e.getCause() instanceof IOException)) { System.out.println("TEST FAILED: Got unexpected non-null " + "cause in ServiceNotFoundException"); error = true; } else { System.out.println("TEST PASSED: Got expected non-null " + "cause in ServiceNotFoundException"); error = false; } e.printStackTrace(System.out); } // Unregister the MLet MBean // System.out.println("Unregister the MLet MBean"); mbs.unregisterMBean(mletObjectName); // Release MBean server // System.out.println("Release the MBean server"); MBeanServerFactory.releaseMBeanServer(mbs); // End Test // System.out.println("Bye! Bye!"); if (error) System.exit(1); }
public static void main(String[] args) throws Exception { boolean error = false; // Instantiate the MBean server // System.out.println("Create the MBean server"); MBeanServer mbs = MBeanServerFactory.createMBeanServer(); // Instantiate an MLet // System.out.println("Create the MLet"); MLet mlet = new MLet(); // Register the MLet MBean with the MBeanServer // System.out.println("Register the MLet MBean"); ObjectName mletObjectName = new ObjectName("Test:type=MLet"); mbs.registerMBean(mlet, mletObjectName); // Call getMBeansFromURL // System.out.println("Call mlet.getMBeansFromURL(<url>)"); try { mlet.getMBeansFromURL("bogus://whatever"); System.out.println("TEST FAILED: Expected " + ServiceNotFoundException.class + " exception not thrown."); error = true; } catch (ServiceNotFoundException e) { if (e.getCause() == null) { System.out.println("TEST FAILED: Got null cause in " + ServiceNotFoundException.class + " exception."); error = true; } else { System.out.println("TEST PASSED: Got non-null cause in " + ServiceNotFoundException.class + " exception."); error = false; } e.printStackTrace(System.out); } // Unregister the MLet MBean // System.out.println("Unregister the MLet MBean"); mbs.unregisterMBean(mletObjectName); // Release MBean server // System.out.println("Release the MBean server"); MBeanServerFactory.releaseMBeanServer(mbs); // End Test // System.out.println("Bye! Bye!"); if (error) System.exit(1); }
public static void connectToDS(String host, int port) throws Exception { String url =MessageFormat.format(JMX_URI, new Object[] { host, String.valueOf(port) }); try { JMXServiceURL jmxurl = new JMXServiceURL(url); connector = JMXConnectorFactory.connect(jmxurl, null); mbsc = connector.getMBeanServerConnection(); String[] domains = mbsc.getDomains(); String domain = null; for (int i = 0; i < domains.length; i++) { if (domains[i].equalsIgnoreCase(MBEAN_DOMAIN_GEMFIRE_NAME)) { domain = domains[i]; break; } } Set set = mbsc.queryNames(new ObjectName(domain + ":*"), null); ObjectName on = null; for (Iterator iter = set.iterator(); iter.hasNext();) { on = (ObjectName)iter.next(); String onType = on.getKeyProperty(MBEAN_PROPERTY_BEAN_TYPE); if (MBEAN_AGENT_TYPE.equalsIgnoreCase(onType)) break; } agent = on; if (agent==null) throw new ServiceNotFoundException( MBEAN_AGENT_TYPE + " could not be connected"); String[] params = {}, signature = {}; String method = "connectToSystem"; ObjectName ret = null; ret = (ObjectName) mbsc.invoke(agent, method, params, signature); logger.info("Connected DS client"); if (ret != null && MBEAN_DISTRIBUTED_SYSTEM_TYPE. equalsIgnoreCase(ret.getKeyProperty(MBEAN_PROPERTY_BEAN_TYPE))) { distributedSys = ret; } else { ServiceNotFoundException ex = new ServiceNotFoundException( MBEAN_DISTRIBUTED_SYSTEM_TYPE + " could not be connected"); throw ex; } } catch (NullPointerException nullEx) { logger.error(url + " is construed NULL", nullEx); throw nullEx; } catch (MalformedURLException malfEx) { logger.error(url + " is construed Malformed", malfEx); throw malfEx; } catch (SecurityException secuEx) { logger.error("Connection denied due to Security reasons", secuEx); throw secuEx; } catch (InstanceNotFoundException instEx) { logger.error("Did not find MBean Instance", instEx); throw instEx; } catch (MBeanException beanEx) { logger.error("Exception in MBean", beanEx.getCause()); throw beanEx; } catch (ReflectionException reflEx) { logger.error("Could not get MBean Info", reflEx); throw reflEx; } catch (IOException ioEx) { logger.error("JMX Connection problem. Attempt opeartion Again", ioEx); throw ioEx; } finally { //shLock.unlock(); } }
public static void disconnectFromDS() throws Exception { try { String[] domains = mbsc.getDomains(); String domain = null; for (int i = 0; i < domains.length; i++) { if (domains[i].equalsIgnoreCase(MBEAN_DOMAIN_GEMFIRE_NAME)) { domain = domains[i]; break; } } Set set = mbsc.queryNames(new ObjectName(domain + ":*"), null); ObjectName on = null; for (Iterator iter = set.iterator(); iter.hasNext();) { on = (ObjectName)iter.next(); String onType = on.getKeyProperty(MBEAN_PROPERTY_BEAN_TYPE); if (MBEAN_AGENT_TYPE.equalsIgnoreCase(onType)) break; } agent = on; if (agent==null) throw new ServiceNotFoundException( MBEAN_AGENT_TYPE + " could not be contacted"); String[] params = {}, signature = {}; String method = "disconnectFromSystem"; ObjectName ret = null; mbsc.invoke(agent, method, params, signature); logger.info("DisConnected DS client"); } catch (SecurityException secuEx) { logger.error("Connection denied due to Security reasons", secuEx); throw secuEx; } catch (InstanceNotFoundException instEx) { logger.error("Did not find MBean Instance", instEx); throw instEx; } catch (MBeanException beanEx) { logger.error("Exception in MBean", beanEx.getCause()); throw beanEx; } catch (ReflectionException reflEx) { logger.error("Could not get MBean Info", reflEx); throw reflEx; } catch (IOException ioEx) { logger.error("JMX Connection problem. Attempt opeartion Again", ioEx); throw ioEx; } finally { //shLock.unlock(); } }
public static void main(String[] args) throws Exception { // Create the MBeanServer MBeanServer server = MBeanServerFactory.createMBeanServer(); // Register the MLet in the MBeanServer MLet mlet = new MLet(); ObjectName mletName = new ObjectName("system:mbean=loader"); server.registerMBean(mlet, mletName); // Set the MLet as context classloader // Can be useful for the loaded services that want to access this classloader. Thread.currentThread().setContextClassLoader(mlet); // Resolve the file to load MBeans from // If we got a program argument, we load it from there, otherwise // we assume we have a 'mbeans.mlet' file in this example's directory URL mbeansURL = null; if (args.length == 1) { String file = args[0]; mbeansURL = new File(file).toURL(); } else { mbeansURL = mlet.getResource("examples/services/loading/mbeans.mlet"); } // If the URL is still null, abort if (mbeansURL == null) throw new ServiceNotFoundException("Could not find MBeans to load"); // Load the MBeans Set mbeans = mlet.getMBeansFromURL(mbeansURL); System.out.println("MLet has now the following classpath: " + Arrays.asList(mlet.getURLs())); // Now let's check everything is ok. checkMBeansLoadedSuccessfully(mbeans); // Now the system is loaded, but maybe we should initialize and start them initializeMBeans(server, mbeans); startMBeans(server, mbeans); // Now the system is up and running System.out.println("System up and running !"); // The program exits because none of the loaded MBeans in this example started a non-daemon thread. }