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; }
/** * 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 { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); final Boolean isNotificationSupported = AccessController.doPrivileged( new PrivilegedAction<Boolean>() { public Boolean run() { try { Class cl = Class.forName("sun.management.VMManagementImpl"); Field f = cl.getDeclaredField("gcNotificationSupport"); f.setAccessible(true); return f.getBoolean(null); } catch (ClassNotFoundException e) { return false; } catch (NoSuchFieldException e) { return false; } catch (IllegalAccessException e) { return false; } } }); if (!isNotificationSupported) { System.out.println("GC Notification not supported by the JVM, test skipped"); return; } final ObjectName gcMXBeanPattern = new ObjectName("java.lang:type=GarbageCollector,*"); Set<ObjectName> names = mbs.queryNames(gcMXBeanPattern, null); if (names.isEmpty()) throw new Exception("Test incorrect: no GC MXBeans"); number = names.size(); for (ObjectName n : names) { if (mbs.isInstanceOf(n, "javax.management.NotificationEmitter")) { listenerInvoked.put(n.getCanonicalName(), null); GcListener listener = new GcListener(); mbs.addNotificationListener(n, listener, null, null); } } // Invocation of System.gc() to trigger major GC System.gc(); // Allocation of many short living and small objects to trigger minor GC Object data[] = new Object[32]; for (int i = 0; i < 100000000; i++) { data[i % 32] = new int[8]; } int wakeup = 0; synchronized (synchronizer) { while (count != number) { synchronizer.wait(10000); wakeup++; if (wakeup > 10) break; } } for (GarbageCollectionNotificationInfo notif : listenerInvoked.values()) { checkGarbageCollectionNotificationInfoContent(notif); } System.out.println("Test passed"); }
private static void checkPlatformMBeans() throws Exception { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); Set<ObjectName> mbeanNames = mbs.queryNames(null, null); for (ObjectName name : mbeanNames) { if (!mbs.isInstanceOf(name, NotificationBroadcaster.class.getName())) { System.out.println(name + ": not a NotificationBroadcaster"); } else { MBeanInfo mbi = mbs.getMBeanInfo(name); check(name.toString(), mbi.getNotifications()); } } }
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 synchronized ObjectName uniqueObjectName( MBeanServer server, Object object, String objectName) { if (!objectName.endsWith("=")) { String className = object.getClass().getName(); if (className.indexOf(".") > 0) className = className.substring(className.lastIndexOf(".") + 1); if (className.endsWith("MBean")) className = className.substring(0, className.length() - 5); if (!objectName.endsWith(":")) objectName += ","; objectName += className + "="; } ObjectName oName = null; try { while (true) { Integer id = (Integer) __objectId.get(objectName); if (id == null) id = new Integer(0); oName = new ObjectName(objectName + id); id = new Integer(id.intValue() + 1); __objectId.put(objectName, id); // If no server, this must be unique if (server == null) break; // Otherwise let's check it is unique // if not found then it is unique if (!server.isRegistered(oName)) break; } } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); } return oName; }
private PatternBinding( int hasCode, @NotNull String verb, @Nullable String route, @NotNull Pattern pattern, @Nullable Set<String> paramNames, @NotNull Middleware[] middleware) { this.route = route; this.pattern = pattern; this.paramNames = paramNames; Collections.addAll(this.middleware, middleware); // register on JMX try { objectName = new ObjectName( "com.jetdrone.yoke:type=Route@" + hasCode + ",method=" + verb + ",path=" + ObjectName.quote(route)); } catch (MalformedObjectNameException e) { throw new RuntimeException(e); } try { mbs.registerMBean(new RouteMBean(this.middleware), objectName); } catch (InstanceAlreadyExistsException e) { // ignore } catch (MBeanRegistrationException | NotCompliantMBeanException e) { throw new RuntimeException(e); } }
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); } }
private boolean isModified(ObjectName name) { boolean modified = false; if (name != null) { try { modified = (Boolean) server.getAttribute(name, "Modified"); } catch (Exception e) { // Okay to fail } } return modified; }
private int getState(ObjectName name) { int status = -1; if (name != null) { try { status = (Integer) server.getAttribute(name, "State"); } catch (Exception e) { log.warn("getState", e); } } return status; }
private void addMiddleware(@NotNull Middleware[] middleware) { Collections.addAll(this.middleware, middleware); // un register if present try { mbs.unregisterMBean(objectName); } catch (InstanceNotFoundException e) { // ignore } catch (MBeanRegistrationException e) { throw new RuntimeException(e); } // re register if present try { mbs.registerMBean(new RouteMBean(this.middleware), objectName); } catch (InstanceAlreadyExistsException e) { // ignore } catch (MBeanRegistrationException | NotCompliantMBeanException e) { throw new RuntimeException(e); } }
private long persist(File f, ObjectName name) { long deployed = f.lastModified(); try { Element e = (Element) server.getAttribute(name, "Persist"); if (e != null) { XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); Document doc = new Document(); e.detach(); doc.setRootElement(e); File tmp = new File(f.getAbsolutePath() + ".tmp"); FileWriter writer = new FileWriter(tmp); out.output(doc, writer); writer.close(); f.delete(); tmp.renameTo(f); deployed = f.lastModified(); } } catch (Exception ex) { log.warn("persist", ex); } return deployed; }
public void testMbeans() throws MalformedObjectNameException, BundleException, InstanceNotFoundException, ReflectionException, MBeanException, AttributeNotFoundException { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); ObjectName digraphName = new ObjectName(REGION_DOMAIN_PROP + ":type=RegionDigraph,*"); ObjectName regionNameAllQuery = new ObjectName(REGION_DOMAIN_PROP + ":type=Region,name=*,*"); Set<ObjectInstance> digraphs = server.queryMBeans(null, digraphName); assertEquals("Expected only one instance of digraph", 1, digraphs.size()); Set<ObjectInstance> regions = server.queryMBeans(null, regionNameAllQuery); assertEquals("Expected only one instance of region", 1, regions.size()); Region pp1Region = digraph.createRegion(PP1); Bundle pp1Bundle = bundleInstaller.installBundle(PP1, pp1Region); Region sp1Region = digraph.createRegion(SP1); Bundle sp1Bundle = bundleInstaller.installBundle(SP1, sp1Region); regions = server.queryMBeans(null, regionNameAllQuery); assertEquals("Wrong number of regions", 3, regions.size()); Set<ObjectInstance> pp1Query = server.queryMBeans(null, new ObjectName(REGION_DOMAIN_PROP + ":type=Region,name=" + PP1 + ",*")); assertEquals("Expected only one instance of: " + PP1, 1, pp1Query.size()); Set<ObjectInstance> sp1Query = server.queryMBeans(null, new ObjectName(REGION_DOMAIN_PROP + ":type=Region,name=" + SP1 + ",*")); assertEquals("Expected only one instance of: " + SP1, 1, sp1Query.size()); ObjectName pp1Name = (ObjectName) server.invoke(digraphs.iterator().next().getObjectName(), "getRegion", new Object[] {PP1}, new String[] {String.class.getName()}); assertEquals(PP1 + " regions not equal.", pp1Query.iterator().next().getObjectName(), pp1Name); ObjectName sp1Name = (ObjectName) server.invoke(digraphs.iterator().next().getObjectName(), "getRegion", new Object[] {SP1}, new String[] {String.class.getName()}); assertEquals(SP1 + " regions not equal.", sp1Query.iterator().next().getObjectName(), sp1Name); // test non existing region ObjectName shouldNotExistName = (ObjectName) server.invoke(digraphs.iterator().next().getObjectName(), "getRegion", new Object[] {"ShouldNotExist"}, new String[] {String.class.getName()}); assertNull("Should not exist", shouldNotExistName); long[] bundleIds = (long[]) server.getAttribute(pp1Name, "BundleIds"); assertEquals("Wrong number of bundles", 1, bundleIds.length); assertEquals("Wrong bundle", pp1Bundle.getBundleId(), bundleIds[0]); String name = (String) server.getAttribute(pp1Name, "Name"); assertEquals("Wrong name", PP1, name); bundleIds = (long[]) server.getAttribute(sp1Name, "BundleIds"); assertEquals("Wrong number of bundles", 1, bundleIds.length); assertEquals("Wrong bundle", sp1Bundle.getBundleId(), bundleIds[0]); name = (String) server.getAttribute(sp1Name, "Name"); assertEquals("Wrong name", SP1, name); regionBundle.stop(); // Now make sure we have no mbeans digraphs = server.queryMBeans(digraphName, null); assertEquals("Wrong number of digraphs", 0, digraphs.size()); regions = server.queryMBeans(null, regionNameAllQuery); assertEquals("Wrong number of regions", 0, regions.size()); }
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); } }