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

The following examples show how to use javax.management.MBeanServer#createMBean() . 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: MLetCommand.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (System.getSecurityManager() == null)
        throw new IllegalStateException("No security manager installed!");

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

    // Instantiate the MBean server
    //
    System.out.println("Create the MBean server");
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();
    // Register the MLetMBean
    //
    System.out.println("Create MLet MBean");
    ObjectName mlet = new ObjectName("MLetTest:name=MLetMBean");
    mbs.createMBean("javax.management.loading.MLet", mlet);
    // Test OK!
    //
    System.out.println("Bye! Bye!");
}
 
Example 2
Source File: RepositoryWildcardTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static int mbeanCreation(MBeanServer mbs, String name)
    throws Exception {
    int error = 0;
    try {
        System.out.println("Test: createMBean(" + name + ")");
        mbs.createMBean(classname, ObjectName.getInstance(name));
        error++;
        System.out.println("Didn't get expected exception!");
        System.out.println("Test failed!");
    } catch (RuntimeOperationsException e) {
        System.out.println("Got expected exception = " +
                           e.getCause().toString());
        System.out.println("Test passed!");
    }
    return error;
}
 
Example 3
Source File: RepositoryWildcardTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static int mbeanCreation(MBeanServer mbs, String name)
    throws Exception {
    int error = 0;
    try {
        System.out.println("Test: createMBean(" + name + ")");
        mbs.createMBean(classname, ObjectName.getInstance(name));
        error++;
        System.out.println("Didn't get expected exception!");
        System.out.println("Test failed!");
    } catch (RuntimeOperationsException e) {
        System.out.println("Got expected exception = " +
                           e.getCause().toString());
        System.out.println("Test passed!");
    }
    return error;
}
 
Example 4
Source File: MLetCommand.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (System.getSecurityManager() == null)
        throw new IllegalStateException("No security manager installed!");

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

    // Instantiate the MBean server
    //
    System.out.println("Create the MBean server");
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();
    // Register the MLetMBean
    //
    System.out.println("Create MLet MBean");
    ObjectName mlet = new ObjectName("MLetTest:name=MLetMBean");
    mbs.createMBean("javax.management.loading.MLet", mlet);
    // Test OK!
    //
    System.out.println("Bye! Bye!");
}
 
Example 5
Source File: SystemClassLoaderTest.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 {
    // Instantiate the MBean server
    //
    System.out.println("Create the MBean server");
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();

    ClassLoader mbsClassLoader = mbs.getClass().getClassLoader();

    String testClassName = Test.class.getName();

    // Check that the MBeanServer class loader does not know our test class
    try {
        Class.forName(testClassName, true, mbsClassLoader);
        System.out.println("TEST IS INVALID: MBEANSERVER'S CLASS LOADER " +
                           "KNOWS OUR TEST CLASS");
        System.exit(1);
    } catch (ClassNotFoundException e) {
        // As required
    }

    // Register the MBean
    //
    System.out.println("Create MBean from this class");
    ObjectName objectName = new ObjectName("whatever:type=whatever");
    mbs.createMBean(testClassName, objectName);
    // Test OK!
    //
    System.out.println("Bye! Bye!");
}
 
Example 6
Source File: SystemClassLoaderTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Instantiate the MBean server
    //
    System.out.println("Create the MBean server");
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();

    ClassLoader mbsClassLoader = mbs.getClass().getClassLoader();

    String testClassName = Test.class.getName();

    // Check that the MBeanServer class loader does not know our test class
    try {
        Class.forName(testClassName, true, mbsClassLoader);
        System.out.println("TEST IS INVALID: MBEANSERVER'S CLASS LOADER " +
                           "KNOWS OUR TEST CLASS");
        System.exit(1);
    } catch (ClassNotFoundException e) {
        // As required
    }

    // Register the MBean
    //
    System.out.println("Create MBean from this class");
    ObjectName objectName = new ObjectName("whatever:type=whatever");
    mbs.createMBean(testClassName, objectName);
    // Test OK!
    //
    System.out.println("Bye! Bye!");
}
 
Example 7
Source File: MailExample.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Starts the http server
 */
