List of usage examples for javax.management MBeanServer isRegistered
public boolean isRegistered(ObjectName name);
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. c o 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:org.camelcookbook.monitoring.managed.ManagedSpringTest.java
@Test public void testManagedResource() throws Exception { final ManagementAgent managementAgent = context.getManagementStrategy().getManagementAgent(); assertNotNull(managementAgent);// ww w .j a v a2 s. co m final MBeanServer mBeanServer = managementAgent.getMBeanServer(); assertNotNull(mBeanServer); final String mBeanServerDefaultDomain = managementAgent.getMBeanServerDefaultDomain(); assertEquals("org.apache.camel", mBeanServerDefaultDomain); final String managementName = context.getManagementName(); assertNotNull("CamelContext should have a management name if JMX is enabled", managementName); LOG.info("managementName = {}", managementName); // Get the Camel Context MBean ObjectName onContext = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/" + managementName + ",type=context,name=\"" + context.getName() + "\""); assertTrue("Should be registered", mBeanServer.isRegistered(onContext)); // Get myManagedBean ObjectName onManagedBean = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/" + managementName + ",type=processors,name=\"myManagedBean\""); LOG.info("Canonical Name = {}", onManagedBean.getCanonicalName()); assertTrue("Should be registered", mBeanServer.isRegistered(onManagedBean)); // Send a couple of messages to get some route statistics template.sendBody("direct:start", "Hello Camel"); template.sendBody("direct:start", "Camel Rocks!"); // Get MBean attribute int camelsSeenCount = (Integer) mBeanServer.getAttribute(onManagedBean, "CamelsSeenCount"); assertEquals(2, camelsSeenCount); // Stop the route via JMX mBeanServer.invoke(onManagedBean, "resetCamelsSeenCount", null, null); camelsSeenCount = (Integer) mBeanServer.getAttribute(onManagedBean, "CamelsSeenCount"); assertEquals(0, camelsSeenCount); }
From source file:org.camelcookbook.monitoring.naming.JmxNamingContextSpringTest.java
@Test public void testNamingContextSpring() throws Exception { final ManagementAgent managementAgent = context.getManagementStrategy().getManagementAgent(); assertNotNull(managementAgent);//from ww w . j av a2s. c o m final MBeanServer mBeanServer = managementAgent.getMBeanServer(); assertNotNull(mBeanServer); final String mBeanServerDefaultDomain = managementAgent.getMBeanServerDefaultDomain(); assertEquals("org.apache.camel", mBeanServerDefaultDomain); final String managementName = context.getManagementName(); assertNotNull("CamelContext should have a management name if JMX is enabled", managementName); LOG.info("managementName = {}", managementName); // Get the Camel Context MBean ObjectName onContext = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/" + managementName + ",type=context,name=\"" + context.getName() + "\""); assertTrue("Should be registered", mBeanServer.isRegistered(onContext)); // Get the first Route MBean by id ObjectName onRoute1 = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/" + managementName + ",type=routes,name=\"first-route\""); LOG.info("Canonical Name = {}", onRoute1.getCanonicalName()); assertTrue("Should be registered", mBeanServer.isRegistered(onRoute1)); // Send a couple of messages to get some route statistics template.sendBody("direct:start", "Hello Camel"); template.sendBody("direct:start", "Camel Rocks!"); // Get an MBean attribute for the number of messages processed assertEquals(2L, mBeanServer.getAttribute(onRoute1, "ExchangesCompleted")); // Get the other Route MBean by id ObjectName onRoute2 = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/" + managementName + ",type=routes,name=\"other-route\""); assertTrue("Should be registered", mBeanServer.isRegistered(onRoute2)); // Get an MBean attribute for the number of messages processed assertEquals(0L, mBeanServer.getAttribute(onRoute2, "ExchangesCompleted")); // Send some messages to the other route template.sendBody("direct:startOther", "Hello Other Camel"); template.sendBody("direct:startOther", "Other Camel Rocks!"); // Verify that the MBean statistics updated correctly assertEquals(2L, mBeanServer.getAttribute(onRoute2, "ExchangesCompleted")); // Check this routes running state assertEquals("Started", mBeanServer.getAttribute(onRoute2, "State")); // Stop the route via JMX mBeanServer.invoke(onRoute2, "stop", null, null); // verify the route now shows its state as stopped assertEquals("Stopped", mBeanServer.getAttribute(onRoute2, "State")); }
From source file:com.cubeia.firebase.server.lobby.systemstate.StateLobby.java
/** * Add MBean info to JMX./*from w w w . ja v a2 s . c om*/ * Will be called from the constructor. * */ private void initJmx() { try { MBeanServer mbs = getMBeanServer(); ObjectName monitorName = new ObjectName("com.cubeia.firebase.lobby:type=SysLobby"); if (!mbs.isRegistered(monitorName)) { mbs.registerMBean(this, monitorName); } } catch (Exception e) { log.error("failed to start JMX for State Lobby", e); } }
From source file:org.jboss.web.tomcat.tc5.session.JBossCacheCluster.java
/** * Gets our TreeCache, either from a local reference or the JMX * server. If one is not found, creates and configures it. *//*from ww w . ja v a 2 s .co m*/ private PojoCacheMBean getTreeCache() throws Exception { if (treeCache == null) { MBeanServer server = getMBeanServer(); ObjectName objName = new ObjectName(treeCacheObjectName); if (server.isRegistered(objName)) { // Get a proxy to the existing TreeCache treeCache = (PojoCacheMBean) MBeanProxyExt.create(PojoCacheMBean.class, objName); } else { // Create our own tree cache treeCache = new PojoCache(); // See if there is an XML descriptor file to configure the cache InputStream configIS = getCacheConfigStream(); if (configIS != null) { PropertyConfigurator config = new PropertyConfigurator(); config.configure(treeCache, configIS); try { configIS.close(); } catch (IOException io) { // ignore } if (clusterName != null) { // Override the XML config with the name provided in // server.xml. Method setClusterName is specified in the // Cluster interface, otherwise we would not do this treeCache.setClusterName(clusterName); } } else { // User did not try to configure the cache. // Configure it using defaults. Only exception // is the clusterName, which user can specify in server.xml. String channelName = (clusterName == null) ? DEFAULT_CLUSTER_NAME : clusterName; treeCache.setClusterName(channelName); treeCache.setIsolationLevel(DEFAULT_ISOLATION_LEVEL); treeCache.setCacheMode(DEFAULT_CACHE_MODE); treeCache.setLockAcquisitionTimeout(DEFAULT_LOCK_TIMEOUT); treeCache.setTransactionManagerLookupClass(DEFAULT_TM_LOOKUP); } treeCacheLocal = true; } } return treeCache; }
From source file:org.red5.server.tomcat.TomcatVHostLoader.java
/** * Initialization./*from w w w. ja va 2 s.com*/ */ @SuppressWarnings("cast") public void init() { 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 = 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(); } 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); } }
From source file:org.camelcookbook.monitoring.naming.JmxNamingPatternSpringTest.java
@Test public void testNamingPatternSpring() throws Exception { final ManagementAgent managementAgent = context.getManagementStrategy().getManagementAgent(); assertNotNull(managementAgent);// w w w.ja v a 2 s . co m final MBeanServer mBeanServer = managementAgent.getMBeanServer(); assertNotNull(mBeanServer); final String mBeanServerDefaultDomain = managementAgent.getMBeanServerDefaultDomain(); assertEquals("org.apache.camel", mBeanServerDefaultDomain); final String managementName = context.getManagementName(); assertNotNull("CamelContext should have a management name if JMX is enabled", managementName); LOG.info("managementName = {}; name = {}", managementName, context.getName()); assertTrue(managementName.startsWith("CustomName")); // Get the Camel Context MBean ObjectName onContext = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/" + managementName + ",type=context,name=\"" + context.getName() + "\""); assertTrue("Should be registered", mBeanServer.isRegistered(onContext)); // Get the first Route MBean by id ObjectName onRoute1 = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/" + managementName + ",type=routes,name=\"first-route\""); LOG.info("Canonical Name = {}", onRoute1.getCanonicalName()); assertTrue("Should be registered", mBeanServer.isRegistered(onRoute1)); // Send a couple of messages to get some route statistics template.sendBody("direct:start", "Hello Camel"); template.sendBody("direct:start", "Camel Rocks!"); // Get an MBean attribute for the number of messages processed assertEquals(2L, mBeanServer.getAttribute(onRoute1, "ExchangesCompleted")); // Get the other Route MBean by id ObjectName onRoute2 = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/" + managementName + ",type=routes,name=\"other-route\""); assertTrue("Should be registered", mBeanServer.isRegistered(onRoute2)); // Get an MBean attribute for the number of messages processed assertEquals(0L, mBeanServer.getAttribute(onRoute2, "ExchangesCompleted")); // Send some messages to the other route template.sendBody("direct:startOther", "Hello Other Camel"); template.sendBody("direct:startOther", "Other Camel Rocks!"); // Verify that the MBean statistics updated correctly assertEquals(2L, mBeanServer.getAttribute(onRoute2, "ExchangesCompleted")); // Check this routes running state assertEquals("Started", mBeanServer.getAttribute(onRoute2, "State")); // Stop the route via JMX mBeanServer.invoke(onRoute2, "stop", null, null); // verify the route now shows its state as stopped assertEquals("Stopped", mBeanServer.getAttribute(onRoute2, "State")); }
From source file:org.red5.server.undertow.UndertowLoader.java
protected void registerJMX() { // register with jmx MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try {/*from w ww.j a va2 s.c o m*/ ObjectName oName = new ObjectName("org.red5.server:type=UndertowLoader"); // check for existing registration before registering if (!mbs.isRegistered(oName)) { mbs.registerMBean(this, oName); } else { log.debug("ContextLoader is already registered in JMX"); } } catch (Exception e) { log.warn("Error on jmx registration", e); } }
From source file:com.web.server.SARDeployer.java
/** * This method undeployed the SAR/*ww w . ja va 2 s. com*/ * @param dir * @return */ public boolean deleteDir(File dir) { String fileName = dir.getName(); System.out.println("Dirname to be deleted" + fileName); Sar sar = null; try { sar = (Sar) sardigester.parse(new InputSource( new FileInputStream(deployDirectory + "/" + fileName + "/META-INF/" + "mbean-service.xml"))); } catch (IOException | SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } URLClassLoader sarClassLoader = (URLClassLoader) sarsMap.get(fileName); if (sarClassLoader != null) { ClassLoaderUtil.closeClassLoader(sarClassLoader); CopyOnWriteArrayList mbeans = sar.getMbean(); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); System.out.println(mbs); ObjectName objName; try { for (int index = 0; index < mbeans.size(); index++) { Mbean mbean = (Mbean) mbeans.get(index); System.out.println(mbean.getObjectname()); System.out.println(mbean.getCls()); objName = new ObjectName(mbean.getObjectname()); if (mbs.isRegistered(objName)) { mbs.invoke(objName, "stopService", null, null); //mbs.invoke(objName, "destroy", null, null); mbs.unregisterMBean(objName); } } sarsMap.remove(fileName); } catch (MalformedObjectNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MBeanRegistrationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstanceNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ReflectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MBeanException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return recursiveDelete(dir); }
From source file:com.web.server.SARDeployer.java
/** * This method extracts the SAR archive and configures for the SAR and starts the services * @param file/*from ww w . j a va 2s .c o m*/ * @param warDirectoryPath * @throws IOException */ public void extractSar(File file, String warDirectoryPath) throws IOException { ZipFile zip = new ZipFile(file); ZipEntry ze = null; String fileName = file.getName(); fileName = fileName.substring(0, fileName.indexOf('.')); fileName += "sar"; String fileDirectory; CopyOnWriteArrayList classPath = new CopyOnWriteArrayList(); Enumeration<? extends ZipEntry> entries = zip.entries(); int numBytes; while (entries.hasMoreElements()) { ze = entries.nextElement(); // //System.out.println("Unzipping " + ze.getName()); String filePath = deployDirectory + "/" + fileName + "/" + ze.getName(); if (!ze.isDirectory()) { fileDirectory = filePath.substring(0, filePath.lastIndexOf('/')); } else { fileDirectory = filePath; } // //System.out.println(fileDirectory); createDirectory(fileDirectory); if (!ze.isDirectory()) { FileOutputStream fout = new FileOutputStream(filePath); byte[] inputbyt = new byte[8192]; InputStream istream = zip.getInputStream(ze); while ((numBytes = istream.read(inputbyt, 0, inputbyt.length)) >= 0) { fout.write(inputbyt, 0, numBytes); } fout.close(); istream.close(); if (ze.getName().endsWith(".jar")) { classPath.add(filePath); } } } zip.close(); URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader(); URL[] urls = loader.getURLs(); WebClassLoader sarClassLoader = new WebClassLoader(urls); for (int index = 0; index < classPath.size(); index++) { System.out.println("file:" + classPath.get(index)); new WebServer().addURL(new URL("file:" + classPath.get(index)), sarClassLoader); } new WebServer().addURL(new URL("file:" + deployDirectory + "/" + fileName + "/"), sarClassLoader); sarsMap.put(fileName, sarClassLoader); System.out.println(sarClassLoader.geturlS()); try { Sar sar = (Sar) sardigester.parse(new InputSource( new FileInputStream(deployDirectory + "/" + fileName + "/META-INF/" + "mbean-service.xml"))); CopyOnWriteArrayList mbeans = sar.getMbean(); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); System.out.println(mbs); ObjectName objName; for (int index = 0; index < mbeans.size(); index++) { Mbean mbean = (Mbean) mbeans.get(index); System.out.println(mbean.getObjectname()); System.out.println(mbean.getCls()); objName = new ObjectName(mbean.getObjectname()); Class helloWorldService = sarClassLoader.loadClass(mbean.getCls()); Object obj = helloWorldService.newInstance(); if (mbs.isRegistered(objName)) { mbs.invoke(objName, "stopService", null, null); //mbs.invoke(objName, "destroy", null, null); mbs.unregisterMBean(objName); } mbs.registerMBean(obj, objName); CopyOnWriteArrayList attrlist = mbean.getMbeanAttribute(); if (attrlist != null) { for (int count = 0; count < attrlist.size(); count++) { MBeanAttribute attr = (MBeanAttribute) attrlist.get(count); Attribute mbeanattribute = new Attribute(attr.getName(), attr.getValue()); mbs.setAttribute(objName, mbeanattribute); } } mbs.invoke(objName, "startService", null, null); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedObjectNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstanceAlreadyExistsException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MBeanRegistrationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NotCompliantMBeanException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstanceNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ReflectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MBeanException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidAttributeValueException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (AttributeNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }