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

The following examples show how to use javax.management.remote.JMXConnector#getMBeanServerConnection() . 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: JMXInvokeMBean.java    From ysoserial with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {

	if ( args.length < 4 ) {
		System.err.println(JMXInvokeMBean.class.getName() + " <host> <port> <payload_type> <payload_arg>");
		System.exit(-1);
	}
   	
	JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + args[0] + ":" + args[1] + "/jmxrmi");
       
	JMXConnector jmxConnector = JMXConnectorFactory.connect(url);
	MBeanServerConnection mbeanServerConnection = jmxConnector.getMBeanServerConnection();

	// create the payload
	Object payloadObject = Utils.makePayloadObject(args[2], args[3]);   
	ObjectName mbeanName = new ObjectName("java.util.logging:type=Logging");

	mbeanServerConnection.invoke(mbeanName, "getLoggerLevel", new Object[]{payloadObject}, new String[]{String.class.getCanonicalName()});

	//close the connection
	jmxConnector.close();
   }
 
Example 2
Source File: ProviderTest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
private static void dotest(JMXServiceURL url, MBeanServer mbs)
    throws Exception {
    JMXConnectorServer server = null;
    JMXConnector client = null;

    server = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    server.start();
    JMXServiceURL outputAddr = server.getAddress();
    System.out.println("Server started ["+ outputAddr+ "]");

    client = JMXConnectorFactory.newJMXConnector(outputAddr, null);

    client.connect();
    System.out.println("Client connected");

    MBeanServerConnection connection
        = client.getMBeanServerConnection();

    System.out.println(connection.getDefaultDomain());
}
 
Example 3
Source File: TestManager.java    From openjdk-8 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 4
Source File: ProviderTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void dotest(JMXServiceURL url, MBeanServer mbs)
    throws Exception {
    JMXConnectorServer server = null;
    JMXConnector client = null;

    server = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    server.start();
    JMXServiceURL outputAddr = server.getAddress();
    System.out.println("Server started ["+ outputAddr+ "]");

    client = JMXConnectorFactory.newJMXConnector(outputAddr, null);

    client.connect();
    System.out.println("Client connected");

    MBeanServerConnection connection
        = client.getMBeanServerConnection();

    System.out.println(connection.getDefaultDomain());
}
 
Example 5
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 6
Source File: JMXConnectorHelper.java    From perfmon-agent with Apache License 2.0 5 votes vote down vote up
public MBeanServerConnection getServerConnection(String url, String user, String pwd) {
    try {
        JMXConnector connector = getJMXConnector(url, user, pwd);
        return connector.getMBeanServerConnection();
    } catch (Exception ex) {
        log.error("Failed to get JMX Connector", ex);
        throw new RuntimeException("Failed to get JMX Connector", ex);
    }
}
 
Example 7
Source File: RMIDownloadTest.java    From jdk8u_jdk 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 8
Source File: Client.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
{
   // This JMXServiceURL works only if the connector server is in-VM with
   // the connector. If this is not the case, set the correct host name.
   JMXServiceURL address = new JMXServiceURL("soap", null, 8080, "/jmxconnector");

   // Connect a JSR 160 JMXConnector to the server side
   JMXConnector connector = JMXConnectorFactory.connect(address);

   // Retrieve an MBeanServerConnection that represent the MBeanServer
   // the remote connector server is bound to
   MBeanServerConnection connection = connector.getMBeanServerConnection();

   // Call the server side as if it is a local MBeanServer
   ObjectName delegateName = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate");
   Object proxy = MBeanServerInvocationHandler.newProxyInstance(connection, delegateName, MBeanServerDelegateMBean.class, true);
   MBeanServerDelegateMBean delegate = (MBeanServerDelegateMBean)proxy;

   System.out.println(delegate.getImplementationVendor() + " is cool !");

   // Register an MBean, and get notifications via the SOAP protocol
   connection.addNotificationListener(delegateName, new NotificationListener()
   {
      public void handleNotification(Notification notification, Object handback)
      {
         System.out.println("Got the following notification: " + notification);
      }
   }, null, null);

   ObjectName timerName = ObjectName.getInstance("services:type=Timer");
   connection.createMBean(Timer.class.getName(), timerName, null);

   // Unregistering the MBean to get another notification
   connection.unregisterMBean(timerName);

   // Allow the unregistration notification to arrive before killing this JVM
   Thread.sleep(1000);

   connector.close();
}
 
Example 9
Source File: ExtraCommand.java    From vjtools with Apache License 2.0 5 votes vote down vote up
public void execute(final String hostportOrPid, final String login, final String password, final String beanname,
		int interval) throws Exception {
	JMXConnector jmxc = Client.connect(hostportOrPid, login, password);

	try {
		MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

		gcUtilCommand(mbsc, interval);
	} finally {
		jmxc.close();
	}
}
 
Example 10
Source File: RMIDownloadTest.java    From jdk8u-dev-jdk 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 11
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 12
Source File: MXBeanInteropTest2.java    From jdk8u-jdk 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 13
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 14
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();
        }
    }
}
 
Example 15
Source File: MXBeanTest.java    From jdk8u-dev-jdk 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();
        }
    }
}
 
Example 16
Source File: RMIConnectorInternalMapTest.java    From hottub 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 17
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 18
Source File: EmptyDomainNotificationTest.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 {

        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 19
Source File: RMIConnectorInternalMapTest.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("---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 20
Source File: RMIConnectorInternalMapTest.java    From jdk8u-dev-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) {
        }
    }
}