Java Code Examples for javax.management.remote.JMXConnector#close()

The following examples show how to use javax.management.remote.JMXConnector#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ListenerScaleTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    Sender sender = new Sender();
    mbs.registerMBean(sender, testObjectName);
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");
    JMXConnectorServer cs =
        JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    cs.start();
    JMXServiceURL addr = cs.getAddress();
    JMXConnector cc = JMXConnectorFactory.connect(addr);
    try {
        test(mbs, cs, cc);
    } finally {
        cc.close();
        cs.stop();
    }
}
 
Example 2
Source File: RMIDownloadTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private static void testWithException(boolean send)
throws Exception {
    ClassLoader zoobyCL = new ZoobyClassLoader();
    Class<?> zoobyClass = Class.forName("Zooby", false, zoobyCL);
    Object zooby = zoobyClass.newInstance();

    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///");
    JMXConnectorServer cs =
            JMXConnectorServerFactory.newJMXConnectorServer(url, null, pmbs);
    cs.start();
    JMXServiceURL addr = cs.getAddress();
    JMXConnector cc = JMXConnectorFactory.connect(addr);
    MBeanServerConnection mbsc = cc.getMBeanServerConnection();

    Object rzooby;
    if (send) {
        System.out.println("Sending object...");
        mbsc.setAttribute(getSetName, new Attribute("It", zooby));
        rzooby = getSetInstance.getIt();
    } else {
        System.out.println("Receiving object...");
        getSetInstance.setIt(zooby);
        rzooby = mbsc.getAttribute(getSetName, "It");
    }

    if (!rzooby.getClass().getName().equals("Zooby")) {
        throw new Exception("FAILED: remote object is not a Zooby");
    }
    if (rzooby.getClass().getClassLoader() ==
            zooby.getClass().getClassLoader()) {
        throw new Exception("FAILED: same class loader: " +
                zooby.getClass().getClassLoader());
    }

    cc.close();
    cs.stop();
}
 
Example 3
Source File: IIOPURLTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    JMXServiceURL inputAddr =
        new JMXServiceURL("service:jmx:iiop://");
    JMXConnectorServer s;
    try {
        s = JMXConnectorServerFactory.newJMXConnectorServer(inputAddr, null, null);
    } catch (java.net.MalformedURLException x) {
        try {
            Class.forName("javax.management.remote.rmi._RMIConnectionImpl_Tie");
            throw new RuntimeException("MalformedURLException thrown but iiop appears to be supported");
        } catch (ClassNotFoundException expected) { }
        System.out.println("IIOP protocol not supported, test skipped");
        return;
    }
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();
    mbs.registerMBean(s, new ObjectName("a:b=c"));
    s.start();
    JMXServiceURL outputAddr = s.getAddress();
    if (!outputAddr.getURLPath().startsWith("/ior/IOR:")) {
        throw new RuntimeException("URL path should start with \"/ior/IOR:\": " +
                                   outputAddr);
    }
    System.out.println("IIOP URL path looks OK: " + outputAddr);
    JMXConnector c = JMXConnectorFactory.connect(outputAddr);
    System.out.println("Successfully got default domain: " +
                       c.getMBeanServerConnection().getDefaultDomain());
    c.close();
    s.stop();
}
 
Example 4
Source File: MonitoringClient.java    From javasimon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
	 * Entry point to this monitoring client.
	 *
	 * @param args host:port part of the JMX connector server
	 * @throws java.io.IOException thrown in case of some I/O exception
	 * @throws javax.management.MalformedObjectNameException thrown when the name of the JMX object is incorrect
	 */
	public static void main(String[] args) throws IOException, MalformedObjectNameException {
		final JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + args[0] + "/jmxrmi");

//		final Map<String, String[]> env = new HashMap<String, String[]>();
//		env.put(JMXConnector.CREDENTIALS, new String[]{login, pass});

		JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
		MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
		SimonManagerMXBean simonManagerMXBean = JMX.newMXBeanProxy(mbsc, new ObjectName("org.javasimon.jmx.example:type=Simon"), SimonManagerMXBean.class);

		System.out.println("List of retrieved Simons:");
		for (String n : simonManagerMXBean.getSimonNames()) {
			System.out.println("  " + n);
		}

		System.out.println("List of stopwatch Simons:");
		for (SimonInfo si : simonManagerMXBean.getSimonInfos()) {
			if (si.getType().equals(SimonInfo.STOPWATCH)) {
				System.out.println("  " + si.getName());
			}
		}

		simonManagerMXBean.printSimonTree();

		jmxc.close();
	}
 
