Java Code Examples for javax.management.MBeanServerConnection#invoke()

The following examples show how to use javax.management.MBeanServerConnection#invoke() . 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: VMOptionOpenDataTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String... args) throws Exception {
    MBeanServerConnection msc = ManagementFactory.getPlatformMBeanServer();
    HotSpotDiagnosticMXBean mxbean =
        ManagementFactory.getPlatformMXBean(msc, HotSpotDiagnosticMXBean.class);


    String[] signatures = new String[] {
        String.class.getName()
    };
    Object obj = msc.invoke(mxbean.getObjectName(), "getVMOption",
        new String[] { "PrintVMOptions"}, signatures);

    CompositeData data = (CompositeData)obj;
    validateType(data);

    VMOption option = mxbean.getVMOption("PrintVMOptions");
    VMOption o = VMOption.from(data);
    assertEquals(option, o);
}
 
Example 2
Source File: AMXGlassfish.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
    Invoke the waitAMXReady() method on the DomainRoot MBean, which must already be loaded.
 */
private static void invokeWaitAMXReady(final MBeanServerConnection conn, final ObjectName objectName)
{
    try
    {
        conn.invoke( objectName, "waitAMXReady", null, null );
    }
    catch( final Exception e )
    {
        throw new RuntimeException(e);
    }
}
 
Example 3
Source File: JBoss.java    From ysoserial-modified with MIT License 5 votes vote down vote up
private static void doExploit ( final Object payloadObject, MBeanServerConnection mbc )
        throws IOException, InstanceNotFoundException, IntrospectionException, ReflectionException {
    Object[] params = new Object[1];
    params[ 0 ] = payloadObject;
    System.err.println("Querying MBeans");
    Set<ObjectInstance> testMBeans = mbc.queryMBeans(null, null);
    System.err.println("Found " + testMBeans.size() + " MBeans");
    for ( ObjectInstance oi : testMBeans ) {
        MBeanInfo mBeanInfo = mbc.getMBeanInfo(oi.getObjectName());
        for ( MBeanOperationInfo opInfo : mBeanInfo.getOperations() ) {
            try {
                mbc.invoke(oi.getObjectName(), opInfo.getName(), params, new String[] {});
                System.err.println(oi.getObjectName() + ":" + opInfo.getName() + " -> SUCCESS");
                return;
            }
            catch ( Throwable e ) {
                String msg = e.getMessage();
                if ( msg.startsWith("java.lang.ClassNotFoundException:") ) {
                    int start = msg.indexOf('"');
                    int stop = msg.indexOf('"', start + 1);
                    String module = ( start >= 0 && stop > 0 ) ? msg.substring(start + 1, stop) : "<unknown>";
                    if ( !"<unknown>".equals(module) && !"org.jboss.as.jmx:main".equals(module) ) {
                        int cstart = msg.indexOf(':');
                        int cend = msg.indexOf(' ', cstart + 2);
                        String cls = msg.substring(cstart + 2, cend);
                        System.err.println(oi.getObjectName() + ":" + opInfo.getName() + " -> FAIL CNFE " + cls + " (" + module + ")");
                    }
                }
                else {
                    System.err.println(oi.getObjectName() + ":" + opInfo.getName() + " -> SUCCESS|ERROR " + msg);
                    return;
                }
            }
        }
    }
}
 
Example 4
Source File: ThreadDump.java    From java-svc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) throws IOException, AttachException, InstanceNotFoundException,
		MalformedObjectNameException, MBeanException, ReflectionException {
	AttachUtils.printJVMVersion();
	String pid = AttachUtils.checkPid(args);
	JMXConnector connector = JMXConnectorFactory.connect(AttachUtils.startLocalAgent(pid));

	MBeanServerConnection connection = connector.getMBeanServerConnection();
	String result = (String) connection.invoke(new ObjectName(DC_OBJECT_NAME), "threadPrint",
			new Object[] { new String[0] }, new String[] { String[].class.getName() });
	System.out.println(result);
}
 
