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:com.pivotal.gemfire.tools.pulse.internal.data.JMXDataUpdater.java

private JMXConnector getJMXConnection() {
    JMXConnector connection = null;
    // Reference to repository
    Repository repository = Repository.get();
    try {//from   ww w . j  av  a  2  s  . c  o m

        String jmxSerURL = "";

        if (LOGGER.infoEnabled()) {
            LOGGER.info(resourceBundle.getString("LOG_MSG_USE_LOCATOR_VALUE") + ":"
                    + repository.getJmxUseLocator());
        }

        if (repository.getJmxUseLocator()) {

            String locatorHost = repository.getJmxHost();
            int locatorPort = Integer.parseInt(repository.getJmxPort());

            if (LOGGER.infoEnabled()) {
                LOGGER.info(resourceBundle.getString("LOG_MSG_HOST") + " : " + locatorHost + " & "
                        + resourceBundle.getString("LOG_MSG_PORT") + " : " + locatorPort);
            }

            InetAddress inetAddr = InetAddress.getByName(locatorHost);

            if ((inetAddr instanceof Inet4Address) || (inetAddr instanceof Inet6Address)) {

                if (inetAddr instanceof Inet4Address) {
                    // Locator has IPv4 Address
                    if (LOGGER.infoEnabled()) {
                        LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_IPV4_ADDRESS") + " - "
                                + inetAddr.toString());
                    }
                } else {
                    // Locator has IPv6 Address
                    if (LOGGER.infoEnabled()) {
                        LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_IPV6_ADDRESS") + " - "
                                + inetAddr.toString());
                    }
                }

                JmxManagerInfo jmxManagerInfo = JmxManagerFinder.askLocatorForJmxManager(inetAddr, locatorPort,
                        15000, repository.isUseSSLLocator());

                if (jmxManagerInfo.port == 0) {
                    if (LOGGER.infoEnabled()) {
                        LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_COULD_NOT_FIND_MANAGER"));
                    }
                } else {
                    if (LOGGER.infoEnabled()) {
                        LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_FOUND_MANAGER") + " : "
                                + resourceBundle.getString("LOG_MSG_HOST") + " : " + jmxManagerInfo.host + " & "
                                + resourceBundle.getString("LOG_MSG_PORT") + " : " + jmxManagerInfo.port
                                + (jmxManagerInfo.ssl ? resourceBundle.getString("LOG_MSG_WITH_SSL")
                                        : resourceBundle.getString("LOG_MSG_WITHOUT_SSL")));
                    }

                    jmxSerURL = formJMXServiceURLString(jmxManagerInfo.host,
                            String.valueOf(jmxManagerInfo.port));
                }

            } /*
               * else if (inetAddr instanceof Inet6Address) { // Locator has IPv6
               * Address if(LOGGER.infoEnabled()){
               * LOGGER.info(resourceBundle.getString
               * ("LOG_MSG_LOCATOR_IPV6_ADDRESS")); } // update message to display
               * on UI cluster.setConnectionErrorMsg(resourceBundle.getString(
               * "LOG_MSG_JMX_CONNECTION_IPv6_ADDRESS"));
               * 
               * }
               */else {
                // Locator has Invalid locator Address
                if (LOGGER.infoEnabled()) {
                    LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_BAD_ADDRESS"));
                }
                // update message to display on UI
                cluster.setConnectionErrorMsg(resourceBundle.getString("LOG_MSG_JMX_CONNECTION_BAD_ADDRESS"));

            }

        } else {
            if (LOGGER.infoEnabled()) {
                LOGGER.info(resourceBundle.getString("LOG_MSG_HOST") + " : " + this.serverName + " & "
                        + resourceBundle.getString("LOG_MSG_PORT") + " : " + this.port);
            }
            jmxSerURL = formJMXServiceURLString(this.serverName, this.port);
        }

        if (StringUtils.isNotNullNotEmptyNotWhiteSpace(jmxSerURL)) {
            JMXServiceURL url = new JMXServiceURL(jmxSerURL);

            // String[] creds = {"controlRole", "R&D"};
            String[] creds = { this.userName, this.userPassword };
            Map<String, Object> env = new HashMap<String, Object>();

            env.put(JMXConnector.CREDENTIALS, creds);

            if (repository.isUseSSLManager()) {
                // use ssl to connect
                env.put("com.sun.jndi.rmi.factory.socket", new SslRMIClientSocketFactory());
            }

            connection = JMXConnectorFactory.connect(url, env);

            // Register Pulse URL if not already present in the JMX Manager
            registerPulseUrlToManager(connection);
        }
    } catch (Exception e) {
        if (e instanceof UnknownHostException) {
            // update message to display on UI
            cluster.setConnectionErrorMsg(resourceBundle.getString("LOG_MSG_JMX_CONNECTION_UNKNOWN_HOST"));
        }

        // write errors
        StringWriter swBuffer = new StringWriter();
        PrintWriter prtWriter = new PrintWriter(swBuffer);
        e.printStackTrace(prtWriter);
        LOGGER.severe("Exception Details : " + swBuffer.toString() + "\n");
        if (this.conn != null) {
            try {
                this.conn.close();
            } catch (Exception e1) {
                LOGGER.severe("Error closing JMX connection " + swBuffer.toString() + "\n");
            }
            this.conn = null;
        }
    }

    return connection;
}

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.opennms.features.jmxconfiggenerator.jmxconfig.JmxDatacollectionConfiggenerator.java