Example 5
Source File: IIOPURLTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    JMXServiceURL inputAddr =
        new JMXServiceURL("service:jmx:iiop://");
    JMXConnectorServer s;
    try {
        s = JMXConnectorServerFactory.newJMXConnectorServer(inputAddr, null, null);
    } catch (java.net.MalformedURLException x) {
        try {
            Class.forName("javax.management.remote.rmi._RMIConnectionImpl_Tie");
            throw new RuntimeException("MalformedURLException thrown but iiop appears to be supported");
        } catch (ClassNotFoundException expected) { }
        System.out.println("IIOP protocol not supported, test skipped");
        return;
    }
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();
    mbs.registerMBean(s, new ObjectName("a:b=c"));
    s.start();
    JMXServiceURL outputAddr = s.getAddress();
    if (!outputAddr.getURLPath().startsWith("/ior/IOR:")) {
        throw new RuntimeException("URL path should start with \"/ior/IOR:\": " +
                                   outputAddr);
    }
    System.out.println("IIOP URL path looks OK: " + outputAddr);
    JMXConnector c = JMXConnectorFactory.connect(outputAddr);
    System.out.println("Successfully got default domain: " +
                       c.getMBeanServerConnection().getDefaultDomain());
    c.close();
    s.stop();
}
 
Example 6
Source File: RMIDownloadTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void testWithException(boolean send)
throws Exception {
    ClassLoader zoobyCL = new ZoobyClassLoader();
    Class<?> zoobyClass = Class.forName("Zooby", false, zoobyCL);
    Object zooby = zoobyClass.newInstance();

    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///");
    JMXConnectorServer cs =
            JMXConnectorServerFactory.newJMXConnectorServer(url, null, pmbs);
    cs.start();
    JMXServiceURL addr = cs.getAddress();
    JMXConnector cc = JMXConnectorFactory.connect(addr);
    MBeanServerConnection mbsc = cc.getMBeanServerConnection();

    Object rzooby;
    if (send) {
        System.out.println("Sending object...");
        mbsc.setAttribute(getSetName, new Attribute("It", zooby));
        rzooby = getSetInstance.getIt();
    } else {
        System.out.println("Receiving object...");
        getSetInstance.setIt(zooby);
        rzooby = mbsc.getAttribute(getSetName, "It");
    }

    if (!rzooby.getClass().getName().equals("Zooby")) {
        throw new Exception("FAILED: remote object is not a Zooby");
    }
    if (rzooby.getClass().getClassLoader() ==
            zooby.getClass().getClassLoader()) {
        throw new Exception("FAILED: same class loader: " +
                zooby.getClass().getClassLoader());
    }

    cc.close();
    cs.stop();
}
 
Example 7
Source File: ResourceManagerJMXTest.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private void simultaneousRMIAndROConnections(Credentials adminCreds, JMXServiceURL jmxRmiServiceURL,
        JMXServiceURL jmxRoServiceURL) throws IOException {
    // Test simultaneous RMI and RO connections
    RMTHelper.log("Test simultaneous JMX-RMI and JMX-RO connections as admin");
    final HashMap<String, Object> env = new HashMap<>(1);
    env.put(JMXConnector.CREDENTIALS, new Object[] { TestUsers.TEST.username, adminCreds });
    // Connect to the JMX-RMI Connector Server
    final JMXConnector jmxRmiConnector = JMXConnectorFactory.connect(jmxRmiServiceURL, env);
    final MBeanServerConnection conRmi = jmxRmiConnector.getMBeanServerConnection();

    // Connect to the JMX-RO Connector Server
    env.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, JMXProviderUtils.RO_PROVIDER_PKGS);
    final JMXConnector jmxRoConnector1 = JMXConnectorFactory.connect(jmxRoServiceURL, env);
    final MBeanServerConnection conRo = jmxRoConnector1.getMBeanServerConnection();

    assertFalse("In case of simultaneous RMI and RO JMX connections they must not be equal", conRmi.equals(conRo));

    assertFalse("In case of simultaneous RMI and RO JMX connections the connectors must not provide the same " +
                "connection ids", jmxRmiConnector.getConnectionId().equals(jmxRoConnector1.getConnectionId()));

    RMTHelper.log("Test JMX-RO connection unicity (two connections over RO must not have the same " + "id)");
    final JMXConnector jmxRoConnector2 = JMXConnectorFactory.connect(jmxRoServiceURL, env);
    assertFalse("In case of multiple RO JMX connections the connectors must not provide the same connection " +
                "ids", jmxRoConnector1.getConnectionId().equals(jmxRoConnector2.getConnectionId()));

    // Close all connectors
    jmxRoConnector2.close();
    jmxRoConnector1.close();
    jmxRmiConnector.close();
}
 
