Java Code Examples for javax.management.remote.JMXConnectorFactory#connect()

The following examples show how to use javax.management.remote.JMXConnectorFactory#connect() . 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: LocalProcessWrapper.java    From JCoz with GNU General Public License v3.0 6 votes vote down vote up
public LocalProcessWrapper(VirtualMachineDescriptor descriptor) throws VirtualMachineConnectionException{
    try{
        vm = VirtualMachine.attach(descriptor);
        vm.startLocalManagementAgent();
        Properties props = vm.getAgentProperties();
        String connectorAddress =
            props.getProperty(CONNECTOR_ADDRESS_PROPERTY_KEY);
        JMXServiceURL url = new JMXServiceURL(connectorAddress);
        JMXConnector connector = JMXConnectorFactory.connect(url);
        MBeanServerConnection mbeanConn = connector.getMBeanServerConnection();
        mbeanProxy = JMX.newMXBeanProxy(mbeanConn, 
                JCozProfiler.getMBeanName(),  JCozProfilerMBean.class);
    } catch(IOException | AttachNotSupportedException e){
        throw new VirtualMachineConnectionException(e);
    }
}
 
Example 2
Source File: TestManager.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void connect(String pid, String address) throws Exception {
    if (address == null) {
        throw new RuntimeException("Local connector address for " +
                                   pid + " is null");
    }

    System.out.println("Connect to process " + pid + " via: " + address);

    JMXServiceURL url = new JMXServiceURL(address);
    JMXConnector c = JMXConnectorFactory.connect(url);
    MBeanServerConnection server = c.getMBeanServerConnection();

    System.out.println("Connected.");

    RuntimeMXBean rt = newPlatformMXBeanProxy(server,
        RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
    System.out.println(rt.getName());

    // close the connection
    c.close();
}
 
Example 3
Source File: JMXClient.java    From newblog with Apache License 2.0 6 votes vote down vote up
private static MBeanServerConnection initMBeanServerConnection() {
    try {
        String ipAndPort = JmxPortCheck.check();
        if (Strings.isNullOrEmpty(ipAndPort)) {
            return null;
        }
        String jmxURL = "service:jmx:rmi:///jndi/rmi://" + ipAndPort + "/jmxrmi";
        JMXServiceURL serviceURL = new JMXServiceURL(jmxURL);
        Map map = new HashMap();
        String[] credentials = Config.getProperty("credentials").split(",");
        map.put("jmx.remote.credentials", credentials);
        JMXConnector connector = JMXConnectorFactory.connect(serviceURL, map);
        mbsconnector = connector.getMBeanServerConnection();
    } catch (IOException e) {
        logger.error("get connector error" + e);
    }
    return mbsconnector;
}
 
Example 4
Source File: CARBON15928JMXDisablingTest.java    From product-ei with Apache License 2.0 6 votes vote down vote up
private MBeanInfo testMBeanForDatasource() throws Exception {
    Map<String, String[]> env = new HashMap<>();
    String[] credentials = { "admin", "admin" };
    env.put(JMXConnector.CREDENTIALS, credentials);
    try {
        String url = "service:jmx:rmi://localhost:12311/jndi/rmi://localhost:11199/jmxrmi";
        JMXServiceURL jmxUrl = new JMXServiceURL(url);
        JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxUrl, env);
        MBeanServerConnection mBeanServer = jmxConnector.getMBeanServerConnection();
        ObjectName mbeanObject = new ObjectName(dataSourceName + ",-1234:type=DataSource");
        MBeanInfo mBeanInfo = mBeanServer.getMBeanInfo(mbeanObject);
        return mBeanInfo;
    } catch (MalformedURLException | MalformedObjectNameException | IntrospectionException |
            ReflectionException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    }
}
 
Example 5
Source File: RMIConnectorLogAttributesTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private JMXConnector connectToServer(JMXConnectorServer server) throws IOException, MalformedObjectNameException, NullPointerException, InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException, ReflectionException, MBeanException {
    JMXServiceURL url = server.getAddress();
    Map<String, Object> env = new HashMap<String, Object>();
    JMXConnector connector = JMXConnectorFactory.connect(url, env);

    System.out.println("DEBUG: Client connected to RMI at: " + url);

    return connector;
}
 