/**
 * This method gets the JmxConnector to connect with the given
 * jmxServiceURL./*from   ww w  .j av  a  2s  . c  o m*/
 * 
 * @param username
 *            may be null
 * @param password
 *            may be null
 * @param jmxServiceURL
 *            should not be null!
 * @return a jmxConnector
 * @throws IOException
 *             if the connection to the given jmxServiceURL fails (e.g.
 *             authentication failure or not reachable)
 */
public JMXConnector getJmxConnector(String username, String password, JMXServiceURL jmxServiceURL)
        throws IOException {
    JMXConnector jmxConnector;
    HashMap<String, String[]> env = new HashMap<String, String[]>();

    if (username != null && password != null) {
        String[] credentials = new String[] { username, password };
        env.put("jmx.remote.credentials", credentials);
    }

    jmxConnector = JMXConnectorFactory.connect(jmxServiceURL, env);
    jmxConnector.connect();

    return jmxConnector;
}

From source file:edu.nwpu.gemfire.monitor.data.JMXDataUpdater.java

private JMXConnector getJMXConnection() {
    JMXConnector connection = null;
    // Reference to repository
    Repository repository = Repository.get();
    try {/*from  ww w  . ja  va2 s.co  m*/

        String jmxSerURL = "";

        if (LOGGER.infoEnabled()) {
            LOGGER.info(resourceBundle.getString("LOG_MSG_USE_LOCATOR_VALUE") + ":"
                    + repository.getJmxUseLocator());
        }

        if (repository.getJmxUseLocator()) {

            String locatorHost = repository.getJmxHost();
            int locatorPort = Integer.parseInt(repository.getJmxPort());

            if (LOGGER.infoEnabled()) {
                LOGGER.info(resourceBundle.getString("LOG_MSG_HOST") + " : " + locatorHost + " & "
                        + resourceBundle.getString("LOG_MSG_PORT") + " : " + locatorPort);
            }

            InetAddress inetAddr = InetAddress.getByName(locatorHost);

            if ((inetAddr instanceof Inet4Address) || (inetAddr instanceof Inet6Address)) {

                if (inetAddr instanceof Inet4Address) {
                    // Locator has IPv4 Address
                    if (LOGGER.infoEnabled()) {
                        LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_IPV4_ADDRESS") + " - "
                                + inetAddr.toString());
                    }
                } else {
                    // Locator has IPv6 Address
                    if (LOGGER.infoEnabled()) {
                        LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_IPV6_ADDRESS") + " - "
                                + inetAddr.toString());
                    }
                }

                JmxManagerInfo jmxManagerInfo = JmxManagerFinder.askLocatorForJmxManager(inetAddr, locatorPort,
                        15000, repository.isUseSSLLocator());

                if (jmxManagerInfo.port == 0) {
                    if (LOGGER.infoEnabled()) {
                        LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_COULD_NOT_FIND_MANAGER"));
                    }
                } else {
                    if (LOGGER.infoEnabled()) {
                        LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_FOUND_MANAGER") + " : "
                                + resourceBundle.getString("LOG_MSG_HOST") + " : " + jmxManagerInfo.host + " & "
                                + resourceBundle.getString("LOG_MSG_PORT") + " : " + jmxManagerInfo.port
                                + (jmxManagerInfo.ssl ? resourceBundle.getString("LOG_MSG_WITH_SSL")
                                        : resourceBundle.getString("LOG_MSG_WITHOUT_SSL")));
                    }

                    jmxSerURL = formJMXServiceURLString(jmxManagerInfo.host,
                            String.valueOf(jmxManagerInfo.port));
                }

            } /*
               * else if (inetAddr instanceof Inet6Address) { // Locator has IPv6
               * Address if(LOGGER.infoEnabled()){
               * LOGGER.info(resourceBundle.getString
               * ("LOG_MSG_LOCATOR_IPV6_ADDRESS")); } // update message to display
               * on UI cluster.setConnectionErrorMsg(resourceBundle.getString(
               * "LOG_MSG_JMX_CONNECTION_IPv6_ADDRESS"));
               *
               * }
               */else {
                // Locator has Invalid locator Address
                if (LOGGER.infoEnabled()) {
                    LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_BAD_ADDRESS"));
                }
                // update message to display on UI
                cluster.setConnectionErrorMsg(resourceBundle.getString("LOG_MSG_JMX_CONNECTION_BAD_ADDRESS"));

            }

        } else {
            if (LOGGER.infoEnabled()) {
                LOGGER.info(resourceBundle.getString("LOG_MSG_HOST") + " : " + this.serverName + " & "
                        + resourceBundle.getString("LOG_MSG_PORT") + " : " + this.port);
            }
            jmxSerURL = formJMXServiceURLString(this.serverName, this.port);
        }

        if (StringUtils.isNotNullNotEmptyNotWhiteSpace(jmxSerURL)) {
            JMXServiceURL url = new JMXServiceURL(jmxSerURL);

            // String[] creds = {"controlRole", "R&D"};
            String[] creds = { this.userName, this.userPassword };
            Map<String, Object> env = new HashMap<String, Object>();

            env.put(JMXConnector.CREDENTIALS, creds);

            if (repository.isUseSSLManager()) {
                // use ssl to connect
                env.put("com.sun.jndi.rmi.factory.socket", new SslRMIClientSocketFactory());
            }

            connection = JMXConnectorFactory.connect(url, env);

            // Register Pulse URL if not already present in the JMX Manager
            registerPulseUrlToManager(connection);
        }
    } catch (Exception e) {
        if (e instanceof UnknownHostException) {
            // update message to display on UI
            cluster.setConnectionErrorMsg(resourceBundle.getString("LOG_MSG_JMX_CONNECTION_UNKNOWN_HOST"));
        }

        // write errors
        StringWriter swBuffer = new StringWriter();
        PrintWriter prtWriter = new PrintWriter(swBuffer);
        e.printStackTrace(prtWriter);
        LOGGER.severe("Exception Details : " + swBuffer.toString() + "\n");
        if (this.conn != null) {
            try {
                this.conn.close();
            } catch (Exception e1) {
                LOGGER.severe("Error closing JMX connection " + swBuffer.toString() + "\n");
            }
            this.conn = null;
        }
    }

    return connection;
}