Example 5
Source File: ModelControllerMBeanTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testResolveExpressions() throws Exception {
    MBeanServerConnection connection = setupAndGetConnection(new BaseAdditionalInitialization(ProcessType.STANDALONE_SERVER));
    System.clearProperty("jboss.test.resolve.expressions.test");
    Assert.assertEquals("123", connection.invoke(LEGACY_ROOT_NAME, "resolveExpression", new String[]{"${jboss.test.resolve.expressions.test:123}"}, new String[]{String.class.getName()}));

    try {
        connection.invoke(LEGACY_ROOT_NAME, "resolveExpression", new String[]{"${jboss.test.resolve.expressions.test}"}, new String[]{String.class.getName()});
        Assert.fail("Should not have been able to resolve non-existent property");
    } catch (Exception expected) {
        //expected
    }

}
 
Example 6
Source File: JmxRBACProviderHostScopedRolesTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void doOperation(boolean successExpected, String objectName, String operationName, JmxManagementInterface jmx) throws Exception {
    MBeanServerConnection connection = jmx.getConnection();
    ObjectName domain = new ObjectName(objectName);
    try {
        connection.invoke(domain, operationName, ArrayUtils.EMPTY_OBJECT_ARRAY, ArrayUtils.EMPTY_STRING_ARRAY);
        assertTrue("Failure was expected but success happened", successExpected);
    } catch (JMRuntimeException e) {
        if (e.getMessage().contains("WFLYJMX0037")) {
            assertFalse("Success was expected but failure happened: " + e, successExpected);
        } else {
            throw e;
        }
    }
}
 
Example 7
Source File: FuseAdapterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Object assertJmxInvoke(boolean expectSuccess, MBeanServerConnection connection, ObjectName mbean, String method,
        Object[] params, String[] signature) throws InstanceNotFoundException, MBeanException, ReflectionException, IOException {
    try {
        Object result = connection.invoke(mbean, method, params, signature);
        assertTrue(expectSuccess);
        return result;
    } catch (SecurityException se) {
        assertTrue(!expectSuccess);
        return null;
    }
}
 
Example 8
Source File: VirtualMachineMetrics.java    From spring-init with Apache License 2.0 5 votes vote down vote up
private static void gc(MBeanServerConnection mBeanServer) {
	try {
		final ObjectName on = new ObjectName("java.lang:type=Memory");
		mBeanServer.getMBeanInfo(on);
		mBeanServer.invoke(on, "gc", new Object[0], new String[0]);
	}
	catch (Exception ignored) {
		System.err.println("Unable to gc");
	}
}
 
Example 9
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 10
Source File: MXBeanInteropTest2.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
private final int doBasicMXBeanTest(MBeanServerConnection mbsc) {
    int errorCount = 0 ;
    System.out.println("---- doBasicMXBeanTest") ;

    try {
        ObjectName objName =
                new ObjectName("sqe:type=BasicMXBean") ;
        mbsc.createMBean(BASIC_MXBEAN_CLASS_NAME, objName);
        MBeanInfo mbInfo = mbsc.getMBeanInfo(objName);
        printMBeanInfo(mbInfo);
        System.out.println("---- OK\n") ;
        System.out.println("getMBeanInfo\t\t"
                + mbInfo);
        System.out.println("---- OK\n") ;

        System.out.println("Check mxbean field in the MBeanInfo");
        String mxbeanField =
                (String)mbInfo.getDescriptor().getFieldValue(JMX.MXBEAN_FIELD);

        if ( mxbeanField == null || ! mxbeanField.equals("true")) {
            System.out.println("---- ERROR : Improper mxbean field value "
                    + mxbeanField);
            errorCount++;
        }
        System.out.println("---- OK\n") ;

        System.out.println("Set attribute ObjectNameAtt");
        Attribute att = new Attribute("ObjectNameAtt", objName);
        mbsc.setAttribute(objName, att);
        ObjectName value =
                (ObjectName)mbsc.getAttribute(objName, "ObjectNameAtt");

        if ( ! value.equals(objName) ) {
            errorCount++;
            System.out.println("---- ERROR : setAttribute failed, got "
                    + value
                    + " while expecting "
                    + objName);
        }
        System.out.println("---- OK\n") ;

        System.out.println("Call operation doNothing");
        mbsc.invoke(objName,  "doNothing", null, null);
        System.out.println("---- OK\n") ;

        System.out.println("Call operation getWeather");
        Object weather = mbsc.invoke(objName,
                "getWeather",
                new Object[]{Boolean.TRUE},
                new String[]{"boolean"});
        System.out.println("Weather is " + weather);
        System.out.println("---- OK\n") ;
    } catch (Exception e) {
        Utils.printThrowable(e, true) ;
        errorCount++ ;
        System.out.println("---- ERROR\n") ;
    }

    return errorCount ;
}
 
