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:org.apache.hadoop.hdfs.tools.JMXGet.java

/**
 * @throws Exception//w ww .j av a 2s .c  om
 *     initializes MBeanServer
 */
public void init() throws Exception {

    err("init: server=" + server + ";port=" + port + ";service=" + service + ";localVMUrl=" + localVMUrl);

    String url_string = null;
    // build connection url
    if (localVMUrl != null) {
        // use
        // jstat -snap <vmpid> | grep sun.management.JMXConnectorServer.address
        // to get url
        url_string = localVMUrl;
        err("url string for local pid = " + localVMUrl + " = " + url_string);

    } else if (!port.isEmpty() && !server.isEmpty()) {
        // using server and port
        url_string = "service:jmx:rmi:///jndi/rmi://" + server + ":" + port + "/jmxrmi";
    } // else url stays null

    // Create an RMI connector client and
    // connect it to the RMI connector server

    if (url_string == null) { // assume local vm (for example for Testing)
        mbsc = ManagementFactory.getPlatformMBeanServer();
    } else {
        JMXServiceURL url = new JMXServiceURL(url_string);

        err("Create RMI connector and connect to the RMI connector server" + url);

        JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
        // Get an MBeanServerConnection
        //
        err("\nGet an MBeanServerConnection");
        mbsc = jmxc.getMBeanServerConnection();
    }

    // Get domains from MBeanServer
    //
    err("\nDomains:");

    String domains[] = mbsc.getDomains();
    Arrays.sort(domains);
    for (String domain : domains) {
        err("\tDomain = " + domain);
    }

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

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

    // Query MBean names for specific domain "hadoop" and service
    ObjectName query = new ObjectName("Hadoop:service=" + service + ",*");
    hadoopObjectNames = new ArrayList<>(5);
    err("\nQuery MBeanServer MBeans:");
    Set<ObjectName> names = new TreeSet<>(mbsc.queryNames(query, null));

    for (ObjectName name : names) {
        hadoopObjectNames.add(name);
        err("Hadoop service: " + name);
    }

}

From source file:uk.co.gidley.jmxmonitor.monitoring.MonitoringGroup.java

/**
 * Initialise the monitor. If possible we start the JMX connection now. If not we create a placeholder.
 *
 * @param monitorUrlKey/*from   w  w  w.  ja v  a 2  s  . c o m*/
 * @param monitorsConfiguration
 * @throws MalformedObjectNameException
 * @throws MalformedURLException
 */
private void initialiseMonitorUrl(String monitorUrlKey, CompositeConfiguration monitorsConfiguration)
        throws MalformedObjectNameException, MalformedURLException {
    logger.debug("Initialising Monitor Connection {}", monitorUrlKey);

    String url = monitorsConfiguration.getString(ThreadManager.PROPERTY_PREFIX + monitorUrlKey + URL);
    try {
        // Create JMX connection
        JMXServiceURL serviceUrl = new JMXServiceURL(url);
        JMXConnector jmxc = JMXConnectorFactory.connect(serviceUrl, null);
        logger.debug("JMX connection made {}", jmxc);
        MonitoringGroup.MonitorUrlHolder monitorUrlHolder = monitorUrlHolders.get(monitorUrlKey);
        monitorUrlHolder.setmBeanServerConnection(jmxc.getMBeanServerConnection());
        monitorUrlHolder.getMonitors().clear();

        // Parse monitors inside this
        List<String> loadedMonitors = new ArrayList<String>();
        Iterator<String> monitorKeys = monitorsConfiguration
                .getKeys(ThreadManager.PROPERTY_PREFIX + monitorUrlKey);
        while (monitorKeys.hasNext()) {
            String key = monitorKeys.next();
            if (!key.endsWith(URL)) {
                String monitorName = key.substring(
                        ThreadManager.PROPERTY_PREFIX.length() + monitorUrlKey.length() + 1,
                        key.lastIndexOf("."));
                // Only load each on once (there will be n keys)
                if (!loadedMonitors.contains(monitorName)) {
                    constructMonitor(monitorUrlKey, monitorsConfiguration, monitorUrlHolder, monitorName);
                    loadedMonitors.add(monitorName);
                }
            }
        }
    } catch (IOException e) {
        if (e instanceof MalformedURLException) {
            throw (MalformedURLException) e;
        }
        logger.warn("Unable to connect to {}, {}", monitorUrlKey, e);
    }
}