Example 6
Source File: ConnectorServerFactoryBeanTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void checkServerConnection(MBeanServer hostedServer) throws IOException, MalformedURLException {
	// Try to connect using client.
	JMXServiceURL serviceURL = new JMXServiceURL(ConnectorServerFactoryBean.DEFAULT_SERVICE_URL);
	JMXConnector connector = JMXConnectorFactory.connect(serviceURL);

	assertNotNull("Client Connector should not be null", connector);

	// Get the MBean server connection.
	MBeanServerConnection connection = connector.getMBeanServerConnection();
	assertNotNull("MBeanServerConnection should not be null", connection);

	// Test for MBean server equality.
	assertEquals("Registered MBean count should be the same", hostedServer.getMBeanCount(),
			connection.getMBeanCount());
}
 
Example 7
Source File: JmxClient.java    From jforgame with Apache License 2.0 5 votes vote down vote up
/**
	 * 该工具类简单无敌,试想一下,在生产环境,直接用一个ide就可以链接服务器的jmx接口, 从而可以查看服务器的内存数据,或者执行任意代码,想想都激动不已
	 * ^_^
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String args[]) throws Exception {
		// 如果执行的JavaScript脚本内容过长
		// 则可以把脚本写在一个文件里,然后使用jmx client 动态调用mbean接口方法
		String user = "root";
		String pwd = "root";

		// 如果生产环境需要账号验证的话
		String[] account = new String[] { user, pwd };
		Map<String, String[]> props = new HashMap<String, String[]>();
		props.put("jmx.remote.credentials", account);

		// 10086参数,具体见启动脚本的vm参数,@see -Dcom.sun.management.jmxremote.port=10086
		JMXServiceURL address = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:10086/jmxrmi");
		JMXConnector connector = JMXConnectorFactory.connect(address, props);
		MBeanServerConnection mBeanConnection = connector.getMBeanServerConnection();

		connector.connect();

		ObjectName objectName = new ObjectName("GameMXBean:name=GameMonitor");
		System.out.println("\nMBean count = " + mBeanConnection.getMBeanCount());

//        for (ObjectInstance mxBean : mBeanConnection.queryMBeans(null, null)) {
//            System.out.println("object.getObjectName="+mxBean.getObjectName());
//        }

		GameMonitorMBean mBean = JMX.newMBeanProxy(mBeanConnection, objectName, GameMonitorMBean.class);

		String script = FileUtils.readText("script.js");
		System.err.println(script);

		System.err.println(mBean.execJavaScript(script));
	}
 
Example 8
Source File: JMXRemoteNonManagementEndpointArquillianTest.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Test
@RunAsClient
public void testRemoteConnection() throws Exception {
    String urlString = "service:jmx:remote+http://localhost:8080";

    JMXServiceURL serviceURL = new JMXServiceURL(urlString);
    JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceURL, null);
    MBeanServerConnection connection = jmxConnector.getMBeanServerConnection();

    int count = connection.getMBeanCount();
    assertThat( count ).isGreaterThan( 1 );

    jmxConnector.close();
}
 
Example 9
Source File: EmptyDomainNotificationTest.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        final MBeanServer mbs = MBeanServerFactory.createMBeanServer();

        final JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");

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

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

        final MBeanServerConnection mbsc = client.getMBeanServerConnection();

        final ObjectName mbean = ObjectName.getInstance(":type=Simple");
        mbsc.createMBean(Simple.class.getName(), mbean);

        System.out.println("EmptyDomainNotificationTest-main: add a listener ...");
        final Listener li = new Listener();
        mbsc.addNotificationListener(mbean, li, null, null);

        System.out.println("EmptyDomainNotificationTest-main: ask to send a notif ...");
        mbsc.invoke(mbean, "emitNotification", null, null);

        System.out.println("EmptyDomainNotificationTest-main: waiting notif...");
        final long stopTime = System.currentTimeMillis() + 2000;
        synchronized(li) {
            long toWait = stopTime - System.currentTimeMillis();

            while (li.received < 1 && toWait > 0) {
                li.wait(toWait);

                toWait = stopTime - System.currentTimeMillis();
            }
        }

        if (li.received < 1) {
            throw new RuntimeException("No notif received!");
        } else if (li.received > 1) {
            throw new RuntimeException("Wait one notif but got: "+li.received);
        }

        System.out.println("EmptyDomainNotificationTest-main: Got the expected notif!");

        System.out.println("EmptyDomainNotificationTest-main: remove the listener.");
        mbsc.removeNotificationListener(mbean, li);

        // clean
        client.close();
        server.stop();

        System.out.println("EmptyDomainNotificationTest-main: Bye.");
    }
 
Example 10
Source File: EmptyDomainNotificationTest.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        final MBeanServer mbs = MBeanServerFactory.createMBeanServer();

        final JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");

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

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

        final MBeanServerConnection mbsc = client.getMBeanServerConnection();

        final ObjectName mbean = ObjectName.getInstance(":type=Simple");
        mbsc.createMBean(Simple.class.getName(), mbean);

        System.out.println("EmptyDomainNotificationTest-main: add a listener ...");
        final Listener li = new Listener();
        mbsc.addNotificationListener(mbean, li, null, null);

        System.out.println("EmptyDomainNotificationTest-main: ask to send a notif ...");
        mbsc.invoke(mbean, "emitNotification", null, null);

        System.out.println("EmptyDomainNotificationTest-main: waiting notif...");
        final long stopTime = System.currentTimeMillis() + 2000;
        synchronized(li) {
            long toWait = stopTime - System.currentTimeMillis();

            while (li.received < 1 && toWait > 0) {
                li.wait(toWait);

                toWait = stopTime - System.currentTimeMillis();
            }
        }

        if (li.received < 1) {
            throw new RuntimeException("No notif received!");
        } else if (li.received > 1) {
            throw new RuntimeException("Wait one notif but got: "+li.received);
        }

        System.out.println("EmptyDomainNotificationTest-main: Got the expected notif!");

        System.out.println("EmptyDomainNotificationTest-main: remove the listener.");
        mbsc.removeNotificationListener(mbean, li);

        // clean
        client.close();
        server.stop();

        System.out.println("EmptyDomainNotificationTest-main: Bye.");
    }
 
Example 11
Source File: RMIConnectorNullSubjectConnTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.out.println("---RMIConnectorNullSubjectConnTest 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 nullSubjectConnField = RMIConnector.class.getDeclaredField("nullSubjectConnRef");
        nullSubjectConnField.setAccessible(true);

        WeakReference<MBeanServerConnection> weak =
                (WeakReference<MBeanServerConnection>)nullSubjectConnField.get(connectorClient);

        if (weak != null && weak.get() != null) {
            throw new RuntimeException("nullSubjectConnRef must be null at initial time.");
        }

        MBeanServerConnection conn1 = connectorClient.getMBeanServerConnection(null);
        MBeanServerConnection conn2 = connectorClient.getMBeanServerConnection(null);
        if (conn1 == null) {
            throw new RuntimeException("A connection with null subject should not be null.");
        } else if (conn1 != conn2) {
            throw new RuntimeException("The 2 connections with null subject are not equal.");
        }

        conn1 = null;
        conn2 = null;
        int i = 1;
        do {
            System.gc();
            Thread.sleep(100);
            weak = (WeakReference<MBeanServerConnection>)nullSubjectConnField.get(connectorClient);
        } while ((weak != null && weak.get() != null) && i++ < 60);

        System.out.println("---GC times: " + i);

        if (weak != null && weak.get() != null) {
            throw new RuntimeException("Failed to clean RMIConnector's nullSubjectConn");
        } else {
            System.out.println("---RMIConnectorNullSubjectConnTest: PASSED!");
        }
    } finally {
        try {
            connectorClient.close();
            connectorServer.stop();
        } catch (Exception e) {
        }
    }
}
 
Example 12
Source File: EmptyDomainNotificationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        final MBeanServer mbs = MBeanServerFactory.createMBeanServer();

        final JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");

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

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

        final MBeanServerConnection mbsc = client.getMBeanServerConnection();

        final ObjectName mbean = ObjectName.getInstance(":type=Simple");
        mbsc.createMBean(Simple.class.getName(), mbean);

        System.out.println("EmptyDomainNotificationTest-main: add a listener ...");
        final Listener li = new Listener();
        mbsc.addNotificationListener(mbean, li, null, null);

        System.out.println("EmptyDomainNotificationTest-main: ask to send a notif ...");
        mbsc.invoke(mbean, "emitNotification", null, null);

        System.out.println("EmptyDomainNotificationTest-main: waiting notif...");
        synchronized(li) {
            while (li.received < 1) {
                li.wait();
            }
        }

        if (li.received != 1) {
            throw new RuntimeException("Wait one notif but got: "+li.received);
        }

        System.out.println("EmptyDomainNotificationTest-main: Got the expected notif!");

        System.out.println("EmptyDomainNotificationTest-main: remove the listener.");
        mbsc.removeNotificationListener(mbean, li);

        // clean
        client.close();
        server.stop();

        System.out.println("EmptyDomainNotificationTest-main: Bye.");
    }
 
Example 13
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 14
Source File: MXBeanWeirdParamTest.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 {

            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 15
Source File: RMIExporterTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) {

        try {
            // Instantiate the MBean server
            //
            System.out.println("Create the MBean server");
            MBeanServer mbs = MBeanServerFactory.createMBeanServer();

            // Initialize environment map to be passed to the connector server
            //
            System.out.println("Initialize environment map");
            HashMap env = new HashMap();
            CustomRMIExporter exporter = new CustomRMIExporter();
            env.put(RMIExporter.EXPORTER_ATTRIBUTE, exporter);

            // Create an RMI connector server
            //
            System.out.println("Create an RMI connector server");
            JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");
            JMXConnectorServer cs =
                JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
            cs.start();

            // Create an RMI connector client
            //
            System.out.println("Create an RMI connector client");
            JMXConnector cc =
                JMXConnectorFactory.connect(cs.getAddress(), null);

            // Close RMI connector client
            //
            System.out.println("Close the RMI connector client");
            cc.close();

            // Stop RMI connector server
            //
            System.out.println("Stop the RMI connector server");
            cs.stop();

            // Check if remote objects were exported/unexported successfully
            //
            int errorCount = 0;

            if (exporter.rmiServerExported) {
                System.out.println("RMIServer exported OK!");
            } else {
                System.out.println("RMIServer exported KO!");
                errorCount++;
            }

            if (exporter.rmiServerUnexported) {
                System.out.println("RMIServer unexported OK!");
            } else {
                System.out.println("RMIServer unexported KO!");
                errorCount++;
            }

            if (exporter.rmiConnectionExported) {
                System.out.println("RMIConnection exported OK!");
            } else {
                System.out.println("RMIConnection exported KO!");
                errorCount++;
            }

            if (exporter.rmiConnectionUnexported) {
                System.out.println("RMIConnection unexported OK!");
            } else {
                System.out.println("RMIConnection unexported KO!");
                errorCount++;
            }

            System.out.println("Bye! Bye!");

            if (errorCount > 0) {
                System.out.println("RMIExporterTest FAILED!");
                System.exit(1);
            } else {
                System.out.println("RMIExporterTest PASSED!");
            }
        } catch (Exception e) {
            System.out.println("Unexpected exception caught = " + e);
            e.printStackTrace();
            System.exit(1);
        }
    }
 
Example 16
Source File: UnexpectedNotifTest.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
private static void test() throws Exception {
    // Create client
    //
    JMXConnector connector = JMXConnectorFactory.connect(url);
    MBeanServerConnection client = connector.getMBeanServerConnection();

    // Add listener at the client side
    //
    client.addNotificationListener(mbean, listener, null, null);

    // Cleanup
    //
    receivedNotifs = 0;

    // Ask to send notifs
    //
    Object[] params = new Object[] {new Integer(nb)};
    String[] signatures = new String[] {"java.lang.Integer"};

    client.invoke(mbean, "sendNotifications", params, signatures);

    // Waiting...
    //
    synchronized (lock) {
        for (int i = 0; i < 10; i++) {
            if (receivedNotifs < nb) {
                lock.wait(1000);
            }
        }
    }

    // Waiting again to ensure no more notifs
    //
    Thread.sleep(3000);

    synchronized (lock) {
        if (receivedNotifs != nb) {
            throw new Exception("The client expected to receive " +
                                nb + " notifs, but got " + receivedNotifs);
        }
    }

    // Remove listener
    //
    client.removeNotificationListener(mbean, listener);

    connector.close();
}
 
Example 17
Source File: MBeanServerConnectionFactoryBean.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected Object createObject() throws Exception {
	return JMXConnectorFactory.connect(serviceUrl, environment);
}
 
Example 18
Source File: MultiThreadDeadLockTest.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 {
    print("Create the MBean server");
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();

    print("Initialize environment map");
    HashMap env = new HashMap();

    print("Specify a client socket factory to control socket creation.");
    env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE,
            clientFactory);

    print("Specify a server idle timeout to make a server close an idle connection.");
    env.put("jmx.remote.x.server.connection.timeout", serverTimeout);

    print("Disable client heartbeat.");
    env.put("jmx.remote.x.client.connection.check.period", 0);

    env.put("jmx.remote.x.notification.fetch.timeout", serverTimeout);

    print("Create an RMI server");
    JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
    JMXConnectorServer server =
            JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
    server.start();

    url = server.getAddress();

    print("Create jmx client on "+url);
    StateMachine.setState(CREATE_SOCKET); // allow to create client socket
    client = JMXConnectorFactory.connect(url, env);
    Thread.sleep(100);

    totoName = new ObjectName("default:name=toto");
    mbs.registerMBean(toto, totoName);
    print("Register the mbean: " + totoName);

    print("Add listener to toto MBean");
    client.getMBeanServerConnection().addNotificationListener(
            totoName, myListener, null, null);
    Thread.sleep(10);

    print("send notif, listener will block the fetcher");
    toto.sendNotif();
    Thread.sleep(100);

    StateMachine.setState(NO_OP);

    print("Sleep 3 times of server idle timeout: "+serverTimeout+
            ", the sever should close the idle connection.");
    Thread.sleep(serverTimeout*3);

    print("start the user thread to call mbean method, it will get IOexception" +
            " and start the reconnection, the socket factory will block the" +
            " socket creation.");
    UserThread ut = new UserThread();
    ut.start();
    Thread.sleep(10);

    print("Free the listener, the fetcher will get IO and makes " +
            "a deadlock if the bug is not fixed.");
    StateMachine.setState(FREE_LISTENER);
    Thread.sleep(100);

    print("Allow to create new socket for the reconnection");
    StateMachine.setState(CREATE_SOCKET);

    print("Check whether the user thread gets free to call the mbean.");
    if (!ut.waitDone(5000)) {
        throw new RuntimeException("Possible deadlock!");
    }

    print("Remove the listener.");
    client.getMBeanServerConnection().removeNotificationListener(
            totoName, myListener, null, null);
    Thread.sleep(serverTimeout*3);

    print("\nWell passed, bye!");

    client.close();
    Thread.sleep(10);
    server.stop();
}
 
Example 19
Source File: RMIExporterTest.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) {

        try {
            // Instantiate the MBean server
            //
            System.out.println("Create the MBean server");
            MBeanServer mbs = MBeanServerFactory.createMBeanServer();

            // Initialize environment map to be passed to the connector server
            //
            System.out.println("Initialize environment map");
            HashMap env = new HashMap();
            CustomRMIExporter exporter = new CustomRMIExporter();
            env.put(RMIExporter.EXPORTER_ATTRIBUTE, exporter);

            // Create an RMI connector server
            //
            System.out.println("Create an RMI connector server");
            JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");
            JMXConnectorServer cs =
                JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
            cs.start();

            // Create an RMI connector client
            //
            System.out.println("Create an RMI connector client");
            JMXConnector cc =
                JMXConnectorFactory.connect(cs.getAddress(), null);

            // Close RMI connector client
            //
            System.out.println("Close the RMI connector client");
            cc.close();

            // Stop RMI connector server
            //
            System.out.println("Stop the RMI connector server");
            cs.stop();

            // Check if remote objects were exported/unexported successfully
            //
            int errorCount = 0;

            if (exporter.rmiServerExported) {
                System.out.println("RMIServer exported OK!");
            } else {
                System.out.println("RMIServer exported KO!");
                errorCount++;
            }

            if (exporter.rmiServerUnexported) {
                System.out.println("RMIServer unexported OK!");
            } else {
                System.out.println("RMIServer unexported KO!");
                errorCount++;
            }

            if (exporter.rmiConnectionExported) {
                System.out.println("RMIConnection exported OK!");
            } else {
                System.out.println("RMIConnection exported KO!");
                errorCount++;
            }

            if (exporter.rmiConnectionUnexported) {
                System.out.println("RMIConnection unexported OK!");
            } else {
                System.out.println("RMIConnection unexported KO!");
                errorCount++;
            }

            System.out.println("Bye! Bye!");

            if (errorCount > 0) {
                System.out.println("RMIExporterTest FAILED!");
                System.exit(1);
            } else {
                System.out.println("RMIExporterTest PASSED!");
            }
        } catch (Exception e) {
            System.out.println("Unexpected exception caught = " + e);
            e.printStackTrace();
            System.exit(1);
        }
    }
 
Example 20
Source File: MultiThreadDeadLockTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    print("Create the MBean server");
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();

    print("Initialize environment map");
    HashMap env = new HashMap();

    print("Specify a client socket factory to control socket creation.");
    env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE,
            clientFactory);

    print("Specify a server idle timeout to make a server close an idle connection.");
    env.put("jmx.remote.x.server.connection.timeout", serverTimeout);

    print("Disable client heartbeat.");
    env.put("jmx.remote.x.client.connection.check.period", 0);

    env.put("jmx.remote.x.notification.fetch.timeout", serverTimeout);

    print("Create an RMI server");
    JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
    JMXConnectorServer server =
            JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
    server.start();

    url = server.getAddress();

    print("Create jmx client on "+url);
    StateMachine.setState(CREATE_SOCKET); // allow to create client socket
    client = JMXConnectorFactory.connect(url, env);
    Thread.sleep(100);

    totoName = new ObjectName("default:name=toto");
    mbs.registerMBean(toto, totoName);
    print("Register the mbean: " + totoName);

    print("Add listener to toto MBean");
    client.getMBeanServerConnection().addNotificationListener(
            totoName, myListener, null, null);
    Thread.sleep(10);

    print("send notif, listener will block the fetcher");
    toto.sendNotif();
    Thread.sleep(100);

    StateMachine.setState(NO_OP);

    print("Sleep 3 times of server idle timeout: "+serverTimeout+
            ", the sever should close the idle connection.");
    Thread.sleep(serverTimeout*3);

    print("start the user thread to call mbean method, it will get IOexception" +
            " and start the reconnection, the socket factory will block the" +
            " socket creation.");
    UserThread ut = new UserThread();
    ut.start();
    Thread.sleep(10);

    print("Free the listener, the fetcher will get IO and makes " +
            "a deadlock if the bug is not fixed.");
    StateMachine.setState(FREE_LISTENER);
    Thread.sleep(100);

    print("Allow to create new socket for the reconnection");
    StateMachine.setState(CREATE_SOCKET);

    print("Check whether the user thread gets free to call the mbean.");
    if (!ut.waitDone(5000)) {
        throw new RuntimeException("Possible deadlock!");
    }

    print("Remove the listener.");
    client.getMBeanServerConnection().removeNotificationListener(
            totoName, myListener, null, null);
    Thread.sleep(serverTimeout*3);

    print("\nWell passed, bye!");

    client.close();
    Thread.sleep(10);
    server.stop();
}