Java Code Examples for javax.management.MBeanServer#registerMBean()

The following examples show how to use javax.management.MBeanServer#registerMBean() . 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: ExceptionDiagnosisTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void testCaseProb() throws Exception {
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    ObjectName name = new ObjectName("a:b=c");
    mbs.registerMBean(new CaseProbImpl(), name);
    CaseProbMXBean proxy = JMX.newMXBeanProxy(mbs, name, CaseProbMXBean.class);
    try {
        CaseProb prob = proxy.getCaseProb();
        fail("No exception from proxy method getCaseProb");
    } catch (IllegalArgumentException e) {
        String messageChain = messageChain(e);
        if (messageChain.contains("URLPath")) {
            System.out.println("Message chain contains URLPath as required: "
                    + messageChain);
        } else {
            fail("Exception chain for CaseProb does not mention property" +
                    " URLPath differing only in case");
            System.out.println("Full stack trace:");
            e.printStackTrace(System.out);
        }
    }
}
 
Example 2
Source File: ShardStateWorker.java    From blueflood with Apache License 2.0 6 votes vote down vote up
ShardStateWorker(Collection<Integer> allShards, ShardStateManager shardStateManager, TimeValue period, ShardStateIO io) {
    this.shardStateManager = shardStateManager;
    this.allShards = Collections.unmodifiableCollection(allShards);
    this.periodMs = period.toMillis();
    this.io = io;
    
    try {
        final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        String name = String.format("com.rackspacecloud.blueflood.service:type=%s", getClass().getSimpleName());
        final ObjectName nameObj = new ObjectName(name);
        mbs.registerMBean(this, nameObj);
        activeGauge = Metrics.getRegistry().register(MetricRegistry.name(getClass(), "Active"),
                new JmxBooleanGauge(nameObj, "Active"));

        periodGauge = Metrics.getRegistry().register(MetricRegistry.name(getClass(), "Period"),
                new JmxAttributeGauge(nameObj, "Period"));

    } catch (Exception exc) {
        // not critical (as in tests), but we want it logged.
        log.error("Unable to register mbean for " + getClass().getSimpleName());
        log.debug(exc.getMessage(), exc);
    }
    
    errors = Metrics.counter(getClass(), "Poll Errors");
}
 
Example 3
Source File: ImmutableNotificationInfoTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static boolean test(Object mbean, boolean expectImmutable)
        throws Exception {
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    ObjectName on = new ObjectName("a:b=c");
    mbs.registerMBean(mbean, on);
    MBeanInfo mbi = mbs.getMBeanInfo(on);
    Descriptor d = mbi.getDescriptor();
    String immutableValue = (String) d.getFieldValue("immutableInfo");
    boolean immutable = ("true".equals(immutableValue));
    if (immutable != expectImmutable) {
        System.out.println("FAILED: " + mbean.getClass().getName() +
                " -> " + immutableValue);
        return false;
    } else {
        System.out.println("OK: " + mbean.getClass().getName());
        return true;
    }
}
 
Example 4
Source File: Server.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void main(String[] args) throws Exception
{
   // The address of the connector server
   JMXServiceURL url = new JMXServiceURL("rmi", "localhost", 0, "/jndi/jmx");

   // No need of environment variables or the MBeanServer at this point
   JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, null);
   ObjectName cntorServerName = ObjectName.getInstance(":service=" + JMXConnectorServer.class.getName() + ",protocol=" + url.getProtocol());

   MBeanServer server = MBeanServerFactory.createMBeanServer("remote.notification.example");
   // Register the connector server as MBean
   server.registerMBean(cntorServer, cntorServerName);

   // The rmiregistry needed to bind the RMI stub
   NamingService naming = new NamingService();
   ObjectName namingName = ObjectName.getInstance(":service=" + NamingService.class.getName());
   server.registerMBean(naming, namingName);
   naming.start();

   // Start the connector server
   cntorServer.start();

   System.out.println("Server up and running");
}
 
Example 5
Source File: ListenerScaleTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    Sender sender = new Sender();
    mbs.registerMBean(sender, testObjectName);
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");
    JMXConnectorServer cs =
        JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    cs.start();
    JMXServiceURL addr = cs.getAddress();
    JMXConnector cc = JMXConnectorFactory.connect(addr);
    try {
        test(mbs, cs, cc);
    } finally {
        cc.close();
        cs.stop();
    }
}
 
