Java Code Examples for javax.management.MBeanServerFactory#createMBeanServer()

The following examples show how to use javax.management.MBeanServerFactory#createMBeanServer() . 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: MBeanServerFactoryBeanTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void withLocateExistingAndExistingServer() {
	MBeanServer server = MBeanServerFactory.createMBeanServer();
	try {
		MBeanServerFactoryBean bean = new MBeanServerFactoryBean();
		bean.setLocateExistingServerIfPossible(true);
		bean.afterPropertiesSet();
		try {
			MBeanServer otherServer = bean.getObject();
			assertSame("Existing MBeanServer not located", server, otherServer);
		}
		finally {
			bean.destroy();
		}
	}
	finally {
		MBeanServerFactory.releaseMBeanServer(server);
	}
}
 
Example 2
Source File: MLetCommand.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (System.getSecurityManager() == null)
        throw new IllegalStateException("No security manager installed!");

    System.out.println("java.security.policy=" +
                       System.getProperty("java.security.policy"));

    // Instantiate the MBean server
    //
    System.out.println("Create the MBean server");
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();
    // Register the MLetMBean
    //
    System.out.println("Create MLet MBean");
    ObjectName mlet = new ObjectName("MLetTest:name=MLetMBean");
    mbs.createMBean("javax.management.loading.MLet", mlet);
    // Test OK!
    //
    System.out.println("Bye! Bye!");
}
 
Example 3
Source File: JmxServer.java    From AsuraFramework with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * 启动JMXConnectorServer
 *
 * @author zhangshaobin
 * @created 2012-12-28 下午4:00:59
 *
 * @throws IOException
 */
private void start() {
	if (null != server)
		return;
	try {
		//			platformServer = ManagementFactory.getPlatformMBeanServer();
		server = MBeanServerFactory.createMBeanServer("Asura");
		JMXServiceURL url = new JMXServiceURL("jmxmp", null, port);
		//			JMXServiceURL platformUrl = new JMXServiceURL("jmxmp", null, 9021);
		//       	platformConnectorServer = JMXConnectorServerFactory.newJMXConnectorServer(platformUrl, null, platformServer);
		//       	platformConnectorServer.start();
		//       	System.out.println("JMX PlatformServer started! Used port 9020.");
		connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server);
		connectorServer.start();
		System.out.println(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss] ").format(new Date())
				+ "JMX Server started! used port:" + port);
	} catch (Exception e) {
		e.printStackTrace();
		System.out.println(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss] ").format(new Date())
				+ "JMX Server started failed!" + " " + e.getMessage());
		System.exit(1);
	}
}
 
Example 4
Source File: HeuristicXATest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
   super.setUp();
   mbeanServer = MBeanServerFactory.createMBeanServer();
   locator = createInVMNonHALocator();
}
 
Example 5
Source File: SameObjectTwoNamesTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    boolean expectException =
            (System.getProperty("jmx.mxbean.multiname") == null);
    try {
        ObjectName objectName1 = new ObjectName("test:index=1");
        ObjectName objectName2 = new ObjectName("test:index=2");
        MBeanServer mbs = MBeanServerFactory.createMBeanServer();
        MXBC_SimpleClass01 mxBeanObject = new MXBC_SimpleClass01();

        mbs.registerMBean(mxBeanObject, objectName1);

        mbs.registerMBean(mxBeanObject, objectName2);

        if (expectException) {
            throw new Exception("TEST FAILED: " +
                    "InstanceAlreadyExistsException was not thrown");
        } else
            System.out.println("Correctly got no exception with compat property");
    } catch (InstanceAlreadyExistsException e) {
        if (expectException) {
            System.out.println("Got expected InstanceAlreadyExistsException:");
            e.printStackTrace(System.out);
        } else {
            throw new Exception(
                    "TEST FAILED: Got exception even though compat property set", e);
        }
    }
    System.out.println("TEST PASSED");
}
 