public void start() throws JMException
{
   // creates new server
   MBeanServer server = MBeanServerFactory.createMBeanServer("Mail");
   ObjectName beanName = new ObjectName("Test:name=test");
   server.registerMBean(new TestClass("original"), beanName);

   ObjectName monitorName = new ObjectName("Test:name=monitor");
   server.createMBean("javax.management.monitor.StringMonitor", monitorName, null);

   server.setAttribute(monitorName, new Attribute("ObservedObject", beanName));
   server.setAttribute(monitorName, new Attribute("ObservedAttribute", "Str"));
   server.setAttribute(monitorName, new Attribute("StringToCompare", "original"));
   server.setAttribute(monitorName, new Attribute("GranularityPeriod", new Integer(100)));
   server.setAttribute(monitorName, new Attribute("NotifyDiffer", Boolean.TRUE));

   server.invoke(monitorName, "start", null, null);

   ObjectName mailerName = new ObjectName("Test:name=mailer");
   server.createMBean("mx4j.tools.mail.SMTP", mailerName, null);

   // Sets attributes
   server.setAttribute(mailerName, new Attribute("ObservedObject", monitorName));
   server.setAttribute(mailerName, new Attribute("NotificationName", "jmx.monitor.string.differs"));
   server.setAttribute(mailerName, new Attribute("FromAddress", "monitor@someserver"));
   server.setAttribute(mailerName, new Attribute("FromName", "MX4J"));
   server.setAttribute(mailerName, new Attribute("ServerHost", "smpt-server"));
   server.setAttribute(mailerName, new Attribute("To", "nobody@nobody"));
   server.setAttribute(mailerName, new Attribute("Subject", "Notification on $date$ at $time$"));
   server.setAttribute(mailerName, new Attribute("Content", "Notification on $datetime$ sent by $objectname$ on $observed$ monitor and a notification $notification$\nNotice how $$$$ gets expanded to $$"));

   // this will trigger the monitor and the mailer (Wait for 10 secs app)
   server.setAttribute(beanName, new Attribute("Str", "something-else"));

}
 
Example 8
Source File: SystemClassLoaderTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Instantiate the MBean server
    //
    System.out.println("Create the MBean server");
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();

    ClassLoader mbsClassLoader = mbs.getClass().getClassLoader();

    String testClassName = Test.class.getName();

    // Check that the MBeanServer class loader does not know our test class
    try {
        Class.forName(testClassName, true, mbsClassLoader);
        System.out.println("TEST IS INVALID: MBEANSERVER'S CLASS LOADER " +
                           "KNOWS OUR TEST CLASS");
        System.exit(1);
    } catch (ClassNotFoundException e) {
        // As required
    }

    // Register the MBean
    //
    System.out.println("Create MBean from this class");
    ObjectName objectName = new ObjectName("whatever:type=whatever");
    mbs.createMBean(testClassName, objectName);
    // Test OK!
    //
    System.out.println("Bye! Bye!");
}
 
Example 9
Source File: Server.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void main(String[] args) throws Exception
{
   MBeanServer server = MBeanServerFactory.createMBeanServer();

   // Register and start the rmiregistry MBean
   ObjectName namingName = ObjectName.getInstance("naming:type=rmiregistry");
   server.createMBean("mx4j.tools.naming.NamingService", namingName, null);
   server.invoke(namingName, "start", null, null);
   int namingPort = ((Integer)server.getAttribute(namingName, "Port")).intValue();

   String jndiPath = "/ssljmxconnector";
   JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://localhost/jndi/rmi://localhost:" + namingPort + jndiPath);

   // Create the rmi socket factories for SSL
   Map environment = new HashMap();
   SSLContext context = createSSLContext();
   environment.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, new SSLRMIClientSocketFactory());
   environment.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, new SSLRMIServerSocketFactory(context));

   // Create and start the RMIConnectorServer
   JMXConnectorServer connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, environment, null);
   ObjectName connectorServerName = ObjectName.getInstance("connectors:protocol=" + url.getProtocol());
   server.registerMBean(connectorServer, connectorServerName);
   connectorServer.start();

   System.out.println("Server up and running");
}
 