Example 8
Source File: IIOPURLTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    JMXServiceURL inputAddr =
        new JMXServiceURL("service:jmx:iiop://");
    JMXConnectorServer s;
    try {
        s = JMXConnectorServerFactory.newJMXConnectorServer(inputAddr, null, null);
    } catch (java.net.MalformedURLException x) {
        try {
            Class.forName("javax.management.remote.rmi._RMIConnectionImpl_Tie");
            throw new RuntimeException("MalformedURLException thrown but iiop appears to be supported");
        } catch (ClassNotFoundException expected) { }
        System.out.println("IIOP protocol not supported, test skipped");
        return;
    }
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();
    mbs.registerMBean(s, new ObjectName("a:b=c"));
    s.start();
    JMXServiceURL outputAddr = s.getAddress();
    if (!outputAddr.getURLPath().startsWith("/ior/IOR:")) {
        throw new RuntimeException("URL path should start with \"/ior/IOR:\": " +
                                   outputAddr);
    }
    System.out.println("IIOP URL path looks OK: " + outputAddr);
    JMXConnector c = JMXConnectorFactory.connect(outputAddr);
    System.out.println("Successfully got default domain: " +
                       c.getMBeanServerConnection().getDefaultDomain());
    c.close();
    s.stop();
}
 
Example 9
Source File: MapNullValuesTest.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
private int jmxConnectorFactoryTests() {
    int errorCount = 0;
    echo("");
    echo(dashedMessage("Run JMXConnectorFactory Tests"));
    for (int i = 0; i < maps.length - 1; i++) {
        echo("\n>>> JMXConnectorFactory Test [" + i + "]");
        try {
            echo("\tMap = " + maps[i]);
            echo("\tCreate the MBean server");
            MBeanServer mbs = MBeanServerFactory.createMBeanServer();
            echo("\tCreate the RMI connector server");
            JMXServiceURL url =
                new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:" +
                                  port + "/JMXConnectorFactory" + i);
            JMXConnectorServer jmxcs =
                JMXConnectorServerFactory.newJMXConnectorServer(url,
                                                                null,
                                                                mbs);
            echo("\tStart the RMI connector server");
            jmxcs.start();
            echo("\tCreate and connect the RMI connector");
            JMXConnector jmxc =
                JMXConnectorFactory.connect(jmxcs.getAddress(), maps[i]);
            echo("\tClose the RMI connector");
            jmxc.close();
            echo("\tTest [" + i + "] PASSED!");
        } catch (Exception e) {
            errorCount++;
            echo("\tTest [" + i + "] FAILED!");
            e.printStackTrace(System.out);
        }
    }
    if (errorCount == 0) {
        echo("");
        echo(dashedMessage("JMXConnectorFactory Tests PASSED!"));
    } else {
        echo("");
        echo(dashedMessage("JMXConnectorFactory Tests FAILED!"));
    }
    return errorCount;
}
 
Example 10
Source File: RMIConnectorInternalMapTest.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.out.println("---RMIConnectorInternalMapTest starting...");

    JMXConnectorServer connectorServer = null;
    JMXConnector connectorClient = null;

    try {
        MBeanServer mserver = ManagementFactory.getPlatformMBeanServer();
        JMXServiceURL serverURL = new JMXServiceURL("rmi", "localhost", 0);
        connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(serverURL, null, mserver);
        connectorServer.start();

        JMXServiceURL serverAddr = connectorServer.getAddress();
        connectorClient = JMXConnectorFactory.connect(serverAddr, null);
        connectorClient.connect();

        Field rmbscMapField = RMIConnector.class.getDeclaredField("rmbscMap");
        rmbscMapField.setAccessible(true);
        Map<Subject, WeakReference<MBeanServerConnection>> map =
                (Map<Subject, WeakReference<MBeanServerConnection>>) rmbscMapField.get(connectorClient);
        if (map != null && !map.isEmpty()) { // failed
            throw new RuntimeException("RMIConnector's rmbscMap must be empty at the initial time.");
        }

        Subject delegationSubject =
                new Subject(true,
                Collections.singleton(new JMXPrincipal("delegate")),
                Collections.EMPTY_SET,
                Collections.EMPTY_SET);
        MBeanServerConnection mbsc1 =
                connectorClient.getMBeanServerConnection(delegationSubject);
        MBeanServerConnection mbsc2 =
                connectorClient.getMBeanServerConnection(delegationSubject);

        if (mbsc1 == null) {
            throw new RuntimeException("Got null connection.");
        }
        if (mbsc1 != mbsc2) {
            throw new RuntimeException("Not got same connection with a same subject.");
        }

        map = (Map<Subject, WeakReference<MBeanServerConnection>>) rmbscMapField.get(connectorClient);
        if (map == null || map.isEmpty()) { // failed
            throw new RuntimeException("RMIConnector's rmbscMap has wrong size "
                    + "after creating a delegated connection.");
        }

        delegationSubject = null;
        mbsc1 = null;
        mbsc2 = null;

        int i = 0;
        while (!map.isEmpty() && i++ < 60) {
            System.gc();
            Thread.sleep(100);
        }
        System.out.println("---GC times: " + i);

        if (!map.isEmpty()) {
            throw new RuntimeException("Failed to clean RMIConnector's rmbscMap");
        } else {
            System.out.println("---RMIConnectorInternalMapTest: PASSED!");
        }
    } finally {
        try {
            connectorClient.close();
            connectorServer.stop();
        } catch (Exception e) {
        }
    }
}
 