From source file:org.fluentd.jvmwatcher.proxy.JvmClientProxy.java

/**
 * @return/*  www  .  j  ava  2s. c o m*/
 */
public boolean connect() {
    if (this.localJvmInfo_ == null) {
        return false;
    }

    // connect the JVM server
    if (this.localJvmInfo_.isManageable() != true) {
        try {
            // get JVM Agent address
            this.localJvmInfo_.startManagementAgent();
        } catch (IOException ex) {
            log.error("startManagementAgent error.", ex);
            return false;
        } catch (Exception ex) {
            log.error("startManagementAgent error.", ex);
            return false;
        }
    }

    // connect JVM MBean Server 
    try {
        if (this.jmxUrl_ == null) {
            this.jmxUrl_ = new JMXServiceURL(this.localJvmInfo_.getAddress());
            this.jmxc_ = JMXConnectorFactory.connect(jmxUrl_, null);
            this.server_ = this.jmxc_.getMBeanServerConnection();
        }
    } catch (MalformedURLException ex) {
        log.error(" connect JVM MBean Server error.", ex);
        return false;
    } catch (IOException ex) {
        log.error(" connect JVM MBean Server error.", ex);
        return false;
    } catch (Exception ex) {
        log.error(" connect JVM MBean Server error.", ex);
        return false;
    }

    // this client have successfully connected to the JVM server.
    this.isDeadServer_ = false;

    try {
        ObjectName objName = new ObjectName(THREAD_MXBEAN_NAME);
        this.hasPlatformMXBeans_ = this.server_.isRegistered(objName);
        this.hasHotSpotDiagnosticMXBean_ = this.server_
                .isRegistered(new ObjectName(HOTSPOT_DIAGNOSTIC_MXBEAN_NAME));
        // check if it has 6.0 new APIs
        if (this.hasPlatformMXBeans_ = true) {
            MBeanOperationInfo[] mopis = this.server_.getMBeanInfo(objName).getOperations();
            // look for findDeadlockedThreads operations;
            for (MBeanOperationInfo op : mopis) {
                if (op.getName().equals("findDeadlockedThreads")) {
                    this.supportsLockUsage_ = true;
                    break;
                }
            }

            objName = new ObjectName(COMPILATION_MXBEAN_NAME);
            this.hasCompilationMXBean_ = this.server_.isRegistered(objName);
        }

        if (this.hasPlatformMXBeans_ == true) {
            // WORKAROUND for bug 5056632
            // Check if the access role is correct by getting a RuntimeMXBean
            getRuntimeMXBean();
        }
    } catch (MalformedObjectNameException ex) {
        log.error("connect error.", ex);
        return false;
    } catch (IntrospectionException ex) {
        log.error("connect error.", ex);
        return false;
    } catch (InstanceNotFoundException ex) {
        log.error("connect error.", ex);
        return false;
    } catch (ReflectionException ex) {
        log.error("connect error.", ex);
        return false;
    } catch (IOException ex) {
        log.error("connect error.", ex);
        return false;
    } catch (Exception ex) {
        log.error("connect error.", ex);
        return false;
    }

    // connect success.
    this.isConnect_ = true;

    return true;
}

From source file:com.exxatools.monitoring.jmx.JmxStats.java

/**
 * Get a MBean server connection. Either opens a new connection or returns an already opened connection.
 *
 * @return the opened connection//ww  w .  ja  v  a 2s.  c  om
 * @throws IOException in case the connection cannot be established
 */
