Example usage for javax.management JMX newMBeanProxy

List of usage examples for javax.management JMX newMBeanProxy

Introduction

In this page you can find the example usage for javax.management JMX newMBeanProxy.

Prototype

public static <T> T newMBeanProxy(MBeanServerConnection connection, ObjectName objectName,
        Class<T> interfaceClass, boolean notificationEmitter) 

Source Link

Document

Make a proxy for a Standard MBean in a local or remote MBean Server that may also support the methods of NotificationEmitter .

This method behaves the same as #newMBeanProxy(MBeanServerConnection,ObjectName,Class) , but additionally, if notificationEmitter is true , then the MBean is assumed to be a NotificationBroadcaster or NotificationEmitter and the returned proxy will implement NotificationEmitter as well as interfaceClass .

Usage

From source file:com.example.Client.java

public static void main(String[] args) throws Exception {
    // Create an RMI connector client and
    // connect it to the RMI connector server
    ///*from  w  ww .  jav  a2 s  .  com*/
    echo("\nCreate an RMI connector client and " + "connect it to the RMI connector server");
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:9999/jmxrmi");
    JMXConnector jmxc = JMXConnectorFactory.connect(url, null);

    // Create listener
    //
    ClientListener listener = new ClientListener();

    // Get an MBeanServerConnection
    //
    echo("\nGet an MBeanServerConnection");
    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
    waitForEnterPressed();

    // Get domains from MBeanServer
    //
    echo("\nDomains:");
    String domains[] = mbsc.getDomains();
    Arrays.sort(domains);
    for (String domain : domains) {
        echo("\tDomain = " + domain);
    }
    waitForEnterPressed();

    // Get MBeanServer's default domain
    //
    echo("\nMBeanServer default domain = " + mbsc.getDefaultDomain());

    // Get MBean count
    //
    echo("\nMBean count = " + mbsc.getMBeanCount());

    // Query MBean names
    //
    echo("\nQuery MBeanServer MBeans:");
    Set<ObjectName> names = new TreeSet<ObjectName>(mbsc.queryNames(null, null));
    for (ObjectName name : names) {
        echo("\tObjectName = " + name);
    }
    waitForEnterPressed();

    // ----------------------
    // Manage the Hello MBean
    // ----------------------

    echo("\n>>> Perform operations on Hello MBean <<<");

    // Construct the ObjectName for the Hello MBean
    //
    ObjectName mbeanName = new ObjectName("com.example:type=Hello");

    // Create a dedicated proxy for the MBean instead of
    // going directly through the MBean server connection
    //
    HelloMBean mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName, HelloMBean.class, true);

    // Add notification listener on Hello MBean
    //
    echo("\nAdd notification listener...");
    mbsc.addNotificationListener(mbeanName, listener, null, null);

    // Get CacheSize attribute in Hello MBean
    //
    echo("\nCacheSize = " + mbeanProxy.getCacheSize());

    // Set CacheSize attribute in Hello MBean
    // Calling "reset" makes the Hello MBean emit a
    // notification that will be received by the registered
    // ClientListener.
    //
    mbeanProxy.setCacheSize(150);

    // Sleep for 2 seconds to have time to receive the notification
    //
    echo("\nWaiting for notification...");
    sleep(2000);

    // Get CacheSize attribute in Hello MBean
    //
    echo("\nCacheSize = " + mbeanProxy.getCacheSize());

    // Invoke "sayHello" in Hello MBean
    //
    echo("\nInvoke sayHello() in Hello MBean...");
    mbeanProxy.sayHello();

    // Invoke "add" in Hello MBean
    //
    echo("\nInvoke add(2, 3) in Hello MBean...");
    echo("\nadd(2, 3) = " + mbeanProxy.add(2, 3));

    waitForEnterPressed();

    // ------------------------------
    // Manage the QueueSampler MXBean
    // ------------------------------

    echo("\n>>> Perform operations on QueueSampler MXBean <<<");

    // Construct the ObjectName for the QueueSampler MXBean
    //
    ObjectName mxbeanName = new ObjectName("com.example:type=QueueSampler");

    // Create a dedicated proxy for the MXBean instead of
    // going directly through the MBean server connection
    //
    QueueSamplerMXBean mxbeanProxy = JMX.newMXBeanProxy(mbsc, mxbeanName, QueueSamplerMXBean.class);

    // Get QueueSample attribute in QueueSampler MXBean
    //
    QueueSample queue1 = mxbeanProxy.getQueueSample();
    echo("\nQueueSample.Date = " + queue1.getDate());
    echo("QueueSample.Head = " + queue1.getHead());
    echo("QueueSample.Size = " + queue1.getSize());

    // Invoke "clearQueue" in QueueSampler MXBean
    //
    echo("\nInvoke clearQueue() in QueueSampler MXBean...");
    mxbeanProxy.clearQueue();

    // Get QueueSample attribute in QueueSampler MXBean
    //
    QueueSample queue2 = mxbeanProxy.getQueueSample();
    echo("\nQueueSample.Date = " + queue2.getDate());
    echo("QueueSample.Head = " + queue2.getHead());
    echo("QueueSample.Size = " + queue2.getSize());

    waitForEnterPressed();

    // Close MBeanServer connection
    //
    echo("\nClose the connection to the server");
    jmxc.close();
    echo("\nBye! Bye!");
}