Example 11
Source File: UnserializableTargetObjectTest.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    ObjectName name = new ObjectName("a:b=c");
    Resource resource1 = new Resource();
    Resource resource2 = new Resource();
    Resource resource3 = new Resource();
    Method operationMethod = Resource.class.getMethod("operation");
    Method getCountMethod = Resource.class.getMethod("getCount");
    Method setCountMethod = Resource.class.getMethod("setCount", int.class);
    Descriptor operationDescriptor =
        new DescriptorSupport(new String[] {
                                "descriptorType", "name", "targetObject"
                              }, new Object[] {
                                "operation", "operation", resource1
                              });
    Descriptor getCountDescriptor =
        new DescriptorSupport(new String[] {
                                "descriptorType", "name", "targetObject"
                              }, new Object[] {
                                "operation", "getCount", resource2
                              });
    Descriptor setCountDescriptor =
        new DescriptorSupport(new String[] {
                                "descriptorType", "name", "targetObject"
                              }, new Object[] {
                                "operation", "setCount", resource2
                              });
    Descriptor countDescriptor =
        new DescriptorSupport(new String[] {
                                "descriptorType", "name", "getMethod", "setMethod"
                              }, new Object[] {
                                "attribute", "Count", "getCount", "setCount"
                              });
    ModelMBeanOperationInfo operationInfo =
        new ModelMBeanOperationInfo("operation description",
                                    operationMethod, operationDescriptor);
    ModelMBeanOperationInfo getCountInfo =
        new ModelMBeanOperationInfo("getCount description",
                                    getCountMethod, getCountDescriptor);
    ModelMBeanOperationInfo setCountInfo =
        new ModelMBeanOperationInfo("setCount description",
                                    setCountMethod, setCountDescriptor);
    ModelMBeanAttributeInfo countInfo =
        new ModelMBeanAttributeInfo("Count", "Count description",
                                    getCountMethod, setCountMethod,
                                    countDescriptor);
    ModelMBeanInfo mmbi =
        new ModelMBeanInfoSupport(Resource.class.getName(),
                                  "ModelMBean to test targetObject",
                                  new ModelMBeanAttributeInfo[] {countInfo},
                                  null,  // no constructors
                                  new ModelMBeanOperationInfo[] {
                                      operationInfo, getCountInfo, setCountInfo
                                  },
                                  null); // no notifications
    ModelMBean mmb = new RequiredModelMBean(mmbi);
    mmb.setManagedResource(resource3, "ObjectReference");
    mbs.registerMBean(mmb, name);
    mbs.invoke(name, "operation", null, null);
    mbs.setAttribute(name, new Attribute("Count", 53));
    if (resource1.operationCount != 1)
        throw new Exception("operationCount: " + resource1.operationCount);
    if (resource2.count != 53)
        throw new Exception("count: " + resource2.count);
    int got = (Integer) mbs.getAttribute(name, "Count");
    if (got != 53)
        throw new Exception("got count: " + got);

    JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
    JMXConnectorServer cs =
        JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    cs.start();
    JMXServiceURL addr = cs.getAddress();
    JMXConnector cc = JMXConnectorFactory.connect(addr);
    MBeanServerConnection mbsc = cc.getMBeanServerConnection();
    ModelMBeanInfo rmmbi = (ModelMBeanInfo) mbsc.getMBeanInfo(name);
    // Above gets NotSerializableException if resource included in
    // serialized form
    cc.close();
    cs.stop();
    System.out.println("TEST PASSED");
}
 
