Example usage for javax.management.remote JMXConnectorFactory connect

List of usage examples for javax.management.remote JMXConnectorFactory connect

Introduction

In this page you can find the example usage for javax.management.remote JMXConnectorFactory connect.

Prototype

public static JMXConnector connect(JMXServiceURL serviceURL, Map<String, ?> environment) throws IOException 

Source Link

Document

Creates a connection to the connector server at the given address.

This method is equivalent to:

 JMXConnector conn = JMXConnectorFactory.newJMXConnector(serviceURL, environment); conn.connect(environment); 

Usage

From source file:jmxbf.java

public static void main(String[] args) throws IOException, MalformedObjectNameException {

    String HOST = "";
    String PORT = "";
    String usersFile = "";
    String pwdFile = "";

    CommandLine cmd = getParsedCommandLine(args);

    if (cmd != null) {

        HOST = cmd.getOptionValue("host");
        PORT = cmd.getOptionValue("port");
        usersFile = cmd.getOptionValue("usernames-file");
        pwdFile = cmd.getOptionValue("passwords-file");

    } else {/*from w ww .j a  va  2s. c o  m*/

        System.exit(1);
    }

    String finalResults = "";

    BufferedReader users = new BufferedReader(new FileReader(usersFile));
    BufferedReader pwds = new BufferedReader(new FileReader(pwdFile));

    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + HOST + ":" + PORT + "/jmxrmi");
    //new JMXServiceURL("service:jmx:remoting-jmx://" + HOST + ":" + PORT);

    String user = null;
    boolean found = false;
    while ((user = users.readLine()) != null) {
        String pwd = null;
        while ((pwd = pwds.readLine()) != null) {
            //System.out.println(user+":"+pwd);

            Map<String, String[]> env = new HashMap<>();
            String[] credentials = { user, pwd };
            env.put(JMXConnector.CREDENTIALS, credentials);
            try {

                JMXConnector jmxConnector = JMXConnectorFactory.connect(url, env);

                System.out.println();
                System.out.println();
                System.out.println();
                System.out.println(
                        "[+] ###SUCCESS### - We got a valid connection for: " + user + ":" + pwd + "\r\n\r\n");
                finalResults = finalResults + "\n" + user + ":" + pwd;
                jmxConnector.close();
                found = true;
                break;

            } catch (java.lang.SecurityException e) {
                System.out.println("Auth failed!!!\r\n");

            }
        }
        if (found) {
            System.out.println("Found some valid credentials - continuing brute force");
            found = false;

        }
        //closing and reopening pwds
        pwds.close();
        pwds = new BufferedReader(new FileReader(pwdFile));

    }

    users.close();
    //print final results
    if (finalResults.length() != 0) {
        System.out.println("The following valid credentials were found:\n");
        System.out.println(finalResults);
    }

}

From source file:net.sfr.tv.mom.mgt.HornetqConsole.java

/**
 * @param args the command line arguments
 *//*from w w  w.  j a v  a 2 s .  c  o  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: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  ww  w . jav  a 2 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: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;//w w w.jav a 2 s . com

    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:com.appdynamics.monitors.muleesb.JMXUtil.java

private static JMXConnector connect(String host, int port, String username, String password)
        throws IOException {
    String jmxUrl = buildUrl(host, port);
    JMXServiceURL url = new JMXServiceURL(jmxUrl);
    final Map<String, Object> env = new HashMap<String, Object>();
    JMXConnector connector = null;
    if (!Strings.isNullOrEmpty(username)) {
        env.put(JMXConnector.CREDENTIALS, new String[] { username, password });
        connector = JMXConnectorFactory.connect(url, env);
    } else {/*ww w .j  av a 2 s . c  o m*/
        connector = JMXConnectorFactory.connect(url);
    }
    return connector;
}

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

/**
 * /*w  w w  .  ja v a 2  s.c o  m*/
 * @param hostname
 * @param port
 */
public static void queryJmxServer(String hostname, int port) {
    System.setSecurityManager(new java.rmi.RMISecurityManager());

    JMXServiceURL url;
    JMXConnector jmxc;
    hostname = hostname + ":" + port;
    System.out.println("Create an RMI connector client and connect it to the RMI connector server " + hostname);
    try {
        url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + hostname + "/jmxrmi");
        jmxc = JMXConnectorFactory.connect(url, null);

        System.out.println("Get an MBeanServerConnection...");
        MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
        printJmxStatus(mbsc);

        System.out.println("\nClose the connection to the server");
        jmxc.close();

    } catch (Exception e) {
        System.out.println("Error: JMX Error!");
        e.printStackTrace();
    }
}

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 {//  w  ww.j  a  v a  2s . com
        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: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");
    ///*from w  w w  .j  av a2  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:com.adaptris.core.services.jmx.JmxOperationInvoker.java

public Object invoke(String serviceUrl, String objectName, String username, String password, String methodName,
        Object[] params, String[] signatures) throws Exception {
    Map<String, String[]> env = new HashMap<>();
    if ((!StringUtils.isEmpty(username)) && (!StringUtils.isEmpty(password))) {
        String[] credentials = { username, Password.decode(password) };
        env.put(JMXConnector.CREDENTIALS, credentials);
    }//from  w  ww  .j  a v a 2s .  c  o m
    JMXServiceURL jmxServiceUrl = new JMXServiceURL(serviceUrl);
    JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxServiceUrl, env);
    ObjectName objectNameInst = ObjectName.getInstance(objectName);
    MBeanServerConnection mbeanConn = jmxConnector.getMBeanServerConnection();
    try {
        return mbeanConn.invoke(objectNameInst, methodName, params, signatures);
    } finally {
        jmxConnector.close();

    }
}

From source file:com.googlecode.jmxtrans.connections.JmxConnectionFactory.java

/**
 * Creates the connection./*ww w  .  j  a v  a2s  .  c o m*/
 */
@Override
public JMXConnector makeObject(JMXConnectionParams params) throws Exception {
    return JMXConnectorFactory.connect(params.getUrl(), params.getEnvironment());
}