From source file:com.all.services.ServiceConsole.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    try {//from  w  ww. j  a v  a 2  s . c om
        LOG.info("Connecting to JMX service...");
        if (args.length < 2) {
            LOG.error("Incorrect usage of Ultrapeer console.\n\n Args should be 'command password [host]'");
            throw new IllegalArgumentException("Not enough agrugments to run.");
        }
        HashMap env = new HashMap();
        env.put("jmx.remote.credentials", new String[] { "controlRole", args[1] });
        String hostname = args.length > 2 ? args[2] : "";
        JMXConnector jmxc = JMXConnectorFactory
                .connect(new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + hostname + ":9999/jmxrmi"), env);
        ServiceMonitorMBean mbeanProxy = JMX.newMBeanProxy(jmxc.getMBeanServerConnection(),
                new ObjectName("com.all.services:type=ServiceMonitor"), ServiceMonitorMBean.class, true);
        handleCommand(mbeanProxy, args[0]);
        jmxc.close();
        LOG.info("Done.");
    } catch (Exception e) {
        LOG.error(e, e);
    }
}

From source file:com.neophob.sematrix.cli.PixConClientJmx.java

/**
 * /*from   w w w.ja  v  a2 s.  c om*/
 * @param mbsc
 * @throws Exception
 */
private static void printJmxStatus(MBeanServerConnection mbsc) throws Exception {
    ObjectName mbeanName = new ObjectName(PixelControllerStatus.JMX_BEAN_NAME);

    PixelControllerStatusMBean mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName, PixelControllerStatusMBean.class,
            true);

    // print general status information
    System.out.println("\nGeneric:");
    System.out.printf("%-25s: %s\n", "server version", mbeanProxy.getVersion());
    System.out.printf("%-25s: %3.3f (%s of configured fps: %2.0f)\n", "current fps", mbeanProxy.getCurrentFps(),
            PERCENT_FORMAT.format(mbeanProxy.getCurrentFps() / mbeanProxy.getConfiguredFps()),
            mbeanProxy.getConfiguredFps());
    System.out.printf("%-25s: %d\n", "frame count", mbeanProxy.getFrameCount());
    System.out.printf("%-25s: %s\n", "running since",
            DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - mbeanProxy.getStartTime()));

    // print average timing information
    System.out.println("\nThe following average times have been collected during the last "
            + DurationFormatUtils.formatDuration(mbeanProxy.getRecordedMilliSeconds(), "ss.SSS") + " seconds:");
    for (TimeMeasureItemGlobal valueEnum : TimeMeasureItemGlobal.values()) {
        System.out.printf("   %-22s: %3.3fms\n", valueEnum.getReadableName(),
                mbeanProxy.getAverageTime(valueEnum));
    }

    // print output specific timing information
    for (int output = 0; output < mbeanProxy.getNumberOfOutputs(); output++) {
        System.out.println("\nOuput-specific average times for output #" + (output + 1) + ": "
                + mbeanProxy.getOutputType(output).getReadableName());
        for (TimeMeasureItemOutput outputValueEnum : TimeMeasureItemOutput.values()) {
            System.out.printf("   %-22s: %3.3fms\n", outputValueEnum.getReadableName(),
                    mbeanProxy.getOutputAverageTime(output, outputValueEnum));
        }
    }
}

From source file:com.haulmont.cuba.web.jmx.JmxConnectionHelper.java

protected static <T> T getProxy(MBeanServerConnection connection, ObjectName objectName,
        final Class<T> objectClass) {
    return JMX.newMBeanProxy(connection, objectName, objectClass, true);
}

From source file:com.quinsoft.zeidon.jconsole.JConsoleEnvironment.java