protected MBeanServerConnection getConnection() throws IOException {
    if (connection == null) {
        Map<String, Object> environment = new HashMap<String, Object>();
        if (username != null && password != null) {
            environment.put(JMXConnector.CREDENTIALS, new String[] { username, password });
        }
        connector = JMXConnectorFactory.connect(serviceUrl, environment);
        connection = connector.getMBeanServerConnection();
    }
    return connection;
}

From source file:com.spotify.reaper.cassandra.JmxProxy.java

/**
 * Connect to JMX interface on the given host and port.
 *
 * @param handler  Implementation of {@link RepairStatusHandler} to process incoming
 *                 notifications/*from ww  w .ja  v  a 2s  .  c o  m*/
 *                 of repair events.
 * @param host     hostname or ip address of Cassandra node
 * @param port     port number to use for JMX connection
 * @param username username to use for JMX authentication
 * @param password password to use for JMX authentication
 */
static JmxProxy connect(Optional<RepairStatusHandler> handler, String host, int port, String username,
        String password) throws ReaperException {
    ObjectName ssMbeanName;
    ObjectName cmMbeanName;
    JMXServiceURL jmxUrl;
    try {
        jmxUrl = new JMXServiceURL(String.format(JMX_URL, host, port));
        ssMbeanName = new ObjectName(SS_OBJECT_NAME);
        cmMbeanName = new ObjectName(CompactionManager.MBEAN_OBJECT_NAME);
    } catch (MalformedURLException | MalformedObjectNameException e) {
        LOG.error(String.format("Failed to prepare the JMX connection to %s:%s", host, port));
        throw new ReaperException("Failure during preparations for JMX connection", e);
    }
    try {
        Map<String, Object> env = new HashMap<String, Object>();
        if (username != null && password != null) {
            String[] creds = { username, password };
            env.put(JMXConnector.CREDENTIALS, creds);
        }
        JMXConnector jmxConn = JMXConnectorFactory.connect(jmxUrl, env);
        MBeanServerConnection mbeanServerConn = jmxConn.getMBeanServerConnection();
        Object ssProxy = JMX.newMBeanProxy(mbeanServerConn, ssMbeanName, StorageServiceMBean.class);
        String cassandraVersion = ((StorageServiceMBean) ssProxy).getReleaseVersion();
        if (cassandraVersion.startsWith("2.0") || cassandraVersion.startsWith("1.")) {
            ssProxy = JMX.newMBeanProxy(mbeanServerConn, ssMbeanName, StorageServiceMBean20.class);
        }

        CompactionManagerMBean cmProxy = JMX.newMBeanProxy(mbeanServerConn, cmMbeanName,
                CompactionManagerMBean.class);
        JmxProxy proxy = new JmxProxy(handler, host, jmxUrl, jmxConn, ssProxy, ssMbeanName, mbeanServerConn,
                cmProxy);
        // registering a listener throws bunch of exceptions, so we do it here rather than in the
        // constructor
        mbeanServerConn.addNotificationListener(ssMbeanName, proxy, null, null);
        LOG.debug("JMX connection to {} properly connected: {}", host, jmxUrl.toString());
        return proxy;
    } catch (IOException | InstanceNotFoundException e) {
        LOG.error("Failed to establish JMX connection to {}:{}", host, port);
        throw new ReaperException("Failure when establishing JMX connection", e);
    }
}

From source file:gr.cslab.Metric_test.java

static public void list() {
    String host = hosts.remove(0);
    try {/*  ww w  . ja  v a 2s  .  c o  m*/

        String url = "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi";
        System.out.println("RMI URL:\t" + url + "");
        JMXServiceURL serviceUrl = new JMXServiceURL(url);
        try (JMXConnector jmxc = JMXConnectorFactory.connect(serviceUrl, null)) {
            MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

            System.out.println("List of available names");

            Set<ObjectName> names;
            names = new TreeSet<>(mbsc.queryNames(null, null));
            System.out.println("Available names:");
            for (ObjectName name : names) {
                System.out.println("\tObjectName = " + name);
            }
        }
    } catch (IOException ex) {
        System.err.println("ERROR: failed to query the server " + host);
    }

}

