List of usage examples for javax.management MBeanServerInvocationHandler newProxyInstance
public static <T> T newProxyInstance(MBeanServerConnection connection, ObjectName objectName, Class<T> interfaceClass, boolean notificationBroadcaster)
Return a proxy that implements the given interface by forwarding its methods through the given MBean server to the named MBean.
From source file:org.apache.uima.examples.as.GetMetaRequest.java
private static QueueViewMBean getQueueMBean(String key, ObjectName matchPattern) throws Exception { // Fetch queue names matching a given pattern. Set<ObjectName> queues = new HashSet<ObjectName>(brokerMBeanServer.queryNames(matchPattern, null)); for (ObjectName name : queues) { // Create and return a proxy to the queue's MBean return (QueueViewMBean) MBeanServerInvocationHandler.newProxyInstance(brokerMBeanServer, name, QueueViewMBean.class, true); }//from w ww . j ava 2 s .c om return null; }
From source file:org.red5.server.tomcat.TomcatVHostLoader.java
/** * Starts a web application and its red5 (spring) component. This is basically a stripped down * version of init().//from w w w. j a v a2 s. co m * * @return true on success */ @SuppressWarnings("cast") public boolean startWebApplication(String applicationName) { boolean result = false; log.info("Starting Tomcat virtual host - Web application"); log.info("Virtual host root: {}", webappRoot); log.info("Virtual host context id: {}", defaultApplicationContextId); // application directory String contextName = '/' + applicationName; Container cont = null; //check if the context already exists for the host if ((cont = host.findChild(contextName)) == null) { log.debug("Context did not exist in host"); String webappContextDir = FileUtil.formatPath(webappRoot, applicationName); //prepend slash Context ctx = addContext(contextName, webappContextDir); //set the newly created context as the current container cont = ctx; } else { log.debug("Context already exists in host"); } try { ServletContext servletContext = ((Context) cont).getServletContext(); log.debug("Context initialized: {}", servletContext.getContextPath()); String prefix = servletContext.getRealPath("/"); log.debug("Path: {}", prefix); Loader cldr = cont.getLoader(); log.debug("Loader type: {}", cldr.getClass().getName()); ClassLoader webClassLoader = cldr.getClassLoader(); log.debug("Webapp classloader: {}", webClassLoader); //create a spring web application context XmlWebApplicationContext appctx = new XmlWebApplicationContext(); appctx.setClassLoader(webClassLoader); appctx.setConfigLocations(new String[] { "/WEB-INF/red5-*.xml" }); //check for red5 context bean if (applicationContext.containsBean(defaultApplicationContextId)) { appctx.setParent((ApplicationContext) applicationContext.getBean(defaultApplicationContextId)); } else { log.warn("{} bean was not found in context: {}", defaultApplicationContextId, applicationContext.getDisplayName()); //lookup context loader and attempt to get what we need from it if (applicationContext.containsBean("context.loader")) { ContextLoader contextLoader = (ContextLoader) applicationContext.getBean("context.loader"); appctx.setParent(contextLoader.getContext(defaultApplicationContextId)); } else { log.debug("Context loader was not found, trying JMX"); MBeanServer mbs = JMXFactory.getMBeanServer(); //get the ContextLoader from jmx ObjectName oName = JMXFactory.createObjectName("type", "ContextLoader"); ContextLoaderMBean proxy = null; if (mbs.isRegistered(oName)) { proxy = (ContextLoaderMBean) MBeanServerInvocationHandler.newProxyInstance(mbs, oName, ContextLoaderMBean.class, true); log.debug("Context loader was found"); appctx.setParent(proxy.getContext(defaultApplicationContextId)); } else { log.warn("Context loader was not found"); } } } if (log.isDebugEnabled()) { if (appctx.getParent() != null) { log.debug("Parent application context: {}", appctx.getParent().getDisplayName()); } } // appctx.setServletContext(servletContext); //set the root webapp ctx attr on the each servlet context so spring can find it later servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx); appctx.refresh(); result = true; } catch (Throwable t) { log.error("Error setting up context: {}", applicationName, t); if (log.isDebugEnabled()) { t.printStackTrace(); } } return result; }
From source file:com.cisco.oss.foundation.message.HornetQMessagingFactory.java
private static void printHQVersion(final String host, final String port) { LOGGER.info("HornetQ version: {}", VersionLoader.getVersion().getVersionName()); Runnable getVersionFromServer = new Runnable() { @Override/*from w w w . jav a2 s.co m*/ public void run() { try { // Step 9. Retrieve the ObjectName of the queue. This is used to identify the server resources to manage ObjectName on = ObjectNameBuilder.DEFAULT.getHornetQServerObjectName(); // Step 10. Create JMX Connector to connect to the server's MBeanServer String url = MessageFormat.format("service:jmx:rmi://{0}/jndi/rmi://{0}:{1}/jmxrmi", host, port == null ? "3900" : port); LOGGER.debug("HornetQ Server jmx url: {}", url); JMXConnector connector = JMXConnectorFactory.connect(new JMXServiceURL(url), new HashMap()); // Step 11. Retrieve the MBeanServerConnection MBeanServerConnection mbsc = connector.getMBeanServerConnection(); // Step 12. Create a JMSQueueControl proxy to manage the queue on the server JMSServerControl serverControl = MBeanServerInvocationHandler.newProxyInstance(mbsc, on, JMSServerControl.class, false); String serverControlVersion = serverControl.getVersion(); LOGGER.info("HornetQ Server version: {}", serverControlVersion); } catch (Exception e) { LOGGER.info("can't log server version. error is: {}", e.toString()); } } }; try { new Thread(getVersionFromServer).start(); } catch (Exception e) { LOGGER.info("can't log server version. error is: {}", e.toString()); } }
From source file:com.continuent.tungsten.common.jmx.JmxManager.java
/** * Client helper method to obtain a proxy that implements the given * interface by forwarding its methods through the given MBean server to the * named MBean./* www . ja va2 s. co m*/ * * @param clientConnection the MBean server to forward to * @param mbeanClass The MBean interface this instance implements * @param mbeanName A custom name for this MBean * @param notificationBroadcaster If true make the returned proxy implement * NotificationEmitter by forwarding its methods via connection * @return An MBean proxy */ public static Object getMBeanProxy(JMXConnector clientConnection, Class<?> mbeanClass, String mbeanName, boolean notificationBroadcaster, boolean ignored) { try { ObjectName objectName = generateMBeanObjectName(mbeanClass.getName(), mbeanName); return MBeanServerInvocationHandler.newProxyInstance(clientConnection.getMBeanServerConnection(), objectName, mbeanClass, notificationBroadcaster); } catch (Exception e) { throw new ServerRuntimeException("Unable to get proxy connection to bean", e); } }
From source file:com.continuent.tungsten.common.jmx.JmxManager.java
/** * Client helper method to obtain a proxy that implements the given * interface by forwarding its methods through the given MBean server to the * named MBean.//from w w w.ja v a2 s . com * * @param clientConnection the MBean server to forward to * @param mbeanClass The class for which an MBean exists * @param notificationBroadcaster If true make the returned proxy implement * NotificationEmitter by forwarding its methods via connection * @return An MBean proxy */ public static Object getMBeanProxy(JMXConnector clientConnection, Class<?> mbeanClass, boolean notificationBroadcaster) { String mbeanInterfaceClassName = mbeanClass.getName() + "MBean"; Class<?> mbeanInterfaceClass = null; try { mbeanInterfaceClass = Class.forName(mbeanInterfaceClassName); } catch (ClassNotFoundException c) { throw new ServerRuntimeException(String.format( "Cannot get an RMI proxy for class %s because the interface class %s was not found", mbeanClass.getName(), mbeanInterfaceClassName)); } try { ObjectName objectName = generateMBeanObjectName(mbeanClass); return MBeanServerInvocationHandler.newProxyInstance(clientConnection.getMBeanServerConnection(), objectName, mbeanInterfaceClass, notificationBroadcaster); } catch (Exception e) { throw new ServerRuntimeException( String.format("Cannot get an RMI proxy for class %s because of this exception: %s", mbeanClass.getName(), e), e); } }
From source file:com.continuent.tungsten.common.jmx.JmxManager.java
/** * Client helper method to obtain a proxy that implements the given * interface by forwarding its methods through the given MBean server to the * named MBean./* ww w. j av a 2 s.c om*/ * * @param clientConnection the MBean server to forward to * @param mbeanClass The MBean interface this instance implements * @param mbeanName A custom name for this MBean * @param notificationBroadcaster If true make the returned proxy implement * NotificationEmitter by forwarding its methods via connection * @return An MBean proxy */ public static Object getMBeanProxy(JMXConnector clientConnection, Class<?> mbeanClass, Class<?> mbeanInterface, String mbeanName, boolean notificationBroadcaster, boolean ignored) { try { ObjectName objectName = generateMBeanObjectName(mbeanClass.getName(), mbeanName); return MBeanServerInvocationHandler.newProxyInstance(clientConnection.getMBeanServerConnection(), objectName, mbeanInterface, notificationBroadcaster); } catch (Exception e) { throw new ServerRuntimeException("Unable to get proxy connection to bean", e); } }
From source file:org.red5.server.tomcat.TomcatLoader.java
/** * Starts a web application and its red5 (spring) component. This is * basically a stripped down version of init(). * //from w w w. jav a 2s . c om * @return true on success */ public boolean startWebApplication(String applicationName) { log.info("Starting Tomcat - Web application"); boolean result = false; //get a reference to the current threads classloader final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); log.debug("Webapp root: {}", webappFolder); // application directory String contextName = '/' + applicationName; Container ctx = null; if (webappFolder == null) { // Use default webapps directory webappFolder = System.getProperty("red5.root") + "/webapps"; } System.setProperty("red5.webapp.root", webappFolder); log.info("Application root: {}", webappFolder); // scan for additional webapp contexts // Root applications directory File appDirBase = new File(webappFolder); // check if the context already exists for the host if ((ctx = host.findChild(contextName)) == null) { log.debug("Context did not exist in host"); String webappContextDir = FileUtil.formatPath(appDirBase.getAbsolutePath(), applicationName); log.debug("Webapp context directory (full path): {}", webappContextDir); // set the newly created context as the current container ctx = addContext(contextName, webappContextDir); } else { log.debug("Context already exists in host"); } final ServletContext servletContext = ((Context) ctx).getServletContext(); log.debug("Context initialized: {}", servletContext.getContextPath()); String prefix = servletContext.getRealPath("/"); log.debug("Path: {}", prefix); try { Loader cldr = ctx.getLoader(); log.debug("Loader delegate: {} type: {}", cldr.getDelegate(), cldr.getClass().getName()); if (cldr instanceof WebappLoader) { log.debug("WebappLoader class path: {}", ((WebappLoader) cldr).getClasspath()); } final ClassLoader webClassLoader = cldr.getClassLoader(); log.debug("Webapp classloader: {}", webClassLoader); // get the (spring) config file path final String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation") == null ? defaultSpringConfigLocation : servletContext.getInitParameter("contextConfigLocation"); log.debug("Spring context config location: {}", contextConfigLocation); // get the (spring) parent context key final String parentContextKey = servletContext.getInitParameter("parentContextKey") == null ? defaultParentContextKey : servletContext.getInitParameter("parentContextKey"); log.debug("Spring parent context key: {}", parentContextKey); //set current threads classloader to the webapp classloader Thread.currentThread().setContextClassLoader(webClassLoader); //create a thread to speed-up application loading Thread thread = new Thread("Launcher:" + servletContext.getContextPath()) { @SuppressWarnings("cast") public void run() { //set current threads classloader to the webapp classloader Thread.currentThread().setContextClassLoader(webClassLoader); // create a spring web application context XmlWebApplicationContext appctx = new XmlWebApplicationContext(); appctx.setClassLoader(webClassLoader); appctx.setConfigLocations(new String[] { contextConfigLocation }); // check for red5 context bean ApplicationContext parentAppCtx = null; if (applicationContext.containsBean(defaultParentContextKey)) { parentAppCtx = (ApplicationContext) applicationContext.getBean(defaultParentContextKey); } else { log.warn("{} bean was not found in context: {}", defaultParentContextKey, applicationContext.getDisplayName()); // lookup context loader and attempt to get what we need from it if (applicationContext.containsBean("context.loader")) { ContextLoader contextLoader = (ContextLoader) applicationContext .getBean("context.loader"); parentAppCtx = contextLoader.getContext(defaultParentContextKey); } else { log.debug("Context loader was not found, trying JMX"); MBeanServer mbs = JMXFactory.getMBeanServer(); // get the ContextLoader from jmx ObjectName oName = JMXFactory.createObjectName("type", "ContextLoader"); ContextLoaderMBean proxy = null; if (mbs.isRegistered(oName)) { proxy = (ContextLoaderMBean) MBeanServerInvocationHandler.newProxyInstance(mbs, oName, ContextLoaderMBean.class, true); log.debug("Context loader was found"); parentAppCtx = proxy.getContext(defaultParentContextKey); } else { log.warn("Context loader was not found"); } } } if (log.isDebugEnabled()) { if (appctx.getParent() != null) { log.debug("Parent application context: {}", appctx.getParent().getDisplayName()); } } appctx.setParent(parentAppCtx); appctx.setServletContext(servletContext); // set the root webapp ctx attr on the each // servlet context so spring can find it later servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx); appctx.refresh(); } }; thread.setDaemon(true); thread.start(); result = true; } catch (Throwable t) { log.error("Error setting up context: {} due to: {}", servletContext.getContextPath(), t.getMessage()); t.printStackTrace(); } finally { //reset the classloader Thread.currentThread().setContextClassLoader(originalClassLoader); } return result; }
From source file:org.apache.activemq.broker.jmx.ConcurrentMoveTest.java
public void testConcurrentMove() throws Exception { // Send some messages connection = connectionFactory.createConnection(); connection.start();/*from w w w . j a v a 2 s . c o m*/ Session session = connection.createSession(transacted, authMode); destination = createDestination(); MessageProducer producer = session.createProducer(destination); for (int i = 0; i < messageCount; i++) { Message message = session.createTextMessage("Message: " + i); producer.send(message); } long usageBeforMove = broker.getPersistenceAdapter().size(); LOG.info("Store usage:" + usageBeforMove); // Now get the QueueViewMBean and purge String objectNameStr = broker.getBrokerObjectName().toString(); objectNameStr += ",destinationType=Queue,destinationName=" + getDestinationString(); ObjectName queueViewMBeanName = assertRegisteredObjectName(objectNameStr); final QueueViewMBean proxy = (QueueViewMBean) MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); final ActiveMQQueue to = new ActiveMQQueue("TO"); ((RegionBroker) broker.getRegionBroker()).addDestination(broker.getAdminConnectionContext(), to, false); ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0; i < 50; i++) { executorService.execute(new Runnable() { @Override public void run() { try { proxy.moveMatchingMessagesTo(null, to.getPhysicalName()); } catch (Exception e) { e.printStackTrace(); } } }); } executorService.shutdown(); executorService.awaitTermination(5, TimeUnit.MINUTES); long count = proxy.getQueueSize(); assertEquals("Queue size", count, 0); assertEquals("Browse size", proxy.browseMessages().size(), 0); objectNameStr = broker.getBrokerObjectName().toString(); objectNameStr += ",destinationType=Queue,destinationName=" + to.getQueueName(); queueViewMBeanName = assertRegisteredObjectName(objectNameStr); QueueViewMBean toProxy = (QueueViewMBean) MBeanServerInvocationHandler.newProxyInstance(mbeanServer, queueViewMBeanName, QueueViewMBean.class, true); count = toProxy.getQueueSize(); assertEquals("Queue size", count, messageCount); long usageAfterMove = broker.getPersistenceAdapter().size(); LOG.info("Store usage, before: " + usageBeforMove + ", after:" + usageAfterMove); LOG.info("Store size increase:" + FileUtils.byteCountToDisplaySize(usageAfterMove - usageBeforMove)); assertTrue("Usage not more than doubled", usageAfterMove < (usageBeforMove * 3)); producer.close(); }
From source file:org.apache.aries.jmx.test.blueprint.BlueprintMBeanTest.java
@Test public void testBlueprintMetaDataMBean() throws Exception { //find the Blueprint Sample bundle's container service id String filter = "(&(osgi.blueprint.container.symbolicname=" // no similar one in interfaces + sample.getSymbolicName() + ")(osgi.blueprint.container.version=" + sample.getVersion() + "))"; ServiceReference[] serviceReferences = null; try {/*from ww w .jav a 2s . c o m*/ serviceReferences = bundleContext.getServiceReferences(BlueprintContainer.class.getName(), filter); } catch (InvalidSyntaxException e) { throw new RuntimeException(e); } long sampleBlueprintContainerServiceId = (Long) serviceReferences[0].getProperty(Constants.SERVICE_ID); //retrieve the proxy object BlueprintMetadataMBean metadataProxy = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, new ObjectName(BlueprintMetadataMBean.OBJECTNAME), BlueprintMetadataMBean.class, false); // test getBlueprintContainerServiceIds long[] bpContainerServiceIds = metadataProxy.getBlueprintContainerServiceIds(); assertEquals(3, bpContainerServiceIds.length); // test getBlueprintContainerServiceId assertEquals(sampleBlueprintContainerServiceId, metadataProxy.getBlueprintContainerServiceId(sample.getBundleId())); // test getComponentMetadata // bean: foo BeanValidator bv_foo = new BeanValidator("org.apache.aries.blueprint.sample.Foo", "init", "destroy"); BeanPropertyValidator bpv_a = property("a", "5"); BeanPropertyValidator bpv_b = property("b", "-1"); BeanPropertyValidator bpv_bar = new BeanPropertyValidator("bar"); bpv_bar.setObjectValueValidator(new RefValidator("bar")); BeanPropertyValidator bpv_currency = property("currency", "PLN"); BeanPropertyValidator bpv_date = property("date", "2009.04.17"); bv_foo.addPropertyValidators(bpv_a, bpv_b, bpv_bar, bpv_currency, bpv_date); bv_foo.validate(metadataProxy.getComponentMetadata(sampleBlueprintContainerServiceId, "foo")); // bean: bar BeanPropertyValidator bpv_value = property("value", "Hello FooBar"); BeanPropertyValidator bpv_context = new BeanPropertyValidator("context"); bpv_context.setObjectValueValidator(new RefValidator("blueprintBundleContext")); CollectionValidator cv = new CollectionValidator("java.util.List"); cv.addCollectionValueValidators(new ValueValidator("a list element"), new ValueValidator("5", "java.lang.Integer")); BeanPropertyValidator bpv_list = new BeanPropertyValidator("list"); bpv_list.setObjectValueValidator(cv); BeanValidator bv_bar = new BeanValidator("org.apache.aries.blueprint.sample.Bar"); bv_bar.addPropertyValidators(bpv_value, bpv_context, bpv_list); bv_bar.validate(metadataProxy.getComponentMetadata(sampleBlueprintContainerServiceId, "bar")); // service: ref=foo, no componentId set. So using it to test getComponentIdsByType. String[] serviceComponentIds = metadataProxy.getComponentIdsByType(sampleBlueprintContainerServiceId, BlueprintMetadataMBean.SERVICE_METADATA); assertEquals("There should be two service components in this sample", 2, serviceComponentIds.length); MapEntryValidator mev = new MapEntryValidator(); mev.setKeyValueValidator(new ValueValidator("key"), new ValueValidator("value")); RegistrationListenerValidator rglrv = new RegistrationListenerValidator("serviceRegistered", "serviceUnregistered"); rglrv.setListenerComponentValidator(new RefValidator("fooRegistrationListener")); ServiceValidator sv = new ServiceValidator(4); sv.setServiceComponentValidator(new RefValidator("foo")); sv.addMapEntryValidator(mev); sv.addRegistrationListenerValidator(rglrv); sv.validate(metadataProxy.getComponentMetadata(sampleBlueprintContainerServiceId, serviceComponentIds[0])); // bean: fooRegistrationListener BeanValidator bv_fooRegistrationListener = new BeanValidator( "org.apache.aries.blueprint.sample.FooRegistrationListener"); bv_fooRegistrationListener.validate( metadataProxy.getComponentMetadata(sampleBlueprintContainerServiceId, "fooRegistrationListener")); // reference: ref2 ReferenceListenerValidator rlrv_1 = new ReferenceListenerValidator("bind", "unbind"); rlrv_1.setListenerComponentValidator(new RefValidator("bindingListener")); ReferenceValidator rv = new ReferenceValidator("org.apache.aries.blueprint.sample.InterfaceA", 100); rv.addReferenceListenerValidator(rlrv_1); rv.validate(metadataProxy.getComponentMetadata(sampleBlueprintContainerServiceId, "ref2")); // bean: bindingListener BeanValidator bv_bindingListener = new BeanValidator("org.apache.aries.blueprint.sample.BindingListener"); bv_bindingListener .validate(metadataProxy.getComponentMetadata(sampleBlueprintContainerServiceId, "bindingListener")); // reference-list: ref-list ReferenceListenerValidator rlrv_2 = new ReferenceListenerValidator("bind", "unbind"); rlrv_2.setListenerComponentValidator(new RefValidator("listBindingListener")); ReferenceListValidator rlv_ref_list = new ReferenceListValidator( "org.apache.aries.blueprint.sample.InterfaceA"); rlv_ref_list.addReferenceListenerValidator(rlrv_2); rlv_ref_list.validate(metadataProxy.getComponentMetadata(sampleBlueprintContainerServiceId, "ref-list")); // bean: listBindingListener BeanValidator bv_listBindingListener = new BeanValidator( "org.apache.aries.blueprint.sample.BindingListener"); bv_listBindingListener.validate( metadataProxy.getComponentMetadata(sampleBlueprintContainerServiceId, "listBindingListener")); // bean: circularReference ReferenceListenerValidator rlrv_3 = new ReferenceListenerValidator("bind", "unbind"); rlrv_3.setListenerComponentValidator(new RefValidator("circularReference")); ReferenceListValidator rlv_2 = new ReferenceListValidator("org.apache.aries.blueprint.sample.InterfaceA", 2); rlv_2.addReferenceListenerValidator(rlrv_3); BeanPropertyValidator bpv_list_2 = new BeanPropertyValidator("list"); bpv_list_2.setObjectValueValidator(rlv_2); BeanValidator bv_circularReference = new BeanValidator("org.apache.aries.blueprint.sample.BindingListener", "init"); bv_circularReference.addPropertyValidators(bpv_list_2); bv_circularReference.validate( metadataProxy.getComponentMetadata(sampleBlueprintContainerServiceId, "circularReference")); }
From source file:org.apache.qpid.test.utils.JMXTestUtils.java
public <T> T getManagedObject(Class<T> managedClass, ObjectName objectName) { return MBeanServerInvocationHandler.newProxyInstance(_mbsc, objectName, managedClass, false); }