Example usage for javax.management.remote JMXConnector getMBeanServerConnection

List of usage examples for javax.management.remote JMXConnector getMBeanServerConnection

Introduction

In this page you can find the example usage for javax.management.remote JMXConnector getMBeanServerConnection.

Prototype

public MBeanServerConnection getMBeanServerConnection() throws IOException;

Source Link

Document

Returns an MBeanServerConnection object representing a remote MBean server.

Usage

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

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    try {//from w w w. java 2s  .co m
        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.example.Client.java

public static void main(String[] args) throws Exception {
    // Create an RMI connector client and
    // connect it to the RMI connector server
    ///*ww  w.j  a v a2  s .c  om*/
    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:net.sfr.tv.mom.mgt.HornetqConsole.java

/**
 * @param args the command line arguments
 *///  w  w w  .  j  ava 2  s  .  co m
public static void main(String[] args) {

    try {

        String jmxHost = "127.0.0.1";
        String jmxPort = "6001";

        // Process command line arguments
        String arg;
        for (int i = 0; i < args.length; i++) {
            arg = args[i];
            switch (arg) {
            case "-h":
                jmxHost = args[++i];
                break;
            case "-p":
                jmxPort = args[++i];
                break;
            default:
                break;
            }
        }

        // Check for arguments consistency
        if (StringUtils.isEmpty(jmxHost) || !NumberUtils.isNumber(jmxPort)) {
            LOGGER.info("Usage : ");
            LOGGER.info("hq-console.jar <-h host(127.0.0.1)> <-p port(6001)>\n");
            System.exit(1);
        }

        System.out.println(
                SystemUtils.LINE_SEPARATOR.concat(Ansi.format("HornetQ Console ".concat(VERSION), Color.CYAN)));

        final StringBuilder _url = new StringBuilder("service:jmx:rmi://").append(jmxHost).append(':')
                .append(jmxPort).append("/jndi/rmi://").append(jmxHost).append(':').append(jmxPort)
                .append("/jmxrmi");

        final String jmxServiceUrl = _url.toString();
        JMXConnector jmxc = null;

        final CommandRouter router = new CommandRouter();

        try {
            jmxc = JMXConnectorFactory.connect(new JMXServiceURL(jmxServiceUrl), null);
            assert jmxc != null; // jmxc must be not null
        } catch (final MalformedURLException e) {
            System.out.println(SystemUtils.LINE_SEPARATOR
                    .concat(Ansi.format(jmxServiceUrl + " :" + e.getMessage(), Color.RED)));
        } catch (Throwable t) {
            System.out.println(SystemUtils.LINE_SEPARATOR.concat(
                    Ansi.format("Unable to connect to JMX service URL : ".concat(jmxServiceUrl), Color.RED)));
            System.out.print(SystemUtils.LINE_SEPARATOR.concat(
                    Ansi.format("Did you add jmx-staticport-agent.jar to your classpath ?", Color.MAGENTA)));
            System.out.println(SystemUtils.LINE_SEPARATOR.concat(Ansi.format(
                    "Or did you set the com.sun.management.jmxremote.port option in the hornetq server startup script ?",
                    Color.MAGENTA)));
            System.exit(-1);
        }

        System.out.println("\n".concat(Ansi
                .format("Successfully connected to JMX service URL : ".concat(jmxServiceUrl), Color.YELLOW)));

        final MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

        // PRINT SERVER STATUS REPORT
        System.out.print((String) router.get(Command.STATUS, Option.VM).execute(mbsc, null));
        System.out.print((String) router.get(Command.STATUS, Option.SERVER).execute(mbsc, null));
        System.out.print((String) router.get(Command.STATUS, Option.CLUSTER).execute(mbsc, null));

        printHelp(router);

        // START COMMAND LINE
        Scanner scanner = new Scanner(System.in);
        System.out.print("> ");
        String input;
        while (!(input = scanner.nextLine().concat(" ")).equals("exit ")) {

            String[] cliArgs = input.split("\\ ");
            CommandHandler handler;

            if (cliArgs.length < 1) {
                System.out.print("> ");
                continue;
            }

            Command cmd = Command.fromString(cliArgs[0]);
            if (cmd == null) {
                System.out.print(Ansi.format("Syntax error !", Color.RED).concat("\n"));
                cmd = Command.HELP;
            }

            switch (cmd) {
            case STATUS:
            case LIST:
            case DROP:

                Set<Option> options = router.get(cmd);

                for (Option opt : options) {

                    if (cliArgs[1].equals(opt.toString())) {
                        handler = router.get(cmd, opt);

                        String[] cmdOpts = null;
                        if (cliArgs.length > 2) {
                            cmdOpts = new String[cliArgs.length - 2];
                            for (int i = 0; i < cmdOpts.length; i++) {
                                cmdOpts[i] = cliArgs[2 + i];
                            }
                        }

                        Object result = handler.execute(mbsc, cmdOpts);
                        if (result != null && String.class.isAssignableFrom(result.getClass())) {
                            System.out.print((String) result);
                        }
                        System.out.print("> ");
                    }
                }

                break;

            case FORK:
                // EXECUTE SYSTEM COMMAND
                ProcessBuilder pb = new ProcessBuilder(Arrays.copyOfRange(cliArgs, 1, cliArgs.length));
                pb.inheritIO();
                pb.start();
                break;

            case HELP:
                printHelp(router);
                break;
            }
        }
    } catch (MalformedURLException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
    }

    echo(SystemUtils.LINE_SEPARATOR.concat(Ansi.format("Bye!", Color.CYAN)));

}

From source file:org.camid.rulemanager.ServerShellClientMain.java

public static EPServiceProviderJMXMBean ServerShellClientMain() throws Exception {

    log.info("Loading properties");

    log.info("Attach to server via JMX");
    //        JMXServiceURL url = new JMXServiceURL(properties.getProperty(ServerShellConstants.MGMT_SERVICE_URL));
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:5554/server");

    //        String jmxServiceURL = "service:jmx:rmi:///jndi/rmi://localhost:5554/server";
    JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
    ObjectName mBeanName = new ObjectName(ServerShellConstants.MGMT_MBEAN_NAME);
    EPServiceProviderJMXMBean proxy = (EPServiceProviderJMXMBean) MBeanServerInvocationHandler
            .newProxyInstance(mbsc, mBeanName, EPServiceProviderJMXMBean.class, true);

    //        proxy.destroy("sensor1c");
    return proxy;

    // Create statement via JMX
    //           System.out.println("Creating a statement via Java Management Extensions (JMX) MBean Proxy");
    //           proxy.createEPL("select * from sensor(value>20)","filter", "null");
    ////w ww.j  a  v a 2  s . c  o m
    //
    //        System.out.println("Destroing statement via Java Management Extensions (JMX) MBean Proxy");
    //        proxy.destroy("filterStatement");
    //
    //
    //        System.out.println("Exiting");
    //        System.exit(-1);
}

From source file:org.wso2.carbon.integration.test.client.JMXAnalyzerClient.java

public static int getThreadCount(String host, String port) throws IOException {
    String username = "admin";
    String password = "admin";
    int threadCount = 0;
    String threadName = "JMSThreads";
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi");
    Map<String, String[]> env = new HashMap<String, String[]>();
    ThreadInfo threadIDInfo;//from   ww  w.  ja v a  2  s . c  om

    String[] credentials = { username, password };
    env.put(JMXConnector.CREDENTIALS, credentials);
    JMXConnector jmxConnector = JMXConnectorFactory.connect(url, env);
    MBeanServerConnection mbeanServerConnection = jmxConnector.getMBeanServerConnection();
    final ThreadMXBean remoteThread = ManagementFactory.newPlatformMXBeanProxy(mbeanServerConnection,
            ManagementFactory.THREAD_MXBEAN_NAME, ThreadMXBean.class);
    long[] allThreadIDsArray = remoteThread.getAllThreadIds();

    //get jms thread count
    for (long threadID : allThreadIDsArray) {
        threadIDInfo = remoteThread.getThreadInfo(threadID);
        if (threadIDInfo != null && threadIDInfo.getThreadName() != null
                && threadIDInfo.getThreadName().startsWith(threadName)) {
            threadCount++;
        }
    }
    //close the connection
    jmxConnector.close();
    return threadCount;
}

From source file:cc.kune.kunecli.JMXUtils.java

public static Object doOperation(final String objectName, final String operation) {

    final List<VirtualMachineDescriptor> vms = VirtualMachine.list();

    try {//from  ww  w  . j  a v  a  2s .c om
        for (final VirtualMachineDescriptor vmd : vms) {
            final String id = vmd.id();
            LOG.debug("VM id: " + id);
            final JMXServiceURL url = getURLForPid(id.trim());

            final JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
            final MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

            final ObjectName mbeanName = new ObjectName(objectName);

            MBeanInfo beanInfo;
            try {
                beanInfo = mbsc.getMBeanInfo(mbeanName);
                for (final MBeanOperationInfo currentOp : beanInfo.getOperations()) {
                    if (currentOp.getName().equals(operation)) {
                        LOG.debug("Doing operation '" + operation + "' over mbean: '" + objectName
                                + "' with id: '" + id + "'.");
                        final Object invoke = mbsc.invoke(mbeanName, currentOp.getName(), new Object[] {},
                                new String[] {});
                        return invoke;
                    }
                }
            } catch (final InstanceNotFoundException e) {
                // Ok, operation not found in this VM or domain
            }
        }
        throw new RuntimeException("JMX operation not found");
    } catch (final Exception e) {
        LOG.error("Error in jmx connection", e);
    }
    throw new RuntimeException("JMX operation failed");
}

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:com.redhat.poc.jdg.bankofchina.function.TestCase411RemoteMultiThreadsCustomMarshal.java

public static void registerProtofile(String jmxHost, int jmxPort, String cacheContainerName) throws Exception {
    JMXConnector jmxConnector = JMXConnectorFactory
            .connect(new JMXServiceURL("service:jmx:remoting-jmx://" + jmxHost + ":" + jmxPort));
    MBeanServerConnection jmxConnection = jmxConnector.getMBeanServerConnection();

    ObjectName protobufMetadataManagerObjName = new ObjectName("jboss.infinispan:type=RemoteQuery,name="
            + ObjectName.quote(cacheContainerName) + ",component=ProtobufMetadataManager");

    // initialize client-side serialization context via JMX
    byte[] descriptor = readClasspathResource("/model/userbaseinfo.protobin");
    jmxConnection.invoke(protobufMetadataManagerObjName, "registerProtofile", new Object[] { descriptor },
            new String[] { byte[].class.getName() });
    jmxConnector.close();/*  ww w . j  ava 2  s  .c  om*/
}

From source file:JTop.java

private static MBeanServerConnection connect(String hostname, int port) {
    // Create an RMI connector client and connect it to
    // the RMI connector server
    String urlPath = "/jndi/rmi://" + hostname + ":" + port + "/jmxrmi";
    MBeanServerConnection server = null;
    try {//  w  ww  .  j  a  va  2s . c o m
        JMXServiceURL url = new JMXServiceURL("rmi", "", 0, urlPath);
        JMXConnector jmxc = JMXConnectorFactory.connect(url);
        server = jmxc.getMBeanServerConnection();
    } catch (MalformedURLException e) {
        // should not reach here
    } catch (IOException e) {
        System.err.println("\nCommunication error: " + e.getMessage());
        System.exit(1);
    }
    return server;
}

From source file:com.ibm.soatf.component.osb.ServiceManager.java

public static boolean changeServiceStatus(String servicetype, boolean status, String serviceURI, String host,
        int port, String username, String password) throws FrameworkExecutionException {

    SessionManagementMBean sm = null;//from w w w .  ja v  a2 s.c  o m
    JMXConnector conn = null;
    boolean result = true;
    String statusMsg = "";
    try {
        conn = initConnection(host, port, username, password);
        MBeanServerConnection mbconn = conn.getMBeanServerConnection();
        DomainRuntimeServiceMBean clusterService = (DomainRuntimeServiceMBean) MBeanServerInvocationHandler
                .newProxyInstance(mbconn, new ObjectName(DomainRuntimeServiceMBean.OBJECT_NAME));
        sm = (SessionManagementMBean) clusterService.findService(SessionManagementMBean.NAME,
                SessionManagementMBean.TYPE, null);
        sm.createSession(SESSION_NAME);
        ALSBConfigurationMBean alsbSession = (ALSBConfigurationMBean) clusterService.findService(
                ALSBConfigurationMBean.NAME + "." + SESSION_NAME, ALSBConfigurationMBean.TYPE, null);

        if (servicetype.equals("ProxyService")) {
            Ref ref = constructRef("ProxyService", serviceURI);
            ProxyServiceConfigurationMBean proxyConfigMBean = (ProxyServiceConfigurationMBean) clusterService
                    .findService(ProxyServiceConfigurationMBean.NAME + "." + SESSION_NAME,
                            ProxyServiceConfigurationMBean.TYPE, null);
            if (status) {
                proxyConfigMBean.enableService(ref);
                statusMsg = "Enable the ProxyService : " + serviceURI;
                logger.info(statusMsg);
            } else {
                proxyConfigMBean.disableService(ref);
                statusMsg = "Disable the ProxyService : " + serviceURI;
                logger.info(statusMsg);
            }
        } else if (servicetype.equals("BusinessService")) {
            try {
                Ref ref = constructRef("BusinessService", serviceURI);
                BusinessServiceConfigurationMBean businessConfigMBean = (BusinessServiceConfigurationMBean) clusterService
                        .findService(BusinessServiceConfigurationMBean.NAME + "." + SESSION_NAME,
                                BusinessServiceConfigurationMBean.TYPE, null);
                if (status) {
                    businessConfigMBean.enableService(ref);
                    statusMsg = "Enable the BusinessService : " + serviceURI;
                    logger.info(statusMsg);
                } else {
                    businessConfigMBean.disableService(ref);
                    statusMsg = "Disable the BusinessService : " + serviceURI;
                    logger.info(statusMsg);
                }
            } catch (IllegalArgumentException ex) {
                logger.fatal(ExceptionUtils.getStackTrace(ex));
            }
        }
        sm.activateSession(SESSION_NAME, statusMsg);
        conn.close();
    } catch (Exception ex) {
        if (null != sm) {
            try {
                sm.discardSession(SESSION_NAME);
            } catch (Exception e) {
                logger.debug("Not able to discard the session. " + e.getLocalizedMessage());
                throw new FrameworkExecutionException(e);
            }
        }
        result = false;
        logger.error("Error in MBean Server connection. " + ex.getLocalizedMessage());
        ex.printStackTrace();
    } finally {
        if (null != conn) {
            try {
                conn.close();
            } catch (Exception e) {
                logger.debug("Not able to close the JMX connection. " + e.getLocalizedMessage());
                throw new FrameworkExecutionException(e);

            }
        }
    }

    return result;
}