Example 10
Source File: CounterMonitorThresholdTest.java    From openjdk-jdk8u 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 11
Source File: CounterMonitorThresholdTest.java    From jdk8u60 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 12
Source File: MBeanExceptionTest.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 {
    System.out.println("Test that if an MBean throws RuntimeException " +
                       "it is wrapped in RuntimeMBeanException,");
    System.out.println("and if a Standard MBean throws Exception " +
                       "it is wrapped in MBeanException");
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    Object standard = new Except();
    ObjectName standardName = new ObjectName(":name=Standard MBean");
    Object standardMBean =
        new StandardMBean(new Except(), ExceptMBean.class);
    ObjectName standardMBeanName =
        new ObjectName(":name=Instance of StandardMBean");
    Object dynamic = new DynamicExcept();
    ObjectName dynamicName = new ObjectName(":name=Dynamic MBean");
    mbs.registerMBean(standard, standardName);
    mbs.registerMBean(standardMBean, standardMBeanName);
    mbs.registerMBean(dynamic, dynamicName);
    int failures = 0;
    failures += test(mbs, standardName, true);
    failures += test(mbs, standardMBeanName, true);
    failures += test(mbs, dynamicName, false);

    final boolean[] booleans = {false, true};

    for (boolean runtimeX : booleans) {
        Class<? extends Exception> excC =
                runtimeX ? RuntimeMBeanException.class : MBeanException.class;
        String excS =
                runtimeX ? "a RuntimeMBeanException" : "an MBeanException";
        String mbsS = "a plain MBeanServer";
        System.out.println(
                "Test that, with " + mbsS + ", " + excS + " is wrapped " +
                "in " + excS);
        // E.g. "Test that, with a plain MBeanServer, an MBeanException
        // is wrapped in an MBeanException".
        try {
            mbs.createMBean(
                    Except.class.getName(), new ObjectName(":name=Oops"),
                    new Object[] {runtimeX},
                    new String[] {boolean.class.getName()});
            System.out.println(
                    "FAIL: createMBean succeeded but should not have");
            failures++;
        } catch (Exception e) {
            if (!excC.isInstance(e)) {
                System.out.println(
                        "FAIL: expected " + excC.getName() + " from " +
                        "createMBean, got " + e);
                failures++;
            } else {
                Throwable cause = e.getCause();
                if (!excC.isInstance(cause)) {
                    System.out.println(
                            "FAIL: expected " + excC.getName() +
                            " as cause of " + excC.getName() +
                            ", got " + e);
                    failures++;
                } else
                    System.out.println("...ok");
            }
        }
    }

    if (failures == 0)
        System.out.println("Test passed");
    else {
        System.out.println("TEST FAILED: " + failures + " failure(s)");
        System.exit(1);
    }
}
 
Example 13
Source File: RelationNotificationSeqNoTest.java    From hottub 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 relSvcName = new ObjectName("a:type=relationService");
    RelationServiceMBean relSvc =
            JMX.newMBeanProxy(mbs, relSvcName, RelationServiceMBean.class);
    mbs.createMBean("javax.management.relation.RelationService",
                    relSvcName,
                    new Object[] {Boolean.TRUE},
                    new String[] {"boolean"});

    final BlockingQueue<Notification> q =
            new ArrayBlockingQueue<Notification>(100);
    NotificationListener qListener = new NotificationListener() {
        public void handleNotification(Notification notification,
                                       Object handback) {
            q.add(notification);
        }
    };
    mbs.addNotificationListener(relSvcName, qListener, null, null);

    RoleInfo leftInfo =
        new RoleInfo("left", "javax.management.timer.TimerMBean");
    RoleInfo rightInfo =
        new RoleInfo("right", "javax.management.timer.Timer");
    relSvc.createRelationType("typeName", new RoleInfo[] {leftInfo, rightInfo});
    ObjectName timer1 = new ObjectName("a:type=timer,number=1");
    ObjectName timer2 = new ObjectName("a:type=timer,number=2");
    mbs.createMBean("javax.management.timer.Timer", timer1);
    mbs.createMBean("javax.management.timer.Timer", timer2);

    Role leftRole =
        new Role("left", Arrays.asList(new ObjectName[] {timer1}));
    Role rightRole =
        new Role("right", Arrays.asList(new ObjectName[] {timer2}));
    RoleList roles =
        new RoleList(Arrays.asList(new Role[] {leftRole, rightRole}));

    final int NREPEAT = 10;

    for (int i = 0; i < NREPEAT; i++) {
        relSvc.createRelation("relationName", "typeName", roles);
        relSvc.removeRelation("relationName");
    }

    Notification firstNotif = q.remove();
    long seqNo = firstNotif.getSequenceNumber();
    for (int i = 0; i < NREPEAT * 2 - 1; i++) {
        Notification n = q.remove();
        long nSeqNo = n.getSequenceNumber();
        if (nSeqNo != seqNo + 1) {
            throw new Exception(
                    "TEST FAILED: expected seqNo " + (seqNo + 1) + "; got " +
                    nSeqNo);
        }
        seqNo++;
    }
    System.out.println("TEST PASSED: got " + (NREPEAT * 2) + " notifications " +
            "with contiguous sequence numbers");
}
 