From source file:org.wso2.carbon.integration.test.metrics.CarbonMetricsTestCase.java

/**
 * This method will force metric manager to collect metrics by invoking report() method
 * using remote jmx//ww  w  . j a v a 2 s  .co  m
 * @throws IOException
 * @throws MalformedObjectNameException
 */
private void invokeJMXReportOperation()
        throws IOException, MalformedObjectNameException, XPathExpressionException {
    int JMXServicePort = Integer.parseInt(cepServer.getInstance().getPorts().get("jmxserver"));
    int RMIRegistryPort = Integer.parseInt(cepServer.getInstance().getPorts().get("rmiregistry"));
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://localhost:" + JMXServicePort
            + "/jndi/rmi://localhost:" + RMIRegistryPort + "/jmxrmi");
    Map<String, String[]> env = new HashMap<>();
    String[] credentials = { "admin", "admin" };
    env.put(JMXConnector.CREDENTIALS, credentials);
    JMXConnector jmxConnector = JMXConnectorFactory.connect(url, env);
    MBeanServerConnection mbeanServerConnection = jmxConnector.getMBeanServerConnection();
    ObjectName mbeanName = new ObjectName("org.wso2.carbon:type=MetricManager");
    MetricManagerMXBean mbeanProxy = MBeanServerInvocationHandler.newProxyInstance(mbeanServerConnection,
            mbeanName, MetricManagerMXBean.class, true);
    mbeanProxy.report();
    jmxConnector.close();
}

From source file:com.googlecode.jmxtrans.model.Server.java

/**
 * Helper method for connecting to a Server. You need to close the resulting
 * connection.//from  w w  w . ja v  a  2s.  com
 */
@Override
@JsonIgnore
public JMXConnector getServerConnection() throws IOException {
    JMXServiceURL url = new JMXServiceURL(getUrl());
    return JMXConnectorFactory.connect(url, this.getEnvironment());
}

From source file:org.opennms.systemreport.AbstractSystemReportPlugin.java