Example 11
Source File: MXBeanInteropTest2.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
private final int doBasicMXBeanTest(MBeanServerConnection mbsc) {
    int errorCount = 0 ;
    System.out.println("---- doBasicMXBeanTest") ;

    try {
        ObjectName objName =
                new ObjectName("sqe:type=BasicMXBean") ;
        mbsc.createMBean(BASIC_MXBEAN_CLASS_NAME, objName);
        MBeanInfo mbInfo = mbsc.getMBeanInfo(objName);
        printMBeanInfo(mbInfo);
        System.out.println("---- OK\n") ;
        System.out.println("getMBeanInfo\t\t"
                + mbInfo);
        System.out.println("---- OK\n") ;

        System.out.println("Check mxbean field in the MBeanInfo");
        String mxbeanField =
                (String)mbInfo.getDescriptor().getFieldValue(JMX.MXBEAN_FIELD);

        if ( mxbeanField == null || ! mxbeanField.equals("true")) {
            System.out.println("---- ERROR : Improper mxbean field value "
                    + mxbeanField);
            errorCount++;
        }
        System.out.println("---- OK\n") ;

        System.out.println("Set attribute ObjectNameAtt");
        Attribute att = new Attribute("ObjectNameAtt", objName);
        mbsc.setAttribute(objName, att);
        ObjectName value =
                (ObjectName)mbsc.getAttribute(objName, "ObjectNameAtt");

        if ( ! value.equals(objName) ) {
            errorCount++;
            System.out.println("---- ERROR : setAttribute failed, got "
                    + value
                    + " while expecting "
                    + objName);
        }
        System.out.println("---- OK\n") ;

        System.out.println("Call operation doNothing");
        mbsc.invoke(objName,  "doNothing", null, null);
        System.out.println("---- OK\n") ;

        System.out.println("Call operation getWeather");
        Object weather = mbsc.invoke(objName,
                "getWeather",
                new Object[]{Boolean.TRUE},
                new String[]{"boolean"});
        System.out.println("Weather is " + weather);
        System.out.println("---- OK\n") ;
    } catch (Exception e) {
        Utils.printThrowable(e, true) ;
        errorCount++ ;
        System.out.println("---- ERROR\n") ;
    }

    return errorCount ;
}
 
Example 12
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 13
Source File: MXBeanProxy.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
Object invoke(MBeanServerConnection mbsc, ObjectName name, Object[] args)
        throws Exception {
    return mbsc.invoke(name, getName(), args, signature);
}
 
Example 14
Source File: MissingClassTest.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
private static boolean notifyTest(JMXConnector client,
                                  MBeanServerConnection mbsc)
        throws Exception {
    System.out.println("Send notifications including unknown ones");
    result = new Result();
    LostListener ll = new LostListener();
    client.addConnectionNotificationListener(ll, null, null);
    TestListener nl = new TestListener(ll);
    mbsc.addNotificationListener(on, nl, new TestFilter(), null);
    mbsc.invoke(on, "sendNotifs", NO_OBJECTS, NO_STRINGS);

    // wait for the listeners to receive all their notifs
    // or to fail
    long deadline = System.currentTimeMillis() + 60000;
    long remain;
    while ((remain = deadline - System.currentTimeMillis()) >= 0) {
        synchronized (result) {
            if (result.failed
                || (result.knownCount >= NNOTIFS
                    && result.lostCount >= NNOTIFS*2))
                break;
            result.wait(remain);
        }
    }
    Thread.sleep(2);  // allow any spurious extra notifs to arrive
    if (result.failed) {
        System.out.println("TEST FAILS: Notification strangeness");
        return false;
    } else if (result.knownCount == NNOTIFS
               && result.lostCount == NNOTIFS*2) {
        System.out.println("Success: received known notifications and " +
                           "got NOTIFS_LOST for unknown and " +
                           "unserializable ones");
        return true;
    } else if (result.knownCount >= NNOTIFS
            || result.lostCount >= NNOTIFS*2) {
        System.out.println("TEST FAILS: Received too many notifs: " +
                "known=" + result.knownCount + "; lost=" + result.lostCount);
        return false;
    } else {
        System.out.println("TEST FAILS: Timed out without receiving " +
                           "all notifs: known=" + result.knownCount +
                           "; lost=" + result.lostCount);
        return false;
    }
}
 