Example 14
Source File: RelationNotificationSeqNoTest.java    From openjdk-8 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 relSvcName = new ObjectName("a:type=relationService");
    RelationServiceMBean relSvc =
            JMX.newMBeanProxy(mbs, relSvcName, RelationServiceMBean.class);
    mbs.createMBean("javax.management.relation.RelationService",
                    relSvcName,
                    new Object[] {Boolean.TRUE},
                    new String[] {"boolean"});

    final BlockingQueue<Notification> q =
            new ArrayBlockingQueue<Notification>(100);
    NotificationListener qListener = new NotificationListener() {
        public void handleNotification(Notification notification,
                                       Object handback) {
            q.add(notification);
        }
    };
    mbs.addNotificationListener(relSvcName, qListener, null, null);

    RoleInfo leftInfo =
        new RoleInfo("left", "javax.management.timer.TimerMBean");
    RoleInfo rightInfo =
        new RoleInfo("right", "javax.management.timer.Timer");
    relSvc.createRelationType("typeName", new RoleInfo[] {leftInfo, rightInfo});
    ObjectName timer1 = new ObjectName("a:type=timer,number=1");
    ObjectName timer2 = new ObjectName("a:type=timer,number=2");
    mbs.createMBean("javax.management.timer.Timer", timer1);
    mbs.createMBean("javax.management.timer.Timer", timer2);

    Role leftRole =
        new Role("left", Arrays.asList(new ObjectName[] {timer1}));
    Role rightRole =
        new Role("right", Arrays.asList(new ObjectName[] {timer2}));
    RoleList roles =
        new RoleList(Arrays.asList(new Role[] {leftRole, rightRole}));

    final int NREPEAT = 10;

    for (int i = 0; i < NREPEAT; i++) {
        relSvc.createRelation("relationName", "typeName", roles);
        relSvc.removeRelation("relationName");
    }

    Notification firstNotif = q.remove();
    long seqNo = firstNotif.getSequenceNumber();
    for (int i = 0; i < NREPEAT * 2 - 1; i++) {
        Notification n = q.remove();
        long nSeqNo = n.getSequenceNumber();
        if (nSeqNo != seqNo + 1) {
            throw new Exception(
                    "TEST FAILED: expected seqNo " + (seqNo + 1) + "; got " +
                    nSeqNo);
        }
        seqNo++;
    }
    System.out.println("TEST PASSED: got " + (NREPEAT * 2) + " notifications " +
            "with contiguous sequence numbers");
}
 
Example 15
Source File: AuthorizationTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
private JMXServiceURL createServerSide(Map<String, Object> serverMap)
throws Exception {
    final int NINETY_SECONDS = 90;

    System.out.println("AuthorizationTest::createServerSide: Start") ;

    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    JMXServiceURL url = new JMXServiceURL("rmi", null, 0);

    // Creates connection environment from server side params
    HashMap<String, Object> env = new HashMap<>();
    String value = null;

    if ((value = (String)serverMap.get("-mapType")) != null) {
        if (value.contains("x.access.file")) {
            String accessFileStr = System.getProperty("test.src") +
                File.separator + "access.properties";
            env.put("jmx.remote.x.access.file", accessFileStr);
            System.out.println("Added " + accessFileStr + " file as jmx.remote.x.access.file");
        }
        if (value.contains("x.password.file")) {
            String passwordFileStr = System.getProperty("test.src") +
                File.separator + "password.properties";
            env.put("jmx.remote.x.password.file", passwordFileStr);
            System.out.println("Added " + passwordFileStr + " file as jmx.remote.x.password.file");
        }
    }

    if (serverMap.containsKey("-populate")) {
        String populateClassName = "Simple";
        ObjectName on =
            new ObjectName("defaultDomain:class=Simple");

        Utils.debug(Utils.DEBUG_STANDARD, "create and register Simple MBean") ;
        mbs.createMBean(populateClassName, on);
    }

    cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
    cs.start();

    Utils.waitReady(cs, NINETY_SECONDS);

    JMXServiceURL addr = cs.getAddress();

    System.out.println("AuthorizationTest::createServerSide: Done.") ;

    return addr;
}
 
