private int getHttpsPort() { try { MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0); QueryExp query = Query.eq(Query.attr("Scheme"), Query.value("https")); Set<ObjectName> objectNames = mBeanServer.queryNames(null, query); if (objectNames != null && objectNames.size() > 0) { for (ObjectName objectName : objectNames) { String name = objectName.toString(); if (name.indexOf("port=") > -1) { String[] parts = name.split("port="); String port = parts[1]; try { int portNum = Integer.parseInt(port); return portNum; } catch (NumberFormatException e) { logger.error("Error parsing https port:" + port); return -1; } } } } } catch (Throwable t) { logger.error("Error getting https port:", t); } return -1; }
public void export() { try { // 创建一个MBeanServer MBeanServer mbs = MBeanServerFactory.createMBeanServer(DOMAIN); // MBeanServer mbs = MBeanServerFactory.createMBeanServer();//不能在jconsole中使用 // MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();//可在jconsole中使用 // 用MBeanServer注册LoginStatsMBean // MBeanServer.registerMBean(Object,ObjectName)方法使用的参数有两个:一个是MBean实现的一个实例;另一个是类型ObjectName的一个对象-它用于唯一地标识该MBean mbs.registerMBean(new Status(), new ObjectName(MBeanName)); // 存取该JMX服务的URL: JMXServiceURL url = new JMXServiceURL("rmi", HOST, JMX_PORT, "/jndi/rmi://" + HOST + ":" + 1099 + "/app"); // start()和stop()来启动和停止 JMXConnectorServer JMXConnectorServer jmxServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs); serviceUrl = url.toString(); // 在RMI上注册 LocateRegistry.createRegistry(JMX_PORT); jmxServer.start(); // 创建适配器,用于能够通过浏览器访问MBean // HtmlAdaptorServer adapter = new HtmlAdaptorServer(); // adapter.setPort(9797); // mbs.registerMBean(adapter, new ObjectName( // "MyappMBean:name=htmladapter,port=9797")); // adapter.start(); } catch (Exception e) { e.printStackTrace(); } }
@Test public void checkNotRegistered() throws MalformedObjectNameException { MBeanServer jolokiaServer = JolokiaMBeanServerUtil.getJolokiaMBeanServer(); Assert.assertNotEquals(ManagementFactory.getPlatformMBeanServer(), jolokiaServer); for (MBeanServer server : MBeanServerFactory.findMBeanServer(null)) { Assert.assertNotEquals(server, jolokiaServer); } }
/** * Returns a string array containing the default JMX domains of all available MBeanServers in this * JVM. * * @return a string array of JMX default domains */ public static String[] getMBeanServerDomains() { Set<String> domains = new HashSet<String>(); for (MBeanServer mbs : MBeanServerFactory.findMBeanServer(null)) { String domain = mbs.getDefaultDomain(); if (domain == null) domain = "DefaultDomain"; domains.add(domain); } return domains.toArray(new String[domains.size()]); }
public static void main(String[] args) throws Exception { System.out.println( ">>> Test how for the MBeanServerInvocationHandler to " + "unwrap a user specific exception."); final MBeanServer mbs = MBeanServerFactory.newMBeanServer(); final ObjectName name = new ObjectName("a:b=c"); mbs.registerMBean(new Test(), name); TestMBean proxy = (TestMBean) MBeanServerInvocationHandler.newProxyInstance(mbs, name, TestMBean.class, false); // test the method "getter" System.out.println(">>> Test the method getter to get an IOException."); try { proxy.getIOException(); } catch (IOException e) { System.out.println(">>> Test passed: got expected exception:"); // e.printStackTrace(System.out); } catch (Throwable t) { System.out.println(">>> Test failed: got wrong exception:"); t.printStackTrace(System.out); throw new RuntimeException("Did not get an expected IOException."); } // test the method "setter" System.out.println(">>> Test the method setter to get a RuntimeException."); try { proxy.setRuntimeException("coucou"); } catch (UnsupportedOperationException ue) { System.out.println(">>> Test passed: got expected exception:"); // ue.printStackTrace(System.out); } catch (Throwable t) { System.out.println(">>> Test failed: got wrong exception:"); t.printStackTrace(System.out); throw new RuntimeException("Did not get an expected Runtimeexception."); } // test the method "invoke" System.out.println(">>> Test the method invoke to get an Error."); try { proxy.invokeError(); } catch (AssertionError ae) { System.out.println(">>> Test passed: got expected exception:"); // ue.printStackTrace(System.out); } catch (Throwable t) { System.out.println(">>> Test failed: got wrong exception:"); t.printStackTrace(System.out); throw new RuntimeException("Did not get an expected Error."); } }
public static void main(String[] args) throws Exception { Class thisClass = MethodResultTest.class; Class exoticClass = Exotic.class; String exoticClassName = Exotic.class.getName(); ClassLoader testClassLoader = thisClass.getClassLoader(); if (!(testClassLoader instanceof URLClassLoader)) { System.out.println("TEST INVALID: Not loaded by a " + "URLClassLoader: " + testClassLoader); System.exit(1); } URLClassLoader tcl = (URLClassLoader) testClassLoader; URL[] urls = tcl.getURLs(); ClassLoader shadowLoader = new ShadowLoader( urls, testClassLoader, new String[] { exoticClassName, ExoticMBeanInfo.class.getName(), ExoticException.class.getName() }); Class cl = shadowLoader.loadClass(exoticClassName); if (cl == exoticClass) { System.out.println( "TEST INVALID: Shadow class loader loaded " + "same class as test class loader"); System.exit(1); } Thread.currentThread().setContextClassLoader(shadowLoader); ObjectName on = new ObjectName("a:b=c"); MBeanServer mbs = MBeanServerFactory.newMBeanServer(); mbs.createMBean(Thing.class.getName(), on); final String[] protos = {"rmi", "iiop", "jmxmp"}; boolean ok = true; for (int i = 0; i < protos.length; i++) { try { ok &= test(protos[i], mbs, on); System.out.println(); } catch (Exception e) { System.out.println("TEST FAILED WITH EXCEPTION:"); e.printStackTrace(System.out); ok = false; } } if (ok) System.out.println("Test passed"); else { System.out.println("TEST FAILED"); System.exit(1); } }
public static void main(String[] args) throws Exception { System.out.println( "Test that target MBean class loader is used " + "before JMX Remote API class loader"); ClassLoader jmxRemoteClassLoader = JMXServiceURL.class.getClassLoader(); if (jmxRemoteClassLoader == null) { System.out.println( "JMX Remote API loaded by bootstrap " + "class loader, this test is irrelevant"); return; } if (!(jmxRemoteClassLoader instanceof URLClassLoader)) { System.out.println("TEST INVALID: JMX Remote API not loaded by " + "URLClassLoader"); System.exit(1); } URLClassLoader jrcl = (URLClassLoader) jmxRemoteClassLoader; URL[] urls = jrcl.getURLs(); PrivateMLet mlet = new PrivateMLet(urls, null, false); Class shadowClass = mlet.loadClass(JMXServiceURL.class.getName()); if (shadowClass == JMXServiceURL.class) { System.out.println("TEST INVALID: MLet got original " + "JMXServiceURL not shadow"); System.exit(1); } MBeanServer mbs = MBeanServerFactory.newMBeanServer(); mbs.registerMBean(mlet, mletName); final String[] protos = {"rmi", "iiop", "jmxmp"}; boolean ok = true; for (int i = 0; i < protos.length; i++) { try { ok &= test(protos[i], mbs); } catch (Exception e) { System.out.println("TEST FAILED WITH EXCEPTION:"); e.printStackTrace(System.out); ok = false; } } if (ok) System.out.println("Test passed"); else { System.out.println("TEST FAILED"); System.exit(1); } }
@Test void registerMBean2() throws NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanException, MalformedObjectNameException, AttributeNotFoundException, ReflectionException, InstanceNotFoundException { MBeanServer server = EasyMock.createMock(MBeanServer.class); MBeanServer ret = MBeanServerFactory.newMBeanServer(); ObjectName oName = new ObjectName(JolokiaMBeanServerHolderMBean.OBJECT_NAME); EasyMock.expect(server.registerMBean(EasyMock.anyObject(), EasyMock.eq(oName))) .andThrow(new InstanceAlreadyExistsException()); EasyMock.expect( server.getAttribute( EasyMock.eq(oName), eq(JolokiaMBeanServerUtil.JOLOKIA_MBEAN_SERVER_ATTRIBUTE))) .andReturn(ret); EasyMock.replay(server); MBeanServer m = JolokiaMBeanServerUtil.registerJolokiaMBeanServerHolderMBean(server); Assert.assertEquals(ret, m); }
public class DeadLockTest { private static final String[] protocols = {"rmi", "iiop", "jmxmp"}; private static final MBeanServer mbs = MBeanServerFactory.createMBeanServer(); public static void main(String[] args) { System.out.println(">>> test on a client notification deadlock."); boolean ok = true; for (int i = 0; i < protocols.length; i++) { try { test(protocols[i]); } catch (Exception e) { System.out.println(">>> Test failed for " + protocols[i]); e.printStackTrace(System.out); } } System.out.println(">>> Test passed"); } private static void test(String proto) throws Exception { System.out.println(">>> Test for protocol " + proto); JMXServiceURL u = null; JMXConnectorServer server = null; HashMap env = new HashMap(2); // server will close a client connection after 1 second env.put("jmx.remote.x.server.connection.timeout", "1000"); // disable the client ping env.put("jmx.remote.x.client.connection.check.period", "0"); try { u = new JMXServiceURL(proto, null, 0); server = JMXConnectorServerFactory.newJMXConnectorServer(u, env, mbs); } catch (MalformedURLException e) { System.out.println(">>> Skipping unsupported URL " + proto); } server.start(); JMXServiceURL addr = server.getAddress(); long st = 2000; MyListener myListener; // a cycle to make sure that we test the blocking problem. do { JMXConnector client = JMXConnectorFactory.connect(addr, env); MBeanServerConnection conn = client.getMBeanServerConnection(); myListener = new MyListener(conn); client.addConnectionNotificationListener(myListener, null, null); // wait the server to close the client connection Thread.sleep(st); // makes the listener to do a remote request via the connection // which should be closed by the server. conn.getDefaultDomain(); // allow the listner to have time to work Thread.sleep(100); // get a closed notif, should no block. client.close(); Thread.sleep(100); st += 2000; } while (!myListener.isDone()); server.stop(); } private static class MyListener implements NotificationListener { public MyListener(MBeanServerConnection conn) { this.conn = conn; } public void handleNotification(Notification n, Object h) { if (n instanceof JMXConnectionNotification) { JMXConnectionNotification jcn = (JMXConnectionNotification) n; final String type = jcn.getType(); System.out.println(">>> The listener receives notif with the type:" + type); if (JMXConnectionNotification.CLOSED.equals(type) || JMXConnectionNotification.FAILED.equals(type)) { synchronized (this) { done = false; } try { conn.getDefaultDomain(); } catch (IOException ioe) { // Greate ! } synchronized (this) { done = true; } System.out.println(">>> The listener is not blocked!"); } } } public boolean isDone() { synchronized (this) { return done; } } private boolean done = false; private MBeanServerConnection conn; } }
private static void test(int testno) throws Exception { // com.sun.jmx.trace.TraceImplementation.init(2); Resource resource = new Resource(); Class resourceClass = Resource.class; Class rmmbClass = RequiredModelMBean.class; Method setManagedResource = rmmbClass.getMethod("setManagedResource", new Class[] {Object.class, String.class}); Method sendNotification = rmmbClass.getMethod("sendNotification", new Class[] {Notification.class}); Method addAttributeChangeNL = rmmbClass.getMethod( "addAttributeChangeNotificationListener", new Class[] {NotificationListener.class, String.class, Object.class}); Method getArray = resourceClass.getMethod("getArray", new Class[0]); Method getNumber = resourceClass.getMethod("getNumber", new Class[0]); Method setNumber = resourceClass.getMethod("setNumber", new Class[] {Integer.TYPE}); Method tweakArray = resourceClass.getMethod("tweakArray", new Class[] {Object[].class}); Method addOne = resourceClass.getMethod("addOne", new Class[] {Integer.TYPE}); MBeanServer mbs = MBeanServerFactory.newMBeanServer(); ObjectName on = new ObjectName("a:b=c"); Descriptor attrDescr = new DescriptorSupport(); attrDescr.setField("name", "Array"); attrDescr.setField("descriptorType", "attribute"); attrDescr.setField("getMethod", "getArray"); ModelMBeanAttributeInfo attrInfo = new ModelMBeanAttributeInfo("Array", "array attr", getArray, null, attrDescr); Descriptor attrDescr2 = new DescriptorSupport(); attrDescr2.setField("name", "Number"); attrDescr2.setField("descriptorType", "attribute"); attrDescr2.setField("getMethod", "getNumber"); attrDescr2.setField("setMethod", "setNumber"); ModelMBeanAttributeInfo attrInfo2 = new ModelMBeanAttributeInfo("Number", "number attr", getNumber, setNumber, attrDescr2); Descriptor attrDescr3 = new DescriptorSupport(); attrDescr3.setField("name", "Local"); attrDescr3.setField("descriptorType", "attribute"); attrDescr3.setField("currencyTimeLimit", "" + Integer.MAX_VALUE); ModelMBeanAttributeInfo attrInfo3 = new ModelMBeanAttributeInfo( "Local", "java.lang.String", "local attr", true, true, false, attrDescr3); Descriptor attrDescr4 = new DescriptorSupport(); attrDescr4.setField("name", "Local2"); attrDescr4.setField("descriptorType", "attribute"); ModelMBeanAttributeInfo attrInfo4 = new ModelMBeanAttributeInfo( "Local2", "java.lang.String", "local attr 2", true, true, false, attrDescr4); ModelMBeanAttributeInfo[] attrs = new ModelMBeanAttributeInfo[] {attrInfo, attrInfo2, attrInfo3, attrInfo4}; ModelMBeanOperationInfo operInfo = new ModelMBeanOperationInfo("getArray descr", getArray); ModelMBeanOperationInfo operInfo2 = new ModelMBeanOperationInfo("getNumber descr", getNumber); ModelMBeanOperationInfo operInfo3 = new ModelMBeanOperationInfo("addOne descr", addOne); ModelMBeanOperationInfo operInfo4 = new ModelMBeanOperationInfo("setNumber descr", setNumber); ModelMBeanOperationInfo operInfo5 = new ModelMBeanOperationInfo("tweakArray descr", tweakArray); ModelMBeanOperationInfo operInfoSetManagedResource = new ModelMBeanOperationInfo("setManagedResource descr", setManagedResource); ModelMBeanOperationInfo operInfoSendNotification = new ModelMBeanOperationInfo("sendNotification descr", sendNotification); ModelMBeanOperationInfo operInfoAddAttributeChangeNL = new ModelMBeanOperationInfo("AddAttributeChangeNL descr", addAttributeChangeNL); ModelMBeanOperationInfo[] opers = new ModelMBeanOperationInfo[] { operInfo, operInfo2, operInfo3, operInfo4, operInfo5, operInfoSetManagedResource, operInfoSendNotification, operInfoAddAttributeChangeNL }; ModelMBeanInfo info = new ModelMBeanInfoSupport( Resource.class.getName(), "Resourcish resource", attrs, null, opers, null, null); mbs.createMBean( RequiredModelMBean.class.getName(), on, new Object[] {info}, new String[] {ModelMBeanInfo.class.getName()}); mbs.invoke( on, "setManagedResource", new Object[] {resource, "objectReference"}, new String[] {"java.lang.Object", "java.lang.String"}); switch (testno) { case 0: { /* Check getDescriptors("") on original MBeanInfo */ final Descriptor[] desc = info.getDescriptors(""); checkDescriptors(info, desc, "info.getDescriptors(\"\")"); break; } case 1: { /* Check getDescriptors(null) on original MBeanInfo */ final Descriptor[] desc = info.getDescriptors(null); checkDescriptors(info, desc, "info.getDescriptors(null)"); break; } case 2: { /* Check getDescriptors("") on retrieved MBeanInfo */ final MBeanInfo mbi = mbs.getMBeanInfo(on); final ModelMBeanInfo model = (ModelMBeanInfo) mbi; final Descriptor[] desc = model.getDescriptors(""); checkDescriptors(info, desc, "model.getDescriptors(\"\")"); break; } case 3: { /* Check getDescriptors(null) on retrieved MBeanInfo */ final MBeanInfo mbi = mbs.getMBeanInfo(on); final ModelMBeanInfo model = (ModelMBeanInfo) mbi; final Descriptor[] desc = model.getDescriptors(null); checkDescriptors(info, desc, "model.getDescriptors(null)"); break; } default: System.err.println("UNKNOWN TEST NUMBER " + testno); break; } }
public void run() { started = true; Thread.currentThread().setName("Q2-" + getInstanceId().toString()); try { /* * The following code determines whether a MBeanServer exists * already. If so then the first one in the list is used. * I have not yet find a way to interrogate the server for * information other than MBeans so to pick a specific one * would be difficult. */ ArrayList mbeanServerList = MBeanServerFactory.findMBeanServer(null); if (mbeanServerList.isEmpty()) { server = MBeanServerFactory.createMBeanServer(JMX_NAME); } else { server = (MBeanServer) mbeanServerList.get(0); } final ObjectName loaderName = new ObjectName(Q2_CLASS_LOADER); try { loader = (QClassLoader) java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public Object run() { return new QClassLoader(server, libDir, loaderName, mainClassLoader); } }); server.registerMBean(loader, loaderName); loader = loader.scan(false); } catch (Throwable t) { if (log != null) log.error("initial-scan", t); else t.printStackTrace(); } factory = new QFactory(loaderName, this); initSystemLogger(); addShutdownHook(); q2Thread = Thread.currentThread(); q2Thread.setContextClassLoader(loader); if (cli != null) cli.start(); initConfigDecorator(); for (int i = 1; !shutdown; i++) { try { boolean forceNewClassLoader = scan(); QClassLoader oldClassLoader = loader; loader = loader.scan(forceNewClassLoader); if (loader != oldClassLoader) { oldClassLoader = null; // We want't this to be null so it gets GCed. System.gc(); // force a GC log.info( "new classloader [" + Integer.toString(loader.hashCode(), 16) + "] has been created"); } deploy(); checkModified(); relax(SCAN_INTERVAL); if (i % (3600000 / SCAN_INTERVAL) == 0) logVersion(); } catch (Throwable t) { log.error("start", t); relax(); } } undeploy(); try { server.unregisterMBean(loaderName); } catch (InstanceNotFoundException e) { log.error(e); } if (decorator != null) { decorator.uninitialize(); } if (exit && !shuttingDown) System.exit(0); } catch (Exception e) { if (log != null) log.error(e); else e.printStackTrace(); System.exit(1); } }
/** Constructs a Server object. Creates a new MBeanServer. */ public Server() { mbs = MBeanServerFactory.createMBeanServer(); }