From source file:com.dsf.dbxtract.cdc.AppJournalWindowTest.java

@Test(dependsOnMethods = { "testAppWithJournalWindow" })
public void testInfoStatistics() throws Exception {

    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:5000/jmxrmi");
    JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

    ObjectName mbeanName = new ObjectName("com.dsf.dbxtract:type=InfoMBean");

    TabularDataSupport info = (TabularDataSupport) mbsc.getAttribute(mbeanName, InfoMBean.ATTR_INFO);
    Collection<?> list = info.values();
    boolean hasHandlerEntry = false;
    for (Iterator<?> it = list.iterator(); it.hasNext();) {
        CompositeDataSupport entry = (CompositeDataSupport) it.next();

        if (entry.get("handler").equals(TestWindowHandler.class.getName())) {
            assert (((Long) entry.get("readCount")).longValue() == TEST_SIZE);
            hasHandlerEntry = true;/*  w  ww  . j a v  a 2 s .c om*/
        }
    }
    assert (hasHandlerEntry);
    jmxc.close();
}

From source file:org.wso2.appserver.integration.tests.config.EnvironmentVariableReadTestCase.java

@Test(groups = "wso2.as", description = "Try to persist a Employee obj through the Sessionfactory")
public void testConnectingToJMXServer() throws Exception {
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://localhost:" + (SERVER_PORT + portOffset)
            + "/jndi/rmi://localhost:" + (REGISTRY_PORT + portOffset) + "/jmxrmi");
    Map<String, Object> environment = new HashMap<>();
    String[] credentials = { "admin", "admin" };
    environment.put(JMXConnector.CREDENTIALS, credentials);
    JMXConnector jmxc = JMXConnectorFactory.connect(url, environment);
    log.info("Connection Id =" + jmxc.getConnectionId());
}

From source file:io.mapzone.arena.ArenaPlugin.java

protected void testMBeanConnection() throws Exception {
    // test connection
    String port = System.getProperty("com.sun.management.jmxremote.port");
    if (port != null) {
        String url = "service:jmx:rmi:///jndi/rmi://localhost:" + port + "/jmxrmi";
        JMXServiceURL serviceUrl = new JMXServiceURL(url);
        try (JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceUrl, null);) {
            MBeanServerConnection conn = jmxConnector.getMBeanServerConnection();
            Set<ObjectName> beanSet = conn.queryNames(null, null);
            beanSet.forEach(n -> log.debug("    MBean: " + n));

            beanSet = conn.queryNames(ArenaConfigMBean.NAME.get(), null);
            beanSet.forEach(n -> log.debug("    MBean: " + n));

            ArenaConfigMBean arenaConfig = JMX.newMBeanProxy(conn, ArenaConfigMBean.NAME.get(),
                    ArenaConfigMBean.class);
            arenaConfig.setAppTitle("Arena");
        }/* w  w  w  .ja  v  a  2 s  .  c  om*/
    } else {
        log.info("No jmxremote.port specified.");
    }
}

From source file:dk.netarkivet.common.utils.JMXUtils.java

/**
 * Connects to the given (url-specified) service point,
 * sending the given credentials as login.
 * @param url The JMX service url of some JVM on some machine.
 * @param credentials a map with (at least) one entry, mapping
 * "jmx.remote.credentials" to a String array of length 2.
 * Its first item should be the user name.
 * Its second item should be the password.
 * @return An MBeanServerConnection representing the
 * connected session.//from   ww  w.j  av a  2  s  .c o m
 */
public static MBeanServerConnection getMBeanServerConnection(JMXServiceURL url,
        Map<String, String[]> credentials) {
    ArgumentNotValid.checkNotNull(url, "JMXServiceURL url");
    ArgumentNotValid.checkNotNull(credentials, "Map<String,String[]> credentials");
    try {
        ensureJndiInitialContext();
        return JMXConnectorFactory.connect(url, credentials).getMBeanServerConnection();
    } catch (IOException e) {
        throw new IOFailure("Could not connect to " + url.toString(), e);
    }
}