Example 16
Source File: SSLHttpAdaptor.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Starts the http server
 */
public void start() throws JMException
{
   // creates new server
   MBeanServer server = MBeanServerFactory.createMBeanServer("test");
   ObjectName serverName = new ObjectName("Http:name=HttpAdaptor");
   server.createMBean("mx4j.tools.adaptor.http.HttpAdaptor", serverName, null);
   // set attributes
   if (port > 0)
   {
      server.setAttribute(serverName, new Attribute("Port", new Integer(port)));
   }
   else
   {
      System.out.println("Incorrect port value " + port);
   }
   if (host != null)
   {
      server.setAttribute(serverName, new Attribute("Host", host));
   }
   else
   {
      System.out.println("Incorrect null hostname");
   }
   // set the XSLTProcessor. If you want to use pure XML comment this out
   ObjectName processorName = new ObjectName("Http:name=XSLTProcessor");
   server.createMBean("mx4j.tools.adaptor.http.XSLTProcessor", processorName, null);
   if (path != null)
   {
      server.setAttribute(processorName, new Attribute("File", path));
   }
   server.setAttribute(processorName, new Attribute("UseCache", new Boolean(false)));
   if (pathInJar != null)
   {
      server.setAttribute(processorName, new Attribute("PathInJar", pathInJar));
   }
   server.setAttribute(serverName, new Attribute("ProcessorName", processorName));

   // add a couple of MBeans
   TestClass test1 = new TestClass("t1");
   TestClass test2 = new TestClass("t2");
   server.registerMBean(test1, new ObjectName("Test:name=test1"));
   server.registerMBean(test2, new ObjectName("Test:name=test2"));

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

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

   // SSL support
   ObjectName sslFactory = new ObjectName("Adaptor:service=SSLServerSocketFactory");
   server.createMBean("mx4j.tools.adaptor.ssl.SSLAdaptorServerSocketFactory", sslFactory, null);

   SSLAdaptorServerSocketFactoryMBean factory = (SSLAdaptorServerSocketFactoryMBean)MBeanServerInvocationHandler.newProxyInstance(server, sslFactory, SSLAdaptorServerSocketFactoryMBean.class, false);
   // Customize the values below
   factory.setKeyStoreName("certs");
   factory.setKeyStorePassword("mx4j");

   server.setAttribute(serverName, new Attribute("SocketFactoryName", sslFactory));

   // starts the server
   server.invoke(serverName, "start", null, null);
}
 
Example 17
Source File: MBeanExceptionTest.java    From dragonwell8_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("Test that if an MBean throws RuntimeException " +
                       "it is wrapped in RuntimeMBeanException,");
    System.out.println("and if a Standard MBean throws Exception " +
                       "it is wrapped in MBeanException");
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    Object standard = new Except();
    ObjectName standardName = new ObjectName(":name=Standard MBean");
    Object standardMBean =
        new StandardMBean(new Except(), ExceptMBean.class);
    ObjectName standardMBeanName =
        new ObjectName(":name=Instance of StandardMBean");
    Object dynamic = new DynamicExcept();
    ObjectName dynamicName = new ObjectName(":name=Dynamic MBean");
    mbs.registerMBean(standard, standardName);
    mbs.registerMBean(standardMBean, standardMBeanName);
    mbs.registerMBean(dynamic, dynamicName);
    int failures = 0;
    failures += test(mbs, standardName, true);
    failures += test(mbs, standardMBeanName, true);
    failures += test(mbs, dynamicName, false);

    final boolean[] booleans = {false, true};

    for (boolean runtimeX : booleans) {
        Class<? extends Exception> excC =
                runtimeX ? RuntimeMBeanException.class : MBeanException.class;
        String excS =
                runtimeX ? "a RuntimeMBeanException" : "an MBeanException";
        String mbsS = "a plain MBeanServer";
        System.out.println(
                "Test that, with " + mbsS + ", " + excS + " is wrapped " +
                "in " + excS);
        // E.g. "Test that, with a plain MBeanServer, an MBeanException
        // is wrapped in an MBeanException".
        try {
            mbs.createMBean(
                    Except.class.getName(), new ObjectName(":name=Oops"),
                    new Object[] {runtimeX},
                    new String[] {boolean.class.getName()});
            System.out.println(
                    "FAIL: createMBean succeeded but should not have");
            failures++;
        } catch (Exception e) {
            if (!excC.isInstance(e)) {
                System.out.println(
                        "FAIL: expected " + excC.getName() + " from " +
                        "createMBean, got " + e);
                failures++;
            } else {
                Throwable cause = e.getCause();
                if (!excC.isInstance(cause)) {
                    System.out.println(
                            "FAIL: expected " + excC.getName() +
                            " as cause of " + excC.getName() +
                            ", got " + e);
                    failures++;
                } else
                    System.out.println("...ok");
            }
        }
    }

    if (failures == 0)
        System.out.println("Test passed");
    else {
        System.out.println("TEST FAILED: " + failures + " failure(s)");
        System.exit(1);
    }
}
 
