Example usage for javax.management.remote JMXServiceURL JMXServiceURL

List of usage examples for javax.management.remote JMXServiceURL JMXServiceURL

Introduction

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

Prototype

public JMXServiceURL(String serviceURL) throws MalformedURLException 

Source Link

Document

Constructs a JMXServiceURL by parsing a Service URL string.

Usage

From source file:com.flipkart.poseidon.jmx.PoseidonJMXInvoker.java

public static void main(String[] args) {
    if (args.length < 3) {
        System.err.println(PoseidonJMXInvoker.class.getSimpleName() + " <host> <port> <operation>");
        System.exit(-1);/*from  w w  w .  jav  a2s . co  m*/
    }

    final String CONNECT_STRING = args[0] + ":" + args[1];
    final String OPERATION = args[2];
    try {
        System.out.println("Running " + OPERATION + " over JMX on " + CONNECT_STRING);

        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + CONNECT_STRING + "/jmxrmi");
        MBeanServerConnection connection = JMXConnectorFactory.connect(url).getMBeanServerConnection();
        connection.invoke(ObjectName.getInstance(MBEAN_NAME), OPERATION, null, null);
    } catch (Exception e) {
        if (!(ExceptionUtils.getRootCause(e) instanceof EOFException && "destroy".equals(OPERATION))) {
            e.printStackTrace();
            System.exit(-1);
        }
    }
    System.out.println(OPERATION + " successful over JMX on " + CONNECT_STRING);
}

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 {/*w w w .j  a  v  a 2  s  .co  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.  jav a2 s .  c om*/
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  .j  a v  a  2 s  .  c  o m*/
    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;//ww  w .j  av a  2  s. co m

    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 {// w  ww.j  a va2  s.co  m
        connector = JMXConnectorFactory.connect(url);
    }
    return connector;
}

From source file:com.quartz.monitor.core.QuartzConnectUtil.java

/**
 * JMX connections take the form: service:jmx:rmi:///jndi/rmi://:2911/jmxrmi
 *
 * @param quartzConfig//from w  w w. j av a  2 s.c  om
 * @return
 */
public static JMXServiceURL createQuartzInstanceConnection(QuartzConfig quartzConfig)
        throws MalformedURLException {
    StringBuffer stringBuffer = new StringBuffer().append("service:jmx:rmi:///jndi/rmi://")
            .append(quartzConfig.getHost()).append(":").append(quartzConfig.getPort()).append("/jmxrmi");
    JMXServiceURL jmxServiceURL = new JMXServiceURL(stringBuffer.toString());
    return jmxServiceURL;
}

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

/**
 * /*from   w  w w .  ja v a2s  . co  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:test.integ.be.fedict.hsm.MonitoringTest.java

@Test
public void testJMXConnection() throws Exception {
    JMXServiceURL jmxServiceURL = new JMXServiceURL("service:jmx:remoting-jmx://localhost:9999");
    JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxServiceURL);
    MBeanServerConnection connection = jmxConnector.getMBeanServerConnection();
    MemoryMXBean memoryMXBean = ManagementFactory.newPlatformMXBeanProxy(connection,
            ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class);
    MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
    LOG.debug("used heap memory: " + heapMemoryUsage.getUsed());
}

From source file:com.riotgames.mondev.JMXDiscovery.java

public JMXDiscovery(String hostname, int port, String usr, String pwd) {
    try {// ww  w .  j ava 2s . c  o m
        this.jmxServerUrl = new JMXServiceURL(
                "service:jmx:rmi:///jndi/rmi://" + hostname + ":" + port + "/jmxrmi");
        jmxc = null;
        mbsc = null;
        username = usr;
        password = pwd;

        if (username != null && password == null || username == null && password != null)
            throw new IllegalArgumentException("Both username and password must be set or omitted");
    } catch (Exception e) {
        // Print error
    }
}