Example 15
Source File: MissingClassTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
private static boolean notifyTest(JMXConnector client,
                                  MBeanServerConnection mbsc)
        throws Exception {
    System.out.println("Send notifications including unknown ones");
    result = new Result();
    LostListener ll = new LostListener();
    client.addConnectionNotificationListener(ll, null, null);
    TestListener nl = new TestListener(ll);
    mbsc.addNotificationListener(on, nl, new TestFilter(), null);
    mbsc.invoke(on, "sendNotifs", NO_OBJECTS, NO_STRINGS);

    // wait for the listeners to receive all their notifs
    // or to fail
    long deadline = System.currentTimeMillis() + 60000;
    long remain;
    while ((remain = deadline - System.currentTimeMillis()) >= 0) {
        synchronized (result) {
            if (result.failed
                || (result.knownCount >= NNOTIFS
                    && result.lostCount >= NNOTIFS*2))
                break;
            result.wait(remain);
        }
    }
    Thread.sleep(2);  // allow any spurious extra notifs to arrive
    if (result.failed) {
        System.out.println("TEST FAILS: Notification strangeness");
        return false;
    } else if (result.knownCount == NNOTIFS
               && result.lostCount == NNOTIFS*2) {
        System.out.println("Success: received known notifications and " +
                           "got NOTIFS_LOST for unknown and " +
                           "unserializable ones");
        return true;
    } else if (result.knownCount >= NNOTIFS
            || result.lostCount >= NNOTIFS*2) {
        System.out.println("TEST FAILS: Received too many notifs: " +
                "known=" + result.knownCount + "; lost=" + result.lostCount);
        return false;
    } else {
        System.out.println("TEST FAILS: Timed out without receiving " +
                           "all notifs: known=" + result.knownCount +
                           "; lost=" + result.lostCount);
        return false;
    }
}
 
Example 16
Source File: EmptyDomainNotificationTest.java    From TencentKona-8 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 17
Source File: NotSerializableNotifTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
private static void test(String proto) throws Exception {
    System.out.println("\n>>> Test for protocol " + proto);

    JMXServiceURL url = new JMXServiceURL(proto, null, 0);

    System.out.println(">>> Create a server: "+url);

    JMXConnectorServer server = null;
    try {
        server = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbeanServer);
    } catch (MalformedURLException e) {
        System.out.println("System does not recognize URL: " + url +
                           "; ignoring");
        return;
    }

    server.start();

    url = server.getAddress();

    System.out.println(">>> Creating a client connectint to: "+url);
    JMXConnector conn = JMXConnectorFactory.connect(url, null);
    MBeanServerConnection client = conn.getMBeanServerConnection();

    // add listener from the client side
    Listener listener = new Listener();
    client.addNotificationListener(emitter, listener, null, null);

    // ask to send one not serializable notif
    Object[] params = new Object[] {new Integer(1)};
    String[] signatures = new String[] {"java.lang.Integer"};
    client.invoke(emitter, "sendNotserializableNotifs", params, signatures);

    // listener clean
    client.removeNotificationListener(emitter, listener);
    listener = new Listener();
    client.addNotificationListener(emitter, listener, null, null);

    //ask to send serializable notifs
    params = new Object[] {new Integer(sentNotifs)};
    client.invoke(emitter, "sendNotifications", params, signatures);

    // waiting ...
    synchronized (listener) {
        while (listener.received() < sentNotifs) {
            listener.wait(); // either pass or test timeout (killed by test harness)

        }
    }

    // clean
    client.removeNotificationListener(emitter, listener);

    conn.close();
    server.stop();
}
 