void searchForObjectEngineBeans() {
    try {//  ww w .java2 s . c  om
        proxies = new ArrayList<>();
        Set<ObjectName> objects = server.queryNames(null, null);
        for (ObjectName object : objects) {
            ObjectInstance oi = server.getObjectInstance(object);
            if (oi.getClassName().equals("com.quinsoft.zeidon.jmx.JmxObjectEngineMonitor")) {
                String name = object.getCanonicalName();
                JmxObjectEngineMonitorMBean proxy = JMX.newMBeanProxy(server, object,
                        JmxObjectEngineMonitorMBean.class, true);
                proxies.add(new OeProxy(name, proxy));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:de.iew.spring.integration.SpringIntegrationJmxTest.java

@Test
public void testJmxClientClassic() throws Exception {
    JMXServiceURL clientURL = new JMXServiceURL(this.serviceUrl);
    Map clientEnv = new HashMap();

    JMXConnector connector = JMXConnectorFactory.connect(clientURL, clientEnv);
    MBeanServerConnection connection = connector.getMBeanServerConnection();

    ObjectName mbeanName = new ObjectName(this.jmxTestServiceObjectName);
    JmxTestService mbeanProxy = JMX.newMBeanProxy(connection, mbeanName, JmxTestService.class, true);

    mbeanProxy.setName("Foo Bar");
    mbeanProxy.sayHello();/*from w  w w . j  a  va2s. c om*/

    String[] hellos = mbeanProxy.getStoredHellos();
    Assert.assertEquals(1, hellos.length);

    mbeanProxy.clearHelloStore();

    hellos = mbeanProxy.getStoredHellos();
    Assert.assertEquals(0, hellos.length);
}

From source file:com.paxxis.cornerstone.messaging.service.shell.ServiceShell.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void doShutdown(String[] vals) throws Exception {
    StringBuilder buf = new StringBuilder("service:jmx:rmi://localhost/jndi/rmi://localhost:");
    String serviceName = vals[0];

    buf.append(vals[1]).append("/").append(serviceName);
    String serviceUrl = buf.toString();

    JMXServiceURL url = new JMXServiceURL(serviceUrl);
    JMXConnector jmxc = null;//from ww w. j  a va 2 s  . com
    try {
        jmxc = JMXConnectorFactory.connect(url, null);

    } catch (Exception e) {
        throw new Exception("Unable to establish JMX connection at " + serviceUrl);
    }

    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

    Set<ObjectInstance> mBeansSet = mbsc.queryMBeans(new ObjectName(serviceName + ":*"), null);
    List<IServiceController> serviceProxies = new ArrayList<IServiceController>();
    Class serviceBusInterface = Class.forName(IServiceBusManager.class.getName());
    Class serviceControllerInterface = Class.forName(IServiceController.class.getName());

    for (ObjectInstance mBeanObject : mBeansSet) {
        ObjectName mbeanName = mBeanObject.getObjectName();
        Class mbeanClass = Class.forName(mBeanObject.getClassName());
        if (serviceBusInterface.isAssignableFrom(mbeanClass)) {
            IServiceBusManager requestConnector = JMX.newMBeanProxy(mbsc, mbeanName, IServiceBusManager.class,
                    true);
            System.out.print(mbeanName + " terminating....");
            requestConnector.disconnect();
            while (true) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ie) {

                }

                if (!requestConnector.isConnected()) {
                    break;
                }
            }
            System.out.println(" Done");
        } else if (serviceControllerInterface.isAssignableFrom(mbeanClass)) {
            // save off the service proxies to make sure we disconnect
            // all connectors before shutting down the service itself
            IServiceController mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName, IServiceController.class, true);
            serviceProxies.add(mbeanProxy);
        }
    }

    for (IServiceController mbeanProxy : serviceProxies) {
        try {
            mbeanProxy.shutdown();
        } catch (UndeclaredThrowableException ex) {
        }
    }

    System.out.println("Service terminated");
}

From source file:com.all.services.ServiceInteractiveConsole.java

@SuppressWarnings("unchecked")
private static void execute(String hostname, String password, String command)
        throws IOException, MalformedObjectNameException {
    HashMap env = new HashMap();
    env.put("jmx.remote.credentials", new String[] { "controlRole", password });
    String serviceURL = "service:jmx:rmi:///jndi/rmi://" + hostname + ":9999/jmxrmi";
    JMXServiceURL url = new JMXServiceURL(serviceURL);
    LOG.info("Connecting to " + serviceURL);
    JMXConnector jmxc = JMXConnectorFactory.connect(url, env);
    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
    ObjectName mbeanName = new ObjectName("com.all.services:type=ServiceMonitor");
    ServiceMonitorMBean mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName, ServiceMonitorMBean.class, true);
    ServiceConsole.handleCommand(mbeanProxy, command);
}

From source file:org.apache.hadoop.hdfs.tools.DataNodeAdmin.java

/**
 * Gets the data node registration bean/*from   www.j ava2  s  . co m*/
 * @return  Data node regstration bean
 * @throws MalformedObjectNameException
 */
private DatanodeRegistrationMXBean getDatanodeRegBean() throws MalformedObjectNameException {
    ObjectName mbeanRegName = new ObjectName(DATANODE_REG_NAME);
    return JMX.newMBeanProxy(mbsc, mbeanRegName, DatanodeRegistrationMXBean.class, true);
}

From source file:org.apache.hadoop.hdfs.tools.DataNodeAdmin.java

/**
 * Gets the FSDataset mbean/*from   ww  w. j ava2  s  .c o  m*/
 * @return FSDataset mbean
 * @throws IOException
 */
private FSDatasetMBean getDatasetMBean() throws IOException {
    Set<ObjectName> names = new TreeSet<ObjectName>(mbsc.queryNames(null, null));
    ObjectName fsDataSetObject = null;
    for (ObjectName name : names) {
        if (name.toString().contains("FSDatasetState"))
            fsDataSetObject = name;
    }
    return JMX.newMBeanProxy(mbsc, fsDataSetObject, FSDatasetMBean.class, true);
}