Example 6
Source File: Server.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void main(String[] args) throws Exception
{
   MBeanServer server = MBeanServerFactory.createMBeanServer();

   ObjectName name = new ObjectName("examples:type=remote");
   MyRemoteServiceObject remote = new MyRemoteServiceObject();
   server.registerMBean(remote, name);

   MyRemoteServiceObjectMBean managed = (MyRemoteServiceObjectMBean)MBeanServerInvocationHandler.newProxyInstance(server, name, MyRemoteServiceObjectMBean.class, false);
   managed.start();
}
 
Example 7
Source File: MapNullValuesTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private int jmxConnectorServerFactoryTests() {
    int errorCount = 0;
    echo("");
    echo(dashedMessage("Run JMXConnectorServerFactory Tests"));
    for (int i = 0; i < maps.length - 1; i++) {
        echo("\n>>> JMXConnectorServerFactory 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 + "/JMXConnectorServerFactory" + i);
            JMXConnectorServer jmxcs =
                JMXConnectorServerFactory.newJMXConnectorServer(url,
                                                                maps[i],
                                                                mbs);
            echo("\tStart the RMI connector server");
            jmxcs.start();
            echo("\tCall RMIConnectorServer.toJMXConnector(Map)");
            jmxcs.toJMXConnector(maps[i]);
            echo("\tStop the RMI connector server");
            jmxcs.stop();
            echo("\tTest [" + i + "] PASSED!");
        } catch (Exception e) {
            errorCount++;
            echo("\tTest [" + i + "] FAILED!");
            e.printStackTrace(System.out);
        }
    }
    if (errorCount == 0) {
        echo("");
        echo(dashedMessage("JMXConnectorServerFactory Tests PASSED!"));
    } else {
        echo("");
        echo(dashedMessage("JMXConnectorServerFactory Tests FAILED!"));
    }
    return errorCount;
}
 
Example 8
Source File: ImplVersionCommand.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Instantiate the MBean server
    //
    System.out.println("Create the MBean server");
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();

    // Get the JMX implementation version from the MBeanServerDelegateMBean
    //
    System.out.println("Get the JMX implementation version");
    ObjectName mbsdName =
        new ObjectName("JMImplementation:type=MBeanServerDelegate");
    String mbsdAttribute = "ImplementationVersion";
    String mbsdVersion = (String) mbs.getAttribute(mbsdName, mbsdAttribute);

    // Display JMX implementation version and JVM implementation version
    //
    System.out.println("JMX implementation version          = " +
                       mbsdVersion);
    System.out.println("Java Runtime implementation version = " +
                       args[0]);

    // Check JMX implementation version vs. JVM implementation version
    //
    if (Boolean.valueOf(args[1]).booleanValue()) {
        if (!mbsdVersion.equals(args[0]))
            throw new IllegalArgumentException(
              "JMX and Java Runtime implementation versions do not match!");
        // Test OK!
        //
        System.out.println("JMX and Java Runtime implementation " +
                           "versions match!");
    } else {
        // Test OK!
        //
        System.out.println("JMX and Java Runtime implementation " +
                           "versions do not match because the test " +
                           "is using an unbundled version of JMX!");
    }
    System.out.println("Bye! Bye!");
}
 
Example 9
Source File: ImplVersionCommand.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Instantiate the MBean server
    //
    System.out.println("Create the MBean server");
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();

    // Get the JMX implementation version from the MBeanServerDelegateMBean
    //
    System.out.println("Get the JMX implementation version");
    ObjectName mbsdName =
        new ObjectName("JMImplementation:type=MBeanServerDelegate");
    String mbsdAttribute = "ImplementationVersion";
    String mbsdVersion = (String) mbs.getAttribute(mbsdName, mbsdAttribute);

    // Display JMX implementation version and JVM implementation version
    //
    System.out.println("JMX implementation version          = " +
                       mbsdVersion);
    System.out.println("Java Runtime implementation version = " +
                       args[0]);

    // Check JMX implementation version vs. JVM implementation version
    //
    if (Boolean.valueOf(args[1]).booleanValue()) {
        if (!mbsdVersion.equals(args[0]))
            throw new IllegalArgumentException(
              "JMX and Java Runtime implementation versions do not match!");
        // Test OK!
        //
        System.out.println("JMX and Java Runtime implementation " +
                           "versions match!");
    } else {
        // Test OK!
        //
        System.out.println("JMX and Java Runtime implementation " +
                           "versions do not match because the test " +
                           "is using an unbundled version of JMX!");
    }
    System.out.println("Bye! Bye!");
}
 
Example 10
Source File: IIOPURLTest.java    From dragonwell8_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 11
Source File: RMIExporterTest.java    From jdk8u-jdk 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 12
Source File: MBSFPreStartPostStartTest.java    From openjdk-jdk8u 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 13
Source File: HttpAdaptor.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Starts the http server
 */
public void start() throws JMException, MalformedURLException
{
   // creates new server
   MBeanServer server = MBeanServerFactory.createMBeanServer("test");
   ObjectName serverName = new ObjectName("Http:name=HttpAdaptor");
   server.createMBean("mx4j.tools.adaptor.http.HttpAdaptor", serverName, null);
   // set attributes
   if (port > 0)
   {
      server.setAttribute(serverName, new Attribute("Port", new Integer(port)));
   }
   else
   {
      System.out.println("Incorrect port value " + port);
   }
   if (host != null)
   {
      server.setAttribute(serverName, new Attribute("Host", host));
   }
   else
   {
      System.out.println("Incorrect null hostname");
   }
   // set the XSLTProcessor. If you want to use pure XML comment this out
   ObjectName processorName = new ObjectName("Http:name=XSLTProcessor");
   server.createMBean("mx4j.tools.adaptor.http.XSLTProcessor", processorName, null);
   if (path != null)
   {
      server.setAttribute(processorName, new Attribute("File", path));
   }
   server.setAttribute(processorName, new Attribute("UseCache", new Boolean(false)));
   if (pathInJar != null)
   {
      server.setAttribute(processorName, new Attribute("PathInJar", pathInJar));
   }
   server.setAttribute(serverName, new Attribute("ProcessorName", processorName));

   // add a couple of MBeans
   TestClass test1 = new TestClass("t1", new URL("http://mx4j.sourceforge.net"));
   TestClass test2 = new TestClass("t1", new URL("http://www.sourceforge.net/projects/mx4j"));
   server.registerMBean(test1, new ObjectName("Test:name=test1"));
   server.registerMBean(test2, new ObjectName("Test:name=test2"));

   // add a stats MBean
   TimedStatisticsRecorder recoder = new TimedStatisticsRecorder();
   recoder.setObservedObject(new ObjectName("Test:name=test1"));
   recoder.setObservedAttribute("Double");
   server.registerMBean(recoder, new ObjectName("Test:name=test1recorder"));
   server.invoke(new ObjectName("Test:name=test1recorder"), "start", null, null);

   // add a couple of MBeans

   // add user names
   server.invoke(serverName, "addAuthorization", new Object[]{"mx4j", "mx4j"}, new String[]{"java.lang.String", "java.lang.String"});

   // use basic authentication
   //server.setAttribute(serverName, new Attribute("AuthenticationMethod", "basic"));

   // starts the server
   server.invoke(serverName, "start", null, null);
}
 
Example 14
Source File: EmptyDomainNotificationTest.java    From openjdk-8-source 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 15
Source File: GetMBeansFromURLTest.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 {

        boolean error = false;

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

        // Instantiate an MLet
        //
        System.out.println("Create the MLet");
        MLet mlet = new MLet();

        // Register the MLet MBean with the MBeanServer
        //
        System.out.println("Register the MLet MBean");
        ObjectName mletObjectName = new ObjectName("Test:type=MLet");
        mbs.registerMBean(mlet, mletObjectName);

        // Call getMBeansFromURL
        //
        System.out.println("Call mlet.getMBeansFromURL(<url>)");
        try {
            mlet.getMBeansFromURL("bogus://whatever");
            System.out.println("TEST FAILED: Expected " +
                               ServiceNotFoundException.class +
                               " exception not thrown.");
            error = true;
        } catch (ServiceNotFoundException e) {
            if (e.getCause() == null) {
                System.out.println("TEST FAILED: Got null cause in " +
                                   ServiceNotFoundException.class +
                                   " exception.");
                error = true;
            } else {
                System.out.println("TEST PASSED: Got non-null cause in " +
                                   ServiceNotFoundException.class +
                                   " exception.");
                error = false;
            }
            e.printStackTrace(System.out);
        }

        // Unregister the MLet MBean
        //
        System.out.println("Unregister the MLet MBean");
        mbs.unregisterMBean(mletObjectName);

        // Release MBean server
        //
        System.out.println("Release the MBean server");
        MBeanServerFactory.releaseMBeanServer(mbs);

        // End Test
        //
        System.out.println("Bye! Bye!");
        if (error) System.exit(1);
    }
 
Example 16
Source File: InstrumentationManagerImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
@PostConstruct
public void init() {
    if (bus != null && bus.getExtension(MBeanServer.class) != null) {
        enabled = true;
        mbs = bus.getExtension(MBeanServer.class);
    }
    if (isEnabled()) {
        if (mbs == null) {
            // return platform mbean server if the option is specified.
            if (usePlatformMBeanServer) {
                mbs = ManagementFactory.getPlatformMBeanServer();
            } else {
                String mbeanServerID = mbeanServerIDMap.get(mbeanServerName);
                List<MBeanServer> servers = null;
                if (mbeanServerID != null) {
                    servers = CastUtils.cast(MBeanServerFactory.findMBeanServer(mbeanServerID));
                }
                if (servers == null || servers.isEmpty()) {
                    mbs = MBeanServerFactory.createMBeanServer(mbeanServerName);
                    try {
                        mbeanServerID = (String) mbs.getAttribute(getDelegateName(),
                                                                 "MBeanServerId");
                        mbeanServerIDMap.put(mbeanServerName, mbeanServerID);
                    } catch (JMException e) {
                        // ignore
                    }
                } else {
                    mbs = servers.get(0);
                }
            }
        }

        if (!connectFailed && null != bus) {
            try {
                //Register Bus here since we can guarantee that Instrumentation
                //infrastructure has been initialized.
                ManagedBus mbus = new ManagedBus(bus);
                register(mbus);
                if (LOG.isLoggable(Level.INFO)) {
                    LOG.info("registered " + mbus.getObjectName());
                }
            } catch (JMException jmex) {
                LOG.log(Level.SEVERE, "REGISTER_FAILURE_MSG", new Object[]{bus, jmex});
            }
        }
    }

    if (null != bus) {
        bus.setExtension(this, InstrumentationManager.class);
        BusLifeCycleManager blcm = bus.getExtension(BusLifeCycleManager.class);
        if (null != blcm) {
            blcm.registerLifeCycleListener(this);
        }
    }
}
 
Example 17
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 18
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(String proto) throws Exception {
    System.out.println("Unexpected notifications test for protocol " +
                       proto);
    MBeanServer mbs = null;
    try {
        // Create a MBeanServer
        //
        mbs = MBeanServerFactory.createMBeanServer();

        // Create a NotificationEmitter MBean
        //
        mbean = new ObjectName ("Default:name=NotificationEmitter");
        mbs.registerMBean(new NotificationEmitter(), mbean);

        // Create a connector server
        //
        url = new JMXServiceURL("service:jmx:" + proto + "://");

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

        mbs.registerMBean(
                    server,
                    new ObjectName("Default:name=ConnectorServer"));

        server.start();

        url = server.getAddress();

        for (int j = 0; j < 2; j++) {
            test();
        }
    } finally {
        // Stop server
        //
        server.stop();
        // Release the MBeanServer
        //
        MBeanServerFactory.releaseMBeanServer(mbs);
    }
}
 
Example 19
Source File: RMIExporterTest.java    From TencentKona-8 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: MBSFPreStartPostStartTest.java    From jdk8u-dev-jdk 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;
}