Example 18
Source File: MBeanExceptionTest.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("Test that if an MBean throws RuntimeException " +
                       "it is wrapped in RuntimeMBeanException,");
    System.out.println("and if a Standard MBean throws Exception " +
                       "it is wrapped in MBeanException");
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    Object standard = new Except();
    ObjectName standardName = new ObjectName(":name=Standard MBean");
    Object standardMBean =
        new StandardMBean(new Except(), ExceptMBean.class);
    ObjectName standardMBeanName =
        new ObjectName(":name=Instance of StandardMBean");
    Object dynamic = new DynamicExcept();
    ObjectName dynamicName = new ObjectName(":name=Dynamic MBean");
    mbs.registerMBean(standard, standardName);
    mbs.registerMBean(standardMBean, standardMBeanName);
    mbs.registerMBean(dynamic, dynamicName);
    int failures = 0;
    failures += test(mbs, standardName, true);
    failures += test(mbs, standardMBeanName, true);
    failures += test(mbs, dynamicName, false);

    final boolean[] booleans = {false, true};

    for (boolean runtimeX : booleans) {
        Class<? extends Exception> excC =
                runtimeX ? RuntimeMBeanException.class : MBeanException.class;
        String excS =
                runtimeX ? "a RuntimeMBeanException" : "an MBeanException";
        String mbsS = "a plain MBeanServer";
        System.out.println(
                "Test that, with " + mbsS + ", " + excS + " is wrapped " +
                "in " + excS);
        // E.g. "Test that, with a plain MBeanServer, an MBeanException
        // is wrapped in an MBeanException".
        try {
            mbs.createMBean(
                    Except.class.getName(), new ObjectName(":name=Oops"),
                    new Object[] {runtimeX},
                    new String[] {boolean.class.getName()});
            System.out.println(
                    "FAIL: createMBean succeeded but should not have");
            failures++;
        } catch (Exception e) {
            if (!excC.isInstance(e)) {
                System.out.println(
                        "FAIL: expected " + excC.getName() + " from " +
                        "createMBean, got " + e);
                failures++;
            } else {
                Throwable cause = e.getCause();
                if (!excC.isInstance(cause)) {
                    System.out.println(
                            "FAIL: expected " + excC.getName() +
                            " as cause of " + excC.getName() +
                            ", got " + e);
                    failures++;
                } else
                    System.out.println("...ok");
            }
        }
    }

    if (failures == 0)
        System.out.println("Test passed");
    else {
        System.out.println("TEST FAILED: " + failures + " failure(s)");
        System.exit(1);
    }
}
 