Example 12
Source File: RMIExitTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private static void test() {
    try {
        JMXServiceURL u = new JMXServiceURL("rmi", null, 0);
        JMXConnectorServer server;
        JMXServiceURL addr;
        JMXConnector client;
        MBeanServerConnection mserver;

        final ObjectName delegateName =
            new ObjectName("JMImplementation:type=MBeanServerDelegate");
        final NotificationListener dummyListener =
            new NotificationListener() {
                    public void handleNotification(Notification n,
                                                   Object o) {
                        // do nothing
                        return;
                    }
                };

        server = JMXConnectorServerFactory.newJMXConnectorServer(u,
                                                                 null,
                                                                 mbs);
        server.start();

        addr = server.getAddress();
        client = JMXConnectorFactory.newJMXConnector(addr, null);
        client.connect(null);

        mserver = client.getMBeanServerConnection();
        String s1 = "1";
        String s2 = "2";
        String s3 = "3";

        mserver.addNotificationListener(delegateName,
                                        dummyListener, null, s1);
        mserver.addNotificationListener(delegateName,
                                        dummyListener, null, s2);
        mserver.addNotificationListener(delegateName,
                                        dummyListener, null, s3);

        mserver.removeNotificationListener(delegateName,
                                           dummyListener, null, s3);
        mserver.removeNotificationListener(delegateName,
                                           dummyListener, null, s2);
        mserver.removeNotificationListener(delegateName,
                                           dummyListener, null, s1);
        client.close();

        server.stop();
    } catch (Exception e) {
        System.out.println(e);
        e.printStackTrace();
        System.exit(1);
    }
}
 
Example 13
Source File: MXBeanInteropTest1.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public void run(Map<String, Object> args) {

        System.out.println("MXBeanInteropTest1::run: Start") ;
        int errorCount = 0 ;

        try {
            // JMX MbeanServer used inside single VM as if remote.
            // MBeanServer mbs = MBeanServerFactory.newMBeanServer();
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

            JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
            JMXConnectorServer cs =
                JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
            cs.start();

            JMXServiceURL addr = cs.getAddress();
            JMXConnector cc = JMXConnectorFactory.connect(addr);
            MBeanServerConnection mbsc = cc.getMBeanServerConnection();

            // Print out registered java.lang.management MXBeans found
            // in the remote jvm.
            printMBeans(mbsc) ;

            // For each possible kind of JDK 5 defined MXBean, we retrieve its
            // MBeanInfo and print it and we call all getters and print
            // their output.
            errorCount += doClassLoadingMXBeanTest(mbsc) ;
            errorCount += doMemoryMXBeanTest(mbsc) ;
            errorCount += doThreadMXBeanTest(mbsc) ;
            errorCount += doRuntimeMXBeanTest(mbsc) ;
            errorCount += doOperatingSystemMXBeanTest(mbsc) ;
            errorCount += doCompilationMXBeanTest(mbsc) ;
            errorCount += doGarbageCollectorMXBeanTest(mbsc) ;
            errorCount += doMemoryManagerMXBeanTest(mbsc) ;
            errorCount += doMemoryPoolMXBeanTest(mbsc) ;

            // Terminate the JMX Client
            cc.close();

        } catch(Exception e) {
            Utils.printThrowable(e, true) ;
            throw new RuntimeException(e);
        }

        if ( errorCount == 0 ) {
            System.out.println("MXBeanInteropTest1::run: Done without any error") ;
        } else {
            System.out.println("MXBeanInteropTest1::run: Done with "
                    + errorCount
                    + " error(s)") ;
            throw new RuntimeException("errorCount = " + errorCount);
        }
    }
 
Example 14
Source File: MXBeanInteropTest2.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public void run(Map<String, Object> args) {

        System.out.println("MXBeanInteropTest2::run: Start") ;
        int errorCount = 0 ;

        try {
            // JMX MbeanServer used inside single VM as if remote.
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

            JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
            JMXConnectorServer cs =
                JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
            cs.start();

            JMXServiceURL addr = cs.getAddress();
            JMXConnector cc = JMXConnectorFactory.connect(addr);
            MBeanServerConnection mbsc = cc.getMBeanServerConnection();

            // Prints all MBeans whatever the domain is.
            printMBeans(mbsc) ;

            // Call test body
            errorCount += doBasicMXBeanTest(mbsc) ;

            // Terminate the JMX Client
            cc.close();

        } catch(Exception e) {
            Utils.printThrowable(e, true) ;
            throw new RuntimeException(e);
        }

        if ( errorCount == 0 ) {
            System.out.println("MXBeanInteropTest2::run: Done without any error") ;
        } else {
            System.out.println("MXBeanInteropTest2::run: Done with "
                    + errorCount
                    + " error(s)") ;
            throw new RuntimeException("errorCount = " + errorCount);
        }
    }
 