Example 18
Source File: AddGetReleaseRemoveTest.java    From scheduling with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
public void action() throws Exception {

    final ResourceManager rm = rmHelper.getResourceManager();
    // The username and thr password must be the same a used to connect to the RM
    final String adminLogin = TestUsers.TEST.username;
    final String adminPassword = TestUsers.TEST.password;

    // All accounting values are checked through JMX
    final RMAuthentication auth = rmHelper.getRMAuth();
    final PublicKey pubKey = auth.getPublicKey();
    final Credentials adminCreds = Credentials.createCredentials(new CredData(adminLogin, adminPassword), pubKey);

    final JMXServiceURL jmxRmiServiceURL = new JMXServiceURL(auth.getJMXConnectorURL(JMXTransportProtocol.RMI));
    final HashMap<String, Object> env = new HashMap<>(1);
    env.put(JMXConnector.CREDENTIALS, new Object[] { adminLogin, adminCreds });

    // Connect to the JMX RMI Connector Server
    final ObjectName myAccountMBeanName = new ObjectName(RMJMXBeans.MYACCOUNT_MBEAN_NAME);
    final ObjectName managementMBeanName = new ObjectName(RMJMXBeans.MANAGEMENT_MBEAN_NAME);
    final JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxRmiServiceURL, env);
    final MBeanServerConnection conn = jmxConnector.getMBeanServerConnection();

    // Ensure that no refreshes was done and all account values are correctly initialized        
    AttributeList atts = conn.getAttributes(myAccountMBeanName,
                                            new String[] { "UsedNodeTime", "ProvidedNodeTime",
                                                           "ProvidedNodesCount" });

    long usedNodeTime = (Long) ((Attribute) atts.get(0)).getValue();
    long providedNodeTime = (Long) ((Attribute) atts.get(1)).getValue();
    int providedNodesCount = (Integer) ((Attribute) atts.get(2)).getValue();

    // ADD, GET, RELEASE, REMOVE
    // 1) ADD
    final long beforeAddTime = System.currentTimeMillis();
    testNode = rmHelper.createNode("test");
    Node node = testNode.getNode();
    final String nodeURL = node.getNodeInformation().getURL();
    rm.addNode(nodeURL).getBooleanValue();

    // We eat the configuring to free event
    rmHelper.waitForNodeEvent(RMEventType.NODE_ADDED, nodeURL);
    rmHelper.waitForNodeEvent(RMEventType.NODE_STATE_CHANGED, nodeURL);
    // 2) GET
    final long beforeGetTime = System.currentTimeMillis();
    node = rm.getAtMostNodes(1, null).get(0);

    // Sleep a certain amount of time that will be the minimum amount of the GET->RELEASE duration 
    Thread.sleep(GR_DURATION);

    // 3) RELEASE
    rm.releaseNode(node).getBooleanValue();
    final long getReleaseMaxDuration = System.currentTimeMillis() - beforeGetTime;

    // 4) REMOVE  
    rm.removeNode(nodeURL, true).getBooleanValue();
    final long addRemoveMaxDuration = System.currentTimeMillis() - beforeAddTime;

    // Refresh the account manager
    conn.invoke(managementMBeanName, "clearAccoutingCache", null, null);

    // Check account values validity                      
    atts = conn.getAttributes(myAccountMBeanName,
                              new String[] { "UsedNodeTime", "ProvidedNodeTime", "ProvidedNodesCount" });
    usedNodeTime = (Long) ((Attribute) atts.get(0)).getValue() - usedNodeTime;
    providedNodeTime = (Long) ((Attribute) atts.get(1)).getValue() - providedNodeTime;
    providedNodesCount = (Integer) ((Attribute) atts.get(2)).getValue() - providedNodesCount;

    Assert.assertTrue("Invalid value of the usedNodeTime attribute (usedNodeTime=" + usedNodeTime + ")",
                      (usedNodeTime >= GR_DURATION));
    Assert.assertTrue("Invalid value of the usedNodeTime attribute (getReleaseMaxDuration=" +
                      getReleaseMaxDuration + ")", (usedNodeTime <= getReleaseMaxDuration));
    Assert.assertTrue("Invalid value of the providedNodeTime attribute",
                      (providedNodeTime >= usedNodeTime) && (providedNodeTime <= addRemoveMaxDuration));
}
 
Example 19
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 20
Source File: UnexpectedNotifTest.java    From jdk8u-jdk 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();
}