Example 19
Source File: RelationNotificationSeqNoTest.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 {
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    ObjectName relSvcName = new ObjectName("a:type=relationService");
    RelationServiceMBean relSvc =
            JMX.newMBeanProxy(mbs, relSvcName, RelationServiceMBean.class);
    mbs.createMBean("javax.management.relation.RelationService",
                    relSvcName,
                    new Object[] {Boolean.TRUE},
                    new String[] {"boolean"});

    final BlockingQueue<Notification> q =
            new ArrayBlockingQueue<Notification>(100);
    NotificationListener qListener = new NotificationListener() {
        public void handleNotification(Notification notification,
                                       Object handback) {
            q.add(notification);
        }
    };
    mbs.addNotificationListener(relSvcName, qListener, null, null);

    RoleInfo leftInfo =
        new RoleInfo("left", "javax.management.timer.TimerMBean");
    RoleInfo rightInfo =
        new RoleInfo("right", "javax.management.timer.Timer");
    relSvc.createRelationType("typeName", new RoleInfo[] {leftInfo, rightInfo});
    ObjectName timer1 = new ObjectName("a:type=timer,number=1");
    ObjectName timer2 = new ObjectName("a:type=timer,number=2");
    mbs.createMBean("javax.management.timer.Timer", timer1);
    mbs.createMBean("javax.management.timer.Timer", timer2);

    Role leftRole =
        new Role("left", Arrays.asList(new ObjectName[] {timer1}));
    Role rightRole =
        new Role("right", Arrays.asList(new ObjectName[] {timer2}));
    RoleList roles =
        new RoleList(Arrays.asList(new Role[] {leftRole, rightRole}));

    final int NREPEAT = 10;

    for (int i = 0; i < NREPEAT; i++) {
        relSvc.createRelation("relationName", "typeName", roles);
        relSvc.removeRelation("relationName");
    }

    Notification firstNotif = q.remove();
    long seqNo = firstNotif.getSequenceNumber();
    for (int i = 0; i < NREPEAT * 2 - 1; i++) {
        Notification n = q.remove();
        long nSeqNo = n.getSequenceNumber();
        if (nSeqNo != seqNo + 1) {
            throw new Exception(
                    "TEST FAILED: expected seqNo " + (seqNo + 1) + "; got " +
                    nSeqNo);
        }
        seqNo++;
    }
    System.out.println("TEST PASSED: got " + (NREPEAT * 2) + " notifications " +
            "with contiguous sequence numbers");
}
 
Example 20
Source File: RelationNotificationSeqNoTest.java    From dragonwell8_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 relSvcName = new ObjectName("a:type=relationService");
    RelationServiceMBean relSvc =
            JMX.newMBeanProxy(mbs, relSvcName, RelationServiceMBean.class);
    mbs.createMBean("javax.management.relation.RelationService",
                    relSvcName,
                    new Object[] {Boolean.TRUE},
                    new String[] {"boolean"});

    final BlockingQueue<Notification> q =
            new ArrayBlockingQueue<Notification>(100);
    NotificationListener qListener = new NotificationListener() {
        public void handleNotification(Notification notification,
                                       Object handback) {
            q.add(notification);
        }
    };
    mbs.addNotificationListener(relSvcName, qListener, null, null);

    RoleInfo leftInfo =
        new RoleInfo("left", "javax.management.timer.TimerMBean");
    RoleInfo rightInfo =
        new RoleInfo("right", "javax.management.timer.Timer");
    relSvc.createRelationType("typeName", new RoleInfo[] {leftInfo, rightInfo});
    ObjectName timer1 = new ObjectName("a:type=timer,number=1");
    ObjectName timer2 = new ObjectName("a:type=timer,number=2");
    mbs.createMBean("javax.management.timer.Timer", timer1);
    mbs.createMBean("javax.management.timer.Timer", timer2);

    Role leftRole =
        new Role("left", Arrays.asList(new ObjectName[] {timer1}));
    Role rightRole =
        new Role("right", Arrays.asList(new ObjectName[] {timer2}));
    RoleList roles =
        new RoleList(Arrays.asList(new Role[] {leftRole, rightRole}));

    final int NREPEAT = 10;

    for (int i = 0; i < NREPEAT; i++) {
        relSvc.createRelation("relationName", "typeName", roles);
        relSvc.removeRelation("relationName");
    }

    Notification firstNotif = q.remove();
    long seqNo = firstNotif.getSequenceNumber();
    for (int i = 0; i < NREPEAT * 2 - 1; i++) {
        Notification n = q.remove();
        long nSeqNo = n.getSequenceNumber();
        if (nSeqNo != seqNo + 1) {
            throw new Exception(
                    "TEST FAILED: expected seqNo " + (seqNo + 1) + "; got " +
                    nSeqNo);
        }
        seqNo++;
    }
    System.out.println("TEST PASSED: got " + (NREPEAT * 2) + " notifications " +
            "with contiguous sequence numbers");
}