@BeforeClass public static void beforeClass() throws Exception { runtimeType = RuntimeType.getRuntimeType(System.getProperty("target.container")); if (runtimeType == RuntimeType.KARAF) { String jmxServiceURL = "service:jmx:rmi://127.0.0.1:44444/jndi/rmi://127.0.0.1:1099/karaf-root"; Map<String, Object> env = ManagementUtils.getDefaultEnvironment(jmxServiceURL); env.put(JMXConnector.CREDENTIALS, new String[] {credentials[0], credentials[1]}); connector = ManagementUtils.getJMXConnector(jmxServiceURL, env, 10, TimeUnit.SECONDS); } else if (runtimeType == RuntimeType.TOMCAT) { String jmxServiceURL = "service:jmx:rmi:///jndi/rmi://127.0.0.1:8089/jmxrmi"; Map<String, Object> env = ManagementUtils.getDefaultEnvironment(jmxServiceURL); env.put(JMXConnector.CREDENTIALS, new String[] {credentials[0], credentials[1]}); connector = ManagementUtils.getJMXConnector(jmxServiceURL, env, 10, TimeUnit.SECONDS); } else if (runtimeType == RuntimeType.WILDFLY) { String jmxServiceURL = "service:jmx:http-remoting-jmx://127.0.0.1:9990"; Map<String, Object> env = ManagementUtils.getDefaultEnvironment(jmxServiceURL); env.put(JMXConnector.CREDENTIALS, new String[] {credentials[0], credentials[1]}); connector = WildFlyManagementUtils.getJMXConnector(jmxServiceURL, env, 10, TimeUnit.SECONDS); } else { throw new IllegalStateException("Usupported target container: " + runtimeType); } proxy = JMX.newMXBeanProxy( connector.getMBeanServerConnection(), ProfileManagement.OBJECT_NAME, ProfileManagement.class); }
/** * @param objectName * @return artifact * @throws InstanceNotFoundException */ public T getArtifact(final ObjectName objectName) throws InstanceNotFoundException { if (this.server.isRegistered(objectName)) { return JMX.newMXBeanProxy(this.server, objectName, this.artifactType); } throw new InstanceNotFoundException( String.format("Instance '%s' not found", objectName.getCanonicalName())); }
synchronized <T> T objectNameToMXBean(ObjectName name, Class<T> type) { WeakReference<Object> wr = objectNameToProxy.get(name); if (wr != null) { Object proxy = wr.get(); if (type.isInstance(proxy)) return type.cast(proxy); } InvocationHandler handler = new MBeanServerInvocationHandler(mbsc, name); T proxy = JMX.newMXBeanProxy(mbsc, name, type); objectNameToProxy.put(name, new WeakReference<Object>(proxy)); return proxy; }
/** * Returns the LoaderMBean. * * @return LoadeerMBean */ @SuppressWarnings("cast") public LoaderMXBean getLoader() { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); // proxy class LoaderMXBean proxy = null; ObjectName oName; try { oName = new ObjectName("org.red5.server:type=TomcatLoader"); if (mbs.isRegistered(oName)) { proxy = JMX.newMXBeanProxy(mbs, oName, LoaderMXBean.class, true); log.debug("Loader was found"); } else { log.warn("Loader not found"); } } catch (Exception e) { log.error("Exception getting loader", e); } return proxy; }
private boolean isEndpointRegistered(String applicationName, EndpointClassNamePathPair endpoint) { MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); String fullMxBeanName = "org.glassfish.tyrus:type=" + applicationName; ApplicationMXBean proxy; try { proxy = JMX.newMXBeanProxy(mBeanServer, new ObjectName(fullMxBeanName), ApplicationMXBean.class); List<EndpointClassNamePathPair> registeredEndpoints = proxy.getEndpoints(); for (EndpointClassNamePathPair registeredEndpoint : registeredEndpoints) { if (registeredEndpoint.getEndpointPath().equals(endpoint.getEndpointPath()) && registeredEndpoint.getEndpointClassName().equals(endpoint.getEndpointClassName())) { return true; } } } catch (Exception e) { e.printStackTrace(); } return false; }
/** * Returns a proxy for a platform MXBean interface of a given <a href="#MXBeanNames">MXBean * name</a> that forwards its method calls through the given <tt>MBeanServerConnection</tt>. * * <p>This method is equivalent to: * * <blockquote> * * {@link java.lang.reflect.Proxy#newProxyInstance * Proxy.newProxyInstance}<tt>(mxbeanInterface.getClassLoader(), new Class[] { mxbeanInterface }, * handler)</tt> * * </blockquote> * * where <tt>handler</tt> is an {@link java.lang.reflect.InvocationHandler InvocationHandler} to * which method invocations to the MXBean interface are dispatched. This <tt>handler</tt> converts * an input parameter from an MXBean data type to its mapped open type before forwarding to the * <tt>MBeanServer</tt> and converts a return value from an MXBean method call through the * <tt>MBeanServer</tt> from an open type to the corresponding return type declared in the MXBean * interface. * * <p>If the MXBean is a notification emitter (i.e., it implements {@link * javax.management.NotificationEmitter NotificationEmitter}), both the <tt>mxbeanInterface</tt> * and <tt>NotificationEmitter</tt> will be implemented by this proxy. * * <p><b>Notes:</b> * * <ol> * <li>Using an MXBean proxy is a convenience remote access to a platform MXBean of a running * virtual machine. All method calls to the MXBean proxy are forwarded to an * <tt>MBeanServerConnection</tt> where {@link java.io.IOException IOException} may be * thrown when the communication problem occurs with the connector server. An application * remotely accesses the platform MXBeans using proxy should prepare to catch * <tt>IOException</tt> as if accessing with the <tt>MBeanServerConnector</tt> interface. * <li>When a client application is designed to remotely access MXBeans for a running virtual * machine whose version is different than the version on which the application is running, * it should prepare to catch {@link java.io.InvalidObjectException InvalidObjectException} * which is thrown when an MXBean proxy receives a name of an enum constant which is missing * in the enum class loaded in the client application. * <li>{@link javax.management.MBeanServerInvocationHandler MBeanServerInvocationHandler} or its * {@link javax.management.MBeanServerInvocationHandler#newProxyInstance newProxyInstance} * method cannot be used to create a proxy for a platform MXBean. The proxy object created * by <tt>MBeanServerInvocationHandler</tt> does not handle the properties of the platform * MXBeans described in the <a href="#MXBean">class specification</a>. * </ol> * * @param connection the <tt>MBeanServerConnection</tt> to forward to. * @param mxbeanName the name of a platform MXBean within <tt>connection</tt> to forward to. * <tt>mxbeanName</tt> must be in the format of {@link ObjectName ObjectName}. * @param mxbeanInterface the MXBean interface to be implemented by the proxy. * @throws IllegalArgumentException if * <ul> * <li><tt>mxbeanName</tt> is not with a valid {@link ObjectName ObjectName} format, or * <li>the named MXBean in the <tt>connection</tt> is not a MXBean provided by the platform, * or * <li>the named MXBean is not registered in the <tt>MBeanServerConnection</tt>, or * <li>the named MXBean is not an instance of the given <tt>mxbeanInterface</tt> * </ul> * * @throws java.io.IOException if a communication problem occurred when accessing the * <tt>MBeanServerConnection</tt>. */ public static <T> T newPlatformMXBeanProxy( MBeanServerConnection connection, String mxbeanName, Class<T> mxbeanInterface) throws java.io.IOException { final Class interfaceClass = mxbeanInterface; // Only allow MXBean interfaces from rt.jar loaded by the // bootstrap class loader final ClassLoader loader = AccessController.doPrivileged( new PrivilegedAction<ClassLoader>() { public ClassLoader run() { return interfaceClass.getClassLoader(); } }); if (loader != null) { throw new IllegalArgumentException(mxbeanName + " is not a platform MXBean"); } try { final ObjectName objName = new ObjectName(mxbeanName); if (!connection.isInstanceOf(objName, interfaceClass.getName())) { throw new IllegalArgumentException(mxbeanName + " is not an instance of " + interfaceClass); } final Class[] interfaces; // check if the registered MBean is a notification emitter boolean emitter = connection.isInstanceOf(objName, NOTIF_EMITTER); // create an MXBean proxy return JMX.newMXBeanProxy(connection, objName, mxbeanInterface, emitter); } catch (InstanceNotFoundException e) { final IllegalArgumentException iae = new IllegalArgumentException(mxbeanName + " not found in the connection."); iae.initCause(e); throw iae; } catch (MalformedObjectNameException e) { final IllegalArgumentException iae = new IllegalArgumentException(mxbeanName + " is not a valid ObjectName format."); iae.initCause(e); throw iae; } }
private void awaitActive(String type, String name, String version) { try { ObjectName objectName = new ObjectName("org.eclipse.virgo.kernel:type=Model,artifact-type=" + type + ",name=" + name + ",version=" + version); ManageableArtifact artifact = JMX.newMXBeanProxy(this.mBeanServer, objectName, ManageableArtifact.class); long startTime = System.currentTimeMillis(); while (!"ACTIVE".equals(artifact.getState())) { if (System.currentTimeMillis() - startTime > TIMEOUT) { fail("Artifact " + type + " " + name + " " + version + " was not active within " + TIMEOUT + "ms."); } try { Thread.sleep(50); } catch (InterruptedException _) { } } } catch (JMException jme) { fail(jme.getMessage()); } }
@Test @Ignore public void reconnect() throws Exception { MarketDataRequest request = MarketDataRequestBuilder.newRequest().withSymbols("GOOG").create(); final DataFlowID flowID = moduleManager.createDataFlow( new DataRequest[] {new DataRequest(getInstanceURN(), request)}); // wait until some arbitrary number of ticks have been received AbstractMarketDataFeedTest.wait( new Callable<Boolean>() { @Override public Boolean call() throws Exception { return dataSink.getData(flowID).size() > 20; } }); // reconnect and wait for more data // TODO - need to figure out how to make this magic incantation work ObjectName objectName = getInstanceURN().toObjectName(); MBeanServerConnection mMBeanServer = null; AbstractMarketDataModuleMXBean mMBeanProxy = JMX.newMXBeanProxy(mMBeanServer, objectName, AbstractMarketDataModuleMXBean.class, true); }
/** * Initialization. * * @throws ServletException */ @SuppressWarnings("cast") @Override public void start() throws ServletException { log.info("Loading tomcat virtual host"); if (webappFolder != null) { // check for match with base webapp root if (webappFolder.equals(webappRoot)) { log.error("Web application root cannot be the same as base"); return; } } ClassLoader classloader = Thread.currentThread().getContextClassLoader(); // ensure we have a host if (host == null) { host = createHost(); } host.setParentClassLoader(classloader); String propertyPrefix = name; if (domain != null) { propertyPrefix += '_' + domain.replace('.', '_'); } log.debug("Generating name (for props) {}", propertyPrefix); System.setProperty(propertyPrefix + ".webapp.root", webappRoot); log.info("Virtual host root: {}", webappRoot); log.info("Virtual host context id: {}", defaultApplicationContextId); // Root applications directory File appDirBase = new File(webappRoot); // Subdirs of root apps dir File[] dirs = appDirBase.listFiles(new TomcatLoader.DirectoryFilter()); // Search for additional context files for (File dir : dirs) { String dirName = '/' + dir.getName(); // check to see if the directory is already mapped if (null == host.findChild(dirName)) { String webappContextDir = FileUtil.formatPath(appDirBase.getAbsolutePath(), dirName); Context ctx = null; if ("/root".equals(dirName) || "/root".equalsIgnoreCase(dirName)) { log.debug("Adding ROOT context"); ctx = addContext("/", webappContextDir); } else { log.debug("Adding context from directory scan: {}", dirName); ctx = addContext(dirName, webappContextDir); } log.debug("Context: {}", ctx); webappContextDir = null; } } appDirBase = null; dirs = null; // Dump context list if (log.isDebugEnabled()) { for (Container cont : host.findChildren()) { log.debug("Context child name: {}", cont.getName()); } } engine.addChild(host); // Start server try { log.info("Starting Tomcat virtual host"); // may not have to do this step for every host LoaderBase.setApplicationLoader( new TomcatApplicationLoader(embedded, host, applicationContext)); for (Container cont : host.findChildren()) { if (cont instanceof StandardContext) { StandardContext ctx = (StandardContext) cont; ServletContext servletContext = ctx.getServletContext(); log.debug("Context initialized: {}", servletContext.getContextPath()); // set the hosts id servletContext.setAttribute("red5.host.id", getHostId()); String prefix = servletContext.getRealPath("/"); log.debug("Path: {}", prefix); try { Loader cldr = ctx.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 = ManagementFactory.getPlatformMBeanServer(); // get the ContextLoader from jmx ContextLoaderMXBean proxy = null; ObjectName oName = null; try { oName = new ObjectName("org.red5.server:name=contextLoader,type=ContextLoader"); if (mbs.isRegistered(oName)) { proxy = JMX.newMXBeanProxy(mbs, oName, ContextLoaderMXBean.class, true); log.debug("Context loader was found"); proxy.setParentContext(defaultApplicationContextId, appctx.getId()); } else { log.warn("Context loader was not found"); } } catch (Exception e) { log.warn("Exception looking up ContextLoader", e); } } } 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(); } catch (Throwable t) { log.error("Error setting up context: {}", servletContext.getContextPath(), t); if (log.isDebugEnabled()) { t.printStackTrace(); } } } } } catch (Exception e) { log.error("Error loading Tomcat virtual host", e); } }
/** * Starts a web application and its red5 (spring) component. This is basically a stripped down * version of init(). * * @return true on success * @throws ServletException */ @SuppressWarnings("cast") public boolean startWebApplication(String applicationName) throws ServletException { 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 = ((Context) 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 = ManagementFactory.getPlatformMBeanServer(); // get the ContextLoader from jmx ContextLoaderMXBean proxy = null; ObjectName oName = null; try { oName = new ObjectName("org.red5.server:name=contextLoader,type=ContextLoader"); if (mbs.isRegistered(oName)) { proxy = JMX.newMXBeanProxy(mbs, oName, ContextLoaderMXBean.class, true); log.debug("Context loader was found"); proxy.setParentContext(defaultApplicationContextId, appctx.getId()); } else { log.warn("Context loader was not found"); } } catch (Exception e) { log.warn("Exception looking up ContextLoader", e); } } } 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; }
private void test(boolean monitorOnSessionLevel) { Server server = null; try { setContextPath("/monitoringBroadcastApp"); ApplicationMonitor applicationMonitor; if (monitorOnSessionLevel) { applicationMonitor = new SessionAwareApplicationMonitor(); } else { applicationMonitor = new SessionlessApplicationMonitor(); } int sessionsCount = 3; // each sessions gets 3 messages - 2 text messages and 1 binary CountDownLatch sentMessagesLatch = new CountDownLatch(sessionsCount * 3); ApplicationEventListener applicationEventListener = new TestApplicationEventListener( applicationMonitor, null, null, sentMessagesLatch, null, null); getServerProperties() .put(ApplicationEventListener.APPLICATION_EVENT_LISTENER, applicationEventListener); server = startServer(AnnotatedServerEndpoint.class); ClientManager client = createClient(); Session session = null; for (int i = 0; i < sessionsCount; i++) { session = client.connectToServer( AnnotatedClientEndpoint.class, getURI(AnnotatedServerEndpoint.class)); } // send different number of messages of each type so that it can be verified that a correct // MXBean is // accessed session.getBasicRemote().sendText("Broadcast request"); assertTrue(sentMessagesLatch.await(5, TimeUnit.SECONDS)); String applicationMxBeanName = "org.glassfish.tyrus:type=/monitoringBroadcastApp"; MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); ApplicationMXBean applicationMXBean = JMX.newMXBeanProxy( mBeanServer, new ObjectName(applicationMxBeanName), ApplicationMXBean.class); assertEquals(9, applicationMXBean.getSentMessagesCount()); assertEquals(3, applicationMXBean.getBinaryMessageStatisticsMXBean().getSentMessagesCount()); assertEquals(6, applicationMXBean.getTextMessageStatisticsMXBean().getSentMessagesCount()); // check message sizes get monitored properly assertEquals( (TEXT_MESSAGE_1.length() + TEXT_MESSAGE_2.length()) / 2, applicationMXBean.getTextMessageStatisticsMXBean().getAverageSentMessageSize()); assertEquals( BINARY_MESSAGE.limit(), applicationMXBean.getBinaryMessageStatisticsMXBean().getAverageSentMessageSize()); List<EndpointMXBean> endpointMXBeans = applicationMXBean.getEndpointMXBeans(); assertEquals(1, endpointMXBeans.size()); EndpointMXBean endpointMXBean = endpointMXBeans.get(0); assertEquals(9, endpointMXBean.getSentMessagesCount()); assertEquals(3, endpointMXBean.getBinaryMessageStatisticsMXBean().getSentMessagesCount()); assertEquals(6, endpointMXBean.getTextMessageStatisticsMXBean().getSentMessagesCount()); assertEquals( (TEXT_MESSAGE_1.length() + TEXT_MESSAGE_2.length()) / 2, endpointMXBean.getTextMessageStatisticsMXBean().getAverageSentMessageSize()); assertEquals( BINARY_MESSAGE.limit(), endpointMXBean.getBinaryMessageStatisticsMXBean().getAverageSentMessageSize()); List<SessionMXBean> sessionMXBeans = endpointMXBean.getSessionMXBeans(); if (!monitorOnSessionLevel) { assertTrue(sessionMXBeans.isEmpty()); return; } assertEquals(3, sessionMXBeans.size()); for (BaseMXBean sessionMXBean : sessionMXBeans) { assertEquals(3, sessionMXBean.getSentMessagesCount()); assertEquals(1, sessionMXBean.getBinaryMessageStatisticsMXBean().getSentMessagesCount()); assertEquals(2, sessionMXBean.getTextMessageStatisticsMXBean().getSentMessagesCount()); assertEquals( (TEXT_MESSAGE_1.length() + TEXT_MESSAGE_2.length()) / 2, sessionMXBean.getTextMessageStatisticsMXBean().getAverageSentMessageSize()); assertEquals( BINARY_MESSAGE.limit(), sessionMXBean.getBinaryMessageStatisticsMXBean().getAverageSentMessageSize()); } } catch (Exception e) { e.printStackTrace(); fail(); } finally { stopServer(server); } }
/** * Returns an <code>MXBean</code> Proxy for the market data module being tested. * * @return an <code>AbstractMarketDataModuleMXBean</code> value * @throws Exception if an error occurs */ protected final AbstractMarketDataModuleMXBean getMXBeanProxy() throws Exception { ObjectName objectName = getInstanceURN().toObjectName(); MBeanServerConnection mMBeanServer = ModuleTestBase.getMBeanServer(); return JMX.newMXBeanProxy(mMBeanServer, objectName, AbstractMarketDataModuleMXBean.class, true); }