Example 6
Source File: TestDynamicMBeanWrapper.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Test // just to ensure MBeanRegistrationSupport doesn't break anything
public void normalMBeanCanStillBeRegistered() throws Exception {
    final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    final DynamicMBeanWrapper wrapper = new DynamicMBeanWrapper(new MyNotLifecycleAwareMBean());
    final ObjectName on = new ObjectName("org.superbiz.foo:type=dummy2");
    try {
        server.registerMBean(wrapper, on);
        assertTrue(server.isRegistered(on));
        assertEquals("ok", server.invoke(on, "value", new Object[0], null));
    } finally {
        server.unregisterMBean(on);
    }
}
 
Example 7
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 8
Source File: QueryMatchTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static int query(MBeanServer mbs,
                         String pattern,
                         String[][] data) throws Exception {

    int error = 0;

    System.out.println("\nAttribute Value Pattern = " + pattern + "\n");
    for (int i = 0; i < data.length; i++) {
        ObjectName on = new ObjectName("domain:type=Simple,pattern=" +
                                       ObjectName.quote(pattern) +
                                       ",name=" + i);
        Simple s = new Simple(data[i][0]);
        mbs.registerMBean(s, on);
        QueryExp q =
            Query.match(Query.attr("StringNumber"), Query.value(pattern));
        q.setMBeanServer(mbs);
        boolean r = q.apply(on);
        System.out.print("Attribute Value = " +
            mbs.getAttribute(on, "StringNumber"));
        if (r && "OK".equals(data[i][1])) {
            System.out.println(" OK");
        } else if (!r && "KO".equals(data[i][1])) {
            System.out.println(" KO");
        } else {
            System.out.println(" Error");
            error++;
        }
    }

    return error;
}
 
Example 9
Source File: MXBeanTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static void testExplicitMXBean() throws Exception {
    System.out.println("Explicit MXBean test...");
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    ObjectName on = new ObjectName("test:type=Explicit");
    Explicit explicit = new Explicit();
    mbs.registerMBean(explicit, on);
    testMXBean(mbs, on);
}
 
Example 10
Source File: ExceptionDiagnosisTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void testMXBeans(Object mbean, Type... expectedTypes)
        throws Exception {
    try {
        MBeanServer mbs = MBeanServerFactory.newMBeanServer();
        ObjectName name = new ObjectName("a:b=c");
        mbs.registerMBean(mbean, name);
        fail("No exception from registerMBean for " + mbean);
    } catch (NotCompliantMBeanException e) {
        checkExceptionChain("MBean " + mbean, e, expectedTypes);
    }
}
 
Example 11
Source File: MXBeanTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static void testSubclassMXBean() throws Exception {
    System.out.println("Subclass MXBean test...");
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    ObjectName on = new ObjectName("test:type=Subclass");
    Subclass subclass = new Subclass();
    mbs.registerMBean(subclass, on);
    testMXBean(mbs, on);
}
 