Example 15
Source File: MXBeanWeirdParamTest.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String args[]) throws Exception {

            int errorCount = 0 ;
            String msgTag = "ClientSide::main: ";

            try {

                // Get a connection to remote mbean server
                JMXServiceURL addr = new JMXServiceURL(args[0]);
                JMXConnector cc = JMXConnectorFactory.connect(addr);
                MBeanServerConnection mbsc = cc.getMBeanServerConnection();

                // ----
                System.out.println(msgTag + "Create and register the MBean");
                ObjectName objName = new ObjectName("sqe:type=Basic,protocol=rmi") ;
                mbsc.createMBean(BASIC_MXBEAN_CLASS_NAME, objName);
                System.out.println(msgTag +"---- OK\n") ;

                // ----
                System.out.println(msgTag +"Get attribute SqeParameterAtt on our MXBean");
                Object result = mbsc.getAttribute(objName, "SqeParameterAtt");
                System.out.println(msgTag +"(OK) Got result of class "
                        + result.getClass().getName());
                System.out.println(msgTag +"Received CompositeData is " + result);
                System.out.println(msgTag +"---- OK\n") ;

                // ----
                // We use the value returned by getAttribute to perform the invoke.
                System.out.println(msgTag +"Call operation doWeird on our MXBean [1]");
                mbsc.invoke(objName, "doWeird",
                        new Object[]{result},
                        new String[]{"javax.management.openmbean.CompositeData"});
                System.out.println(msgTag +"---- OK\n") ;

                // ----
                // We build the CompositeData ourselves that time.
                System.out.println(msgTag +"Call operation doWeird on our MXBean [2]");
                String typeName = "SqeParameter";
                String[] itemNames = new String[] {"glop"};
                OpenType<?>[] openTypes = new OpenType<?>[] {SimpleType.STRING};
                CompositeType rowType = new CompositeType(typeName, typeName,
                        itemNames, itemNames, openTypes);
                Object[] itemValues = {"HECTOR"};
                CompositeData data =
                        new CompositeDataSupport(rowType, itemNames, itemValues);
                TabularType tabType = new TabularType(typeName, typeName,
                        rowType, new String[]{"glop"});
                TabularDataSupport tds = new TabularDataSupport(tabType);
                tds.put(data);
                System.out.println(msgTag +"Source CompositeData is " + data);
                mbsc.invoke(objName, "doWeird",
                        new Object[]{data},
                        new String[]{"javax.management.openmbean.CompositeData"});
                System.out.println(msgTag +"---- OK\n") ;

                // ----
                System.out.println(msgTag +"Unregister the MBean");
                mbsc.unregisterMBean(objName);
                System.out.println(msgTag +"---- OK\n") ;

                // Terminate the JMX Client
                cc.close();

            } catch(Exception e) {
                Utils.printThrowable(e, true) ;
                errorCount++;
                throw new RuntimeException(e);
            } finally {
                System.exit(errorCount);
            }
        }
 
Example 16
Source File: JMXReporterTest.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * Verifies that we can connect to multiple JMXReporters running on the same machine.
 *
 * @throws Exception
 */
@Test
public void testJMXAvailability() throws Exception {
	ReporterSetup reporterSetup1 = ReporterSetup.forReporter("test1", new JMXReporter("9040-9055"));
	ReporterSetup reporterSetup2 = ReporterSetup.forReporter("test2", new JMXReporter("9040-9055"));

	MetricRegistryImpl reg = new MetricRegistryImpl(
		MetricRegistryConfiguration.defaultMetricRegistryConfiguration(),
		Arrays.asList(reporterSetup1, reporterSetup2));

	TaskManagerMetricGroup mg = new TaskManagerMetricGroup(reg, "host", "tm");

	List<MetricReporter> reporters = reg.getReporters();

	assertTrue(reporters.size() == 2);

	MetricReporter rep1 = reporters.get(0);
	MetricReporter rep2 = reporters.get(1);

	Gauge<Integer> g1 = new Gauge<Integer>() {
		@Override
		public Integer getValue() {
			return 1;
		}
	};
	Gauge<Integer> g2 = new Gauge<Integer>() {
		@Override
		public Integer getValue() {
			return 2;
		}
	};

	rep1.notifyOfAddedMetric(g1, "rep1", new FrontMetricGroup<>(createReporterScopedSettings(0), mg));

	rep2.notifyOfAddedMetric(g2, "rep2", new FrontMetricGroup<>(createReporterScopedSettings(1), mg));

	ObjectName objectName1 = new ObjectName(JMX_DOMAIN_PREFIX + "taskmanager.rep1", JMXReporter.generateJmxTable(mg.getAllVariables()));
	ObjectName objectName2 = new ObjectName(JMX_DOMAIN_PREFIX + "taskmanager.rep2", JMXReporter.generateJmxTable(mg.getAllVariables()));

	JMXServiceURL url1 = new JMXServiceURL("service:jmx:rmi://localhost:" + ((JMXReporter) rep1).getPort().get() + "/jndi/rmi://localhost:" + ((JMXReporter) rep1).getPort().get() + "/jmxrmi");
	JMXConnector jmxCon1 = JMXConnectorFactory.connect(url1);
	MBeanServerConnection mCon1 = jmxCon1.getMBeanServerConnection();

	assertEquals(1, mCon1.getAttribute(objectName1, "Value"));
	assertEquals(2, mCon1.getAttribute(objectName2, "Value"));

	jmxCon1.close();

	JMXServiceURL url2 = new JMXServiceURL("service:jmx:rmi://localhost:" + ((JMXReporter) rep2).getPort().get() + "/jndi/rmi://localhost:" + ((JMXReporter) rep2).getPort().get() + "/jmxrmi");
	JMXConnector jmxCon2 = JMXConnectorFactory.connect(url2);
	MBeanServerConnection mCon2 = jmxCon2.getMBeanServerConnection();

	assertEquals(1, mCon2.getAttribute(objectName1, "Value"));
	assertEquals(2, mCon2.getAttribute(objectName2, "Value"));

	rep1.notifyOfRemovedMetric(g1, "rep1", null);
	rep1.notifyOfRemovedMetric(g2, "rep2", null);

	jmxCon2.close();

	rep1.close();
	rep2.close();
	mg.close();
	reg.shutdown().get();
}
 