private MBeanServerConnection getConnection() {
    final List<Integer> ports = new ArrayList<Integer>();
    Integer p = Integer.getInteger("com.sun.management.jmxremote.port");
    if (p != null)
        ports.add(p);//from w  w  w  .  j  a v a  2  s .  c  om
    ports.add(18980);
    ports.add(1099);
    for (final Integer port : ports) {
        LOG.trace("Trying JMX at localhost:{}/jmxrmi", port);
        try {
            JMXServiceURL url = new JMXServiceURL(
                    String.format("service:jmx:rmi:///jndi/rmi://localhost:%d/jmxrmi", port));
            JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
            return jmxc.getMBeanServerConnection();
        } catch (final Exception e) {
            LOG.debug("Unable to get JMX connection to OpenNMS on port {}.", port, e);
        }
    }
    return null;
}

From source file:org.wso2.carbon.analytics.common.jmx.agent.JmxAgentWebInterface.java

private JMXConnector getJmxConnector(String url, String userName, String password) throws IOException {
    JMXServiceURL jmxServiceURL = new JMXServiceURL(url);
    Map<String, String[]> map = new HashMap<String, String[]>(1);

    map.put(JmxConstant.JMX_REMOTE_CREDENTIALS_STR, new String[] { userName, password });
    return JMXConnectorFactory.connect(jmxServiceURL, map);
}

From source file:org.rhq.cassandra.ClusterInitService.java

private String getSchemaVersionForNode(String storageNode, int jmxPort) throws Exception {
    String url = this.getJMXConnectionURL(storageNode, jmxPort);
    JMXServiceURL serviceURL = new JMXServiceURL(url);
    Map<String, String> env = new HashMap<String, String>();
    JMXConnector connector = null;

    try {//  www  .  j a  va  2 s.c  om
        connector = JMXConnectorFactory.connect(serviceURL, env);
        MBeanServerConnection serverConnection = connector.getMBeanServerConnection();
        ObjectName storageService = new ObjectName("org.apache.cassandra.db:type=StorageService");
        String attribute = "SchemaVersion";
        try {
            return (String) serverConnection.getAttribute(storageService, attribute);
        } catch (Exception e) {
            // It is ok to just catch and log exceptions here particularly in an integration
            // test environment where we could potentially try to do the JMX query before
            // Cassandra is fully initialized. We can query StorageService before the native
            // transport server is initialized which will result in Cassandra throwing a NPE.
            // We do not want propagate that exception because it is just a matter of waiting
            // for Cassandra to finish initializing.
            if (log.isDebugEnabled()) {
                log.debug("Failed to read attribute [" + attribute + "] from " + storageService, e);
            } else {
                log.info("Faied to read attribute [" + attribute + "] from " + storageService + ": "
                        + e.getMessage());
            }
        }
    } finally {
        if (connector != null) {
            connector.close();
        }
    }
    return null;
}

From source file:com.cisco.oss.foundation.message.HornetQMessagingFactory.java

private static void printHQVersion(final String host, final String port) {
    LOGGER.info("HornetQ version: {}", VersionLoader.getVersion().getVersionName());

    Runnable getVersionFromServer = new Runnable() {
        @Override/*from w  w  w  .jav  a 2  s.  c o  m*/
        public void run() {
            try {

                // Step 9. Retrieve the ObjectName of the queue. This is used to identify the server resources to manage
                ObjectName on = ObjectNameBuilder.DEFAULT.getHornetQServerObjectName();

                // Step 10. Create JMX Connector to connect to the server's MBeanServer
                String url = MessageFormat.format("service:jmx:rmi://{0}/jndi/rmi://{0}:{1}/jmxrmi", host,
                        port == null ? "3900" : port);
                LOGGER.debug("HornetQ Server jmx url: {}", url);
                JMXConnector connector = JMXConnectorFactory.connect(new JMXServiceURL(url), new HashMap());

                // Step 11. Retrieve the MBeanServerConnection
                MBeanServerConnection mbsc = connector.getMBeanServerConnection();

                // Step 12. Create a JMSQueueControl proxy to manage the queue on the server
                JMSServerControl serverControl = MBeanServerInvocationHandler.newProxyInstance(mbsc, on,
                        JMSServerControl.class, false);

                String serverControlVersion = serverControl.getVersion();
                LOGGER.info("HornetQ Server version: {}", serverControlVersion);

            } catch (Exception e) {
                LOGGER.info("can't log server version. error is: {}", e.toString());
            }
        }
    };

    try {

        new Thread(getVersionFromServer).start();

    } catch (Exception e) {
        LOGGER.info("can't log server version. error is: {}", e.toString());
    }
}