Example 12
Source File: ParserInfiniteLoopTest.java    From openjdk-jdk8u 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>)");
        String testSrc = System.getProperty("test.src");
        System.out.println("test.src = " + testSrc);
        String urlCodebase;
        if (testSrc.startsWith("/")) {
            urlCodebase =
                "file:" + testSrc.replace(File.separatorChar, '/') + "/";
        } else {
            urlCodebase =
                "file:/" + testSrc.replace(File.separatorChar, '/') + "/";
        }
        String mletFile = urlCodebase + args[0];
        System.out.println("MLet File = " + mletFile);
        try {
            mlet.getMBeansFromURL(mletFile);
            System.out.println(
                "TEST FAILED: Expected ServiceNotFoundException not thrown");
            error = true;
        } catch (ServiceNotFoundException e) {
            if (e.getCause() == null) {
                System.out.println("TEST FAILED: Got unexpected null cause " +
                    "in ServiceNotFoundException");
                error = true;
            } else if (!(e.getCause() instanceof IOException)) {
                System.out.println("TEST FAILED: Got unexpected non-null " +
                    "cause in ServiceNotFoundException");
                error = true;
            } else {
                System.out.println("TEST PASSED: Got expected non-null " +
                    "cause in ServiceNotFoundException");
                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 13
Source File: MXBeanTest.java    From openjdk-jdk8u-backup 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 14
Source File: MXBeanTest.java    From hottub 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: ThreadPoolAccTest.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 {

        ObjectName[] mbeanNames = new ObjectName[6];
        ObservedObject[] monitored = new ObservedObject[6];
        ObjectName[] monitorNames = new ObjectName[6];
        Monitor[] monitor = new Monitor[6];
        String[] principals = { "role1", "role2" };
        String[] attributes = { "Integer", "Double", "String" };

        try {
            echo(">>> CREATE MBeanServer");
            MBeanServer server = MBeanServerFactory.newMBeanServer();

            for (int i = 0; i < 6; i++) {
                mbeanNames[i] =
                    new ObjectName(":type=ObservedObject,instance=" + i);
                monitored[i] = new ObservedObject();
                echo(">>> CREATE ObservedObject = " + mbeanNames[i].toString());
                server.registerMBean(monitored[i], mbeanNames[i]);

                switch (i) {
                    case 0:
                    case 3:
                        monitorNames[i] =
                            new ObjectName(":type=CounterMonitor,instance=" + i);
                        monitor[i] = new CounterMonitor();
                        break;
                    case 1:
                    case 4:
                        monitorNames[i] =
                            new ObjectName(":type=GaugeMonitor,instance=" + i);
                        monitor[i] = new GaugeMonitor();
                        break;
                    case 2:
                    case 5:
                        monitorNames[i] =
                            new ObjectName(":type=StringMonitor,instance=" + i);
                        monitor[i] = new StringMonitor();
                        break;
                }

                echo(">>> CREATE Monitor = " + monitorNames[i].toString());
                server.registerMBean(monitor[i], monitorNames[i]);
                monitor[i].addObservedObject(mbeanNames[i]);
                monitor[i].setObservedAttribute(attributes[i % 3]);
                monitor[i].setGranularityPeriod(500);
                final Monitor m = monitor[i];
                Subject subject = new Subject();
                echo(">>> RUN Principal = " + principals[i / 3]);
                subject.getPrincipals().add(new JMXPrincipal(principals[i / 3]));
                PrivilegedAction<Void> action = new PrivilegedAction<Void>() {
                    public Void run() {
                        m.start();
                        return null;
                    }
                };
                Subject.doAs(subject, action);
            }

            while(!testPrincipals(monitored, monitorNames, monitor, principals));

        } finally {
            for (int i = 0; i < 6; i++)
                if (monitor[i] != null)
                    monitor[i].stop();
        }
    }
 
Example 16
Source File: CounterMonitorDeadlockTest.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
void run() throws Exception {
    final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    final ObjectName observedName = new ObjectName("a:b=c");
    final ObjectName monitorName = new ObjectName("a:type=Monitor");
    mbs.registerMBean(new CounterMonitor(), monitorName);
    final CounterMonitorMBean monitorProxy =
        JMX.newMBeanProxy(mbs, monitorName, CounterMonitorMBean.class);
    final TestMBean observedProxy =
        JMX.newMBeanProxy(mbs, observedName, TestMBean.class);

    final Runnable sensitiveThing = new Runnable() {
        public void run() {
            doSensitiveThing(monitorProxy, observedName);
        }
    };

    final Runnable nothing = new Runnable() {
        public void run() {}
    };

    final Runnable withinGetAttribute =
        (when == When.IN_GET_ATTRIBUTE) ? sensitiveThing : nothing;

    mbs.registerMBean(new Test(withinGetAttribute), observedName);
    monitorProxy.addObservedObject(observedName);
    monitorProxy.setObservedAttribute("Thing");
    monitorProxy.setInitThreshold(100);
    monitorProxy.setGranularityPeriod(10L); // 10 ms
    monitorProxy.setNotify(true);
    monitorProxy.start();

    final int initGetCount = observedProxy.getGetCount();
    int getCount = initGetCount;
    for (int i = 0; i < 500; i++) { // 500 * 10 = 5 seconds
        getCount = observedProxy.getGetCount();
        if (getCount != initGetCount)
            break;
        Thread.sleep(10);
    }
    if (getCount <= initGetCount)
        throw new Exception("Test failed: presumable deadlock");
    // This won't show up as a deadlock in CTRL-\ or in
    // ThreadMXBean.findDeadlockedThreads(), because they don't
    // see that thread A is waiting for thread B (B.join()), and
    // thread B is waiting for a lock held by thread A

    // Now we know the monitor has observed the initial value,
    // so if we want to test notify behaviour we can trigger by
    // exceeding the threshold.
    if (when == When.IN_NOTIFY) {
        final AtomicInteger notifCount = new AtomicInteger();
        final NotificationListener listener = new NotificationListener() {
            public void handleNotification(Notification n, Object h) {
                Thread t = new Thread(sensitiveThing);
                t.start();
                try {
                    t.join();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                notifCount.incrementAndGet();
            }
        };
        mbs.addNotificationListener(monitorName, listener, null, null);
        observedProxy.setThing(1000);
        for (int i = 0; i < 500 && notifCount.get() == 0; i++)
            Thread.sleep(10);
        if (notifCount.get() == 0)
            throw new Exception("Test failed: presumable deadlock");
    }

}
 
Example 17
Source File: CounterMonitorThresholdTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public static void runTest(int offset,
                           int counter[],
                           int derivedGauge[],
                           int threshold[]) throws Exception {
    // Retrieve the platform MBean server
    //
    System.out.println("\nRetrieve the platform MBean server");
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    String domain = mbs.getDefaultDomain();

    // Create and register TestMBean
    //
    ObjectName name =
        new ObjectName(domain +
                       ":type=" + Test.class.getName() +
                       ",offset=" + offset);
    mbs.createMBean(Test.class.getName(), name);
    TestMBean mbean = (TestMBean)
        MBeanServerInvocationHandler.newProxyInstance(
            mbs, name, TestMBean.class, false);

    // Create and register CounterMonitorMBean
    //
    ObjectName cmn =
        new ObjectName(domain +
                       ":type=" + CounterMonitor.class.getName() +
                       ",offset=" + offset);
    CounterMonitor m = new CounterMonitor();
    mbs.registerMBean(m, cmn);
    CounterMonitorMBean cm = (CounterMonitorMBean)
        MBeanServerInvocationHandler.newProxyInstance(
            mbs, cmn, CounterMonitorMBean.class, true);
    ((NotificationEmitter) cm).addNotificationListener(
        new Listener(), null, null);
    cm.addObservedObject(name);
    cm.setObservedAttribute("Counter");
    cm.setGranularityPeriod(100);
    cm.setInitThreshold(1);
    cm.setOffset(offset);
    cm.setModulus(5);
    cm.setNotify(true);

    // Start the monitor
    //
    System.out.println("\nStart monitoring...");
    cm.start();

    // Play with counter
    //
    for (int i = 0; i < counter.length; i++) {
        mbean.setCounter(counter[i]);
        System.out.println("\nCounter = " + mbean.getCounter());
        Integer derivedGaugeValue;
        // either pass or test timeout (killed by test harness)
        // see 8025207
        do {
            Thread.sleep(150);
            derivedGaugeValue = (Integer) cm.getDerivedGauge(name);
        } while (derivedGaugeValue.intValue() != derivedGauge[i]);

        Number thresholdValue = cm.getThreshold(name);
        System.out.println("Threshold = " + thresholdValue);
        if (thresholdValue.intValue() != threshold[i]) {
            System.out.println("Wrong threshold! Current value = " +
                thresholdValue + " Expected value = " + threshold[i]);
            System.out.println("\nStop monitoring...");
            cm.stop();
            throw new IllegalArgumentException("wrong threshold");
        }
    }

    // Stop the monitor
    //
    System.out.println("\nStop monitoring...");
    cm.stop();
}
 
Example 18
Source File: GetMBeansFromURLTest.java    From openjdk-jdk8u 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 19
Source File: TooManyFooTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private static void test(Object child, String name, boolean mxbean)
    throws Exception {
    final ObjectName childName =
            new ObjectName("test:type=Child,name="+name);
    final MBeanServer server =
            ManagementFactory.getPlatformMBeanServer();
    server.registerMBean(child,childName);
    try {
        final MBeanInfo info = server.getMBeanInfo(childName);
        System.out.println(name+": " + info.getDescriptor());
        final int len = info.getOperations().length;
        if (len == OPCOUNT) {
            System.out.println(name+": OK, only "+OPCOUNT+
                    " operations here...");
        } else {
            final String qual = (len>OPCOUNT)?"many":"few";
            System.err.println(name+": Too "+qual+" foos! Found "+
                    len+", expected "+OPCOUNT);
            for (MBeanOperationInfo op : info.getOperations()) {
                System.err.println("public "+op.getReturnType()+" "+
                        op.getName()+"();");
            }
            throw new RuntimeException("Too " + qual +
                    " foos for "+name);
        }

        final Descriptor d = info.getDescriptor();
        final String mxstr = String.valueOf(d.getFieldValue("mxbean"));
        final boolean mxb =
                (mxstr==null)?false:Boolean.valueOf(mxstr).booleanValue();
        System.out.println(name+": mxbean="+mxb);
        if (mxbean && !mxb)
            throw new AssertionError("MXBean is not OpenMBean?");

        for (MBeanOperationInfo mboi : info.getOperations()) {

            // Sanity check
            if (mxbean && !mboi.getName().equals("foo")) {
                // The spec doesn't guarantee that the MBeanOperationInfo
                // of an MXBean will be an OpenMBeanOperationInfo, and in
                // some circumstances in our implementation it will not.
                // However, in thsi tests, for all methods but foo(),
                // it should.
                //
                if (!(mboi instanceof OpenMBeanOperationInfo))
                    throw new AssertionError("Operation "+mboi.getName()+
                            "() is not Open?");
            }

            final String exp = EXPECTED_TYPES.get(mboi.getName());

            // For MXBeans, we need to compare 'exp' with the original
            // type - because mboi.getReturnType() returns the OpenType
            //
            String type = (String)mboi.getDescriptor().
                        getFieldValue("originalType");
            if (type == null) type = mboi.getReturnType();
            if (type.equals(exp)) continue;
            System.err.println("Bad return type for "+
                    mboi.getName()+"! Found "+type+
                    ", expected "+exp);
            throw new RuntimeException("Bad return type for "+
                    mboi.getName());
        }
    } finally {
        server.unregisterMBean(childName);
    }
}
 
Example 20
Source File: SnmpMib.java    From dragonwell8_jdk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * <p>
 * Register an SNMP group and its metadata node in the MIB.
 * </p>
 *
 * <p>
 * This method is provided as a hook to plug-in some custom
 * specific behavior. You might want to override this method
 * if you want to set special links between the MBean, its metadata
 * node, its OID or ObjectName etc..
 * </p>
 *
 * <p>
 * If the MIB is not registered in the MBeanServer, the <code>
 * server</code> and <code>groupObjName</code> parameters will be
 * <code>null</code>.<br>
 * If the given group MBean is not <code>null</code>, and if the
 * <code>server</code> and <code>groupObjName</code> parameters are
 * not null, then this method will also automatically register the
 * group MBean with the given MBeanServer <code>server</code>.
 * </p>
 *
 * @param groupName  The java-ized name of the SNMP group.
 * @param groupOid   The OID as returned by getGroupOid() - in dot
 *                   notation.
 * @param groupObjName The ObjectName as returned by getGroupObjectName().
 *                   This parameter may be <code>null</code> if the
 *                   MIB is not registered in the MBeanServer.
 * @param node       The metadata node, as returned by the metadata
 *                   factory method for this group.
 * @param group      The MBean for this group, as returned by the
 *                   MBean factory method for this group.
 * @param server     The MBeanServer in which the groups are to be
 *                   registered. This parameter will be <code>null</code>
 *                   if the MIB is not registered, otherwise it is a
 *                   reference to the MBeanServer in which the MIB is
 *                   registered.
 *
 */
protected void registerGroupNode(String groupName,   String groupOid,
                                 ObjectName groupObjName, SnmpMibNode node,
                                 Object group, MBeanServer server)
    throws NotCompliantMBeanException, MBeanRegistrationException,
    InstanceAlreadyExistsException, IllegalAccessException {
    root.registerNode(groupOid,node);
    if (server != null && groupObjName != null && group != null)
        server.registerMBean(group,groupObjName);
}