Example 17
Source File: JmxServerControlTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testListConsumers() throws Exception {
   // Without this, the RMI server would bind to the default interface IP (the user's local IP mostly)
   System.setProperty("java.rmi.server.hostname", JMX_SERVER_HOSTNAME);

   // I don't specify both ports here manually on purpose. See actual RMI registry connection port extraction below.
   String urlString = "service:jmx:rmi:///jndi/rmi://" + JMX_SERVER_HOSTNAME + ":" + JMX_SERVER_PORT + "/jmxrmi";

   JMXServiceURL url = new JMXServiceURL(urlString);
   JMXConnector jmxConnector = null;

   try {
      jmxConnector = JMXConnectorFactory.connect(url);
      System.out.println("Successfully connected to: " + urlString);
   } catch (Exception e) {
      jmxConnector = null;
      e.printStackTrace();
      Assert.fail(e.getMessage());
   }

   try {
      MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection();
      String brokerName = "0.0.0.0";  // configured e.g. in broker.xml <broker-name> element
      ObjectNameBuilder objectNameBuilder = ObjectNameBuilder.create(ActiveMQDefaultConfiguration.getDefaultJmxDomain(), brokerName, true);
      ActiveMQServerControl activeMQServerControl = MBeanServerInvocationHandler.newProxyInstance(mBeanServerConnection, objectNameBuilder.getActiveMQServerObjectName(), ActiveMQServerControl.class, false);

      String addressName = "test_list_consumers_address";
      String queueName = "test_list_consumers_queue";
      activeMQServerControl.createAddress(addressName, RoutingType.ANYCAST.name());
      activeMQServerControl.createQueue(new QueueConfiguration(queueName).setAddress(addressName).setRoutingType(RoutingType.ANYCAST).toJSON());
      String uri = "tcp://localhost:61616";
      try (ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactory(uri, null)) {
         MessageConsumer consumer = cf.createConnection().createSession(true, Session.SESSION_TRANSACTED).createConsumer(new ActiveMQQueue(queueName));

         try {
            String options = JsonUtil.toJsonObject(ImmutableMap.of("field","queue", "operation", "EQUALS", "value", queueName)).toString();
            String consumersAsJsonString = activeMQServerControl.listConsumers(options, 1, 10);

            JsonObject consumersAsJsonObject = JsonUtil.readJsonObject(consumersAsJsonString);
            JsonArray array = (JsonArray) consumersAsJsonObject.get("data");

            Assert.assertEquals("number of consumers returned from query", 1, array.size());
            JsonObject jsonConsumer = array.getJsonObject(0);
            Assert.assertEquals("queue name in consumer", queueName, jsonConsumer.getString("queue"));
            Assert.assertEquals("address name in consumer", addressName, jsonConsumer.getString("address"));
         } finally {
            consumer.close();
         }
      }
   } finally {
      jmxConnector.close();
   }
}
 
Example 18
Source File: MBSFPreStartPostStartTest.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Run test
 */
public int runTest(boolean setBeforeStart) throws Exception {

    echo("=-=-= MBSFPreStartPostStartTest: Set MBSF " +
         (setBeforeStart ? "before" : "after") +
         " starting the connector server =-=-=");

    JMXConnectorServer server = null;
    JMXConnector client = null;

    // Create a new MBeanServer
    //
    final MBeanServer mbs = MBeanServerFactory.createMBeanServer();

    try {
        // Create the JMXServiceURL
        //
        final JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");

        // Create a JMXConnectorServer
        //
        server = JMXConnectorServerFactory.newJMXConnectorServer(url,
                                                                 null,
                                                                 mbs);

        // Create MBeanServerForwarder
        //
        MBeanServerForwarder mbsf =
            MBSFInvocationHandler.newProxyInstance();

        // Set MBeanServerForwarder before start()
        //
        if (setBeforeStart)
            server.setMBeanServerForwarder(mbsf);

        // Start the JMXConnectorServer
        //
        server.start();

        // Set MBeanServerForwarder after start()
        //
        if (!setBeforeStart)
            server.setMBeanServerForwarder(mbsf);

        // Create a JMXConnector
        //
        client = server.toJMXConnector(null);

        // Connect to the connector server
        //
        client.connect(null);

        // Get non-secure MBeanServerConnection
        //
        final MBeanServerConnection mbsc =
            client.getMBeanServerConnection();

        // Run method
        //
        mbsc.getDefaultDomain();

        // Check flag in MBeanServerForwarder
        //
        MBSFInvocationHandler mbsfih =
            (MBSFInvocationHandler) Proxy.getInvocationHandler(mbsf);
        if (mbsfih.getFlag() == true) {
            echo("OK: Did go into MBeanServerForwarder!");
        } else {
            echo("KO: Didn't go into MBeanServerForwarder!");
            return 1;
        }
    } catch (Exception e) {
        echo("Failed to perform operation: " + e);
        return 1;
    } finally {
        // Close the connection
        //
        if (client != null)
            client.close();

        // Stop the connector server
        //
        if (server != null)
            server.stop();

        // Release the MBeanServer
        //
        if (mbs != null)
            MBeanServerFactory.releaseMBeanServer(mbs);
    }

    return 0;
}
 
Example 19
Source File: RMIExitTest.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
private static void test() {
    try {
        JMXServiceURL u = new JMXServiceURL("rmi", null, 0);
        JMXConnectorServer server;
        JMXServiceURL addr;
        JMXConnector client;
        MBeanServerConnection mserver;

        final ObjectName delegateName =
            new ObjectName("JMImplementation:type=MBeanServerDelegate");
        final NotificationListener dummyListener =
            new NotificationListener() {
                    public void handleNotification(Notification n,
                                                   Object o) {
                        // do nothing
                        return;
                    }
                };

        server = JMXConnectorServerFactory.newJMXConnectorServer(u,
                                                                 null,
                                                                 mbs);
        server.start();

        addr = server.getAddress();
        client = JMXConnectorFactory.newJMXConnector(addr, null);
        client.connect(null);

        mserver = client.getMBeanServerConnection();
        String s1 = "1";
        String s2 = "2";
        String s3 = "3";

        mserver.addNotificationListener(delegateName,
                                        dummyListener, null, s1);
        mserver.addNotificationListener(delegateName,
                                        dummyListener, null, s2);
        mserver.addNotificationListener(delegateName,
                                        dummyListener, null, s3);

        mserver.removeNotificationListener(delegateName,
                                           dummyListener, null, s3);
        mserver.removeNotificationListener(delegateName,
                                           dummyListener, null, s2);
        mserver.removeNotificationListener(delegateName,
                                           dummyListener, null, s1);
        client.close();

        server.stop();
    } catch (Exception e) {
        System.out.println(e);
        e.printStackTrace();
        System.exit(1);
    }
}
 
Example 20
Source File: MXBeanTest.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
private static <T> void testInterface(Class<T> c, boolean nullTest)
        throws Exception {

    System.out.println("Testing " + c.getName() +
                       (nullTest ? " for null values" : "") + "...");

    MBeanServer mbs = MBeanServerFactory.newMBeanServer();

    JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
    JMXConnectorServer cs =
        JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    cs.start();
    JMXServiceURL addr = cs.getAddress();
    JMXConnector cc = JMXConnectorFactory.connect(addr);
    MBeanServerConnection mbsc = cc.getMBeanServerConnection();

    NamedMXBeans namedMXBeans = new NamedMXBeans(mbsc);
    InvocationHandler ih =
        nullTest ? new MXBeanNullImplInvocationHandler(c, namedMXBeans) :
                   new MXBeanImplInvocationHandler(c, namedMXBeans);
    T impl = c.cast(Proxy.newProxyInstance(c.getClassLoader(),
                                           new Class[] {c},
                                           ih));
    ObjectName on = new ObjectName("test:type=" + c.getName());
    mbs.registerMBean(impl, on);

    System.out.println("Register any MXBeans...");

    Field[] fields = c.getFields();
    for (Field field : fields) {
        String n = field.getName();
        if (n.endsWith("ObjectName")) {
            String objectNameString = (String) field.get(null);
            String base = n.substring(0, n.length() - 10);
            Field f = c.getField(base);
            Object mxbean = f.get(null);
            ObjectName objectName =
                ObjectName.getInstance(objectNameString);
            mbs.registerMBean(mxbean, objectName);
            namedMXBeans.put(objectName, mxbean);
        }
    }

    try {
        testInterface(c, mbsc, on, namedMXBeans, nullTest);
    } finally {
        try {
            cc.close();
        } finally {
            cs.stop();
        }
    }
}