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:dk.netarkivet.common.utils.JMXUtils.java

/** Get a JMXConnector to a given host and port, using login and password.
 *
 * @param hostName The host to attempt to connect to.
 * @param jmxPort The port on the host to connect to
 * (a non-negative number)./*  w  w w . ja va  2  s .c om*/
 * @param login The login name to authenticate as (typically "controlRole"
 * or "monitorRole".
 * @param password The password for JMX access.
 * @return A JMX connector to the given host and port, using default RMI.
 * @throws IOFailure if connecting to JMX fails.
 */
public static JMXConnector getJMXConnector(String hostName, int jmxPort, final String login,
        final String password) {
    ArgumentNotValid.checkNotNullOrEmpty(hostName, "String hostName");
    ArgumentNotValid.checkNotNegative(jmxPort, "int jmxPort");
    ArgumentNotValid.checkNotNullOrEmpty(login, "String login");
    ArgumentNotValid.checkNotNullOrEmpty(password, "String password");

    JMXServiceURL rmiurl = getUrl(hostName, jmxPort, -1);
    Map<String, ?> environment = packageCredentials(login, password);
    Throwable lastException;
    int retries = 0;
    final int maxJmxRetries = getMaxTries();
    do {
        try {
            return JMXConnectorFactory.connect(rmiurl, environment);
        } catch (IOException e) {
            lastException = e;
            if (retries < maxJmxRetries && e.getCause() != null
                    && (e.getCause() instanceof ServiceUnavailableException
                            || e.getCause() instanceof SocketTimeoutException)) {
                // Sleep a bit before trying again
                TimeUtils.exponentialBackoffSleep(retries);
                /*  called exponentialBackoffSleep(retries) which used
                Calendar.MILLISECOND as time unit, which means we only
                wait an exponential number of milliseconds.
                */
                continue;
            }
            break;
        }
    } while (retries++ < maxJmxRetries);
    throw new IOFailure(
            "Failed to connect to URL " + rmiurl + " after " + retries + " of " + maxJmxRetries
                    + " attempts.\nException type: " + lastException.getCause().getClass().getName(),
            lastException);
}

From source file:org.apache.hadoop.test.system.AbstractDaemonClient.java

/**
 * Create connection with the remove JMX server at given host and port
 * @param host name of the remote JMX server host
 * @param port port number of the remote JXM server host
 * @return instance of MBeanServerConnection or <code>null</code> if one
 *    hasn't been established/*from w  w w .  j av  a  2s.c  om*/
 * @throws IOException in case of comminication errors
 */
protected MBeanServerConnection establishJmxConnection(String host, int port) throws IOException {
    if (connection != null)
        return connection;
    String urlPattern = null;
    try {
        urlPattern = "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi";
        JMXServiceURL url = new JMXServiceURL(urlPattern);
        JMXConnector connector = JMXConnectorFactory.connect(url, null);
        connection = connector.getMBeanServerConnection();
    } catch (java.net.MalformedURLException badURLExc) {
        LOG.debug("bad url: " + urlPattern, badURLExc);
        throw new IOException(badURLExc);
    }
    return connection;
}

From source file:org.hyperic.hq.product.jmx.MxUtil.java

public static JMXConnector getMBeanConnector(Properties config) throws MalformedURLException, IOException {

    String jmxUrl = config.getProperty(MxUtil.PROP_JMX_URL);
    Map map = new HashMap();

    String user = config.getProperty(PROP_JMX_USERNAME);
    String pass = config.getProperty(PROP_JMX_PASSWORD);

    map.put(JMXConnector.CREDENTIALS, new String[] { user, pass });

    // required for Oracle AS
    String providerPackages = config.getProperty(PROP_JMX_PROVIDER_PKGS);
    if (providerPackages != null)
        map.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, providerPackages);

    if (jmxUrl == null) {
        throw new MalformedURLException(PROP_JMX_URL + "==null");
    }/*from  ww w . ja  v  a 2 s .c o m*/

    if (jmxUrl.startsWith(PTQL_PREFIX)) {
        jmxUrl = getUrlFromPid(jmxUrl.substring(PTQL_PREFIX.length()));
    }

    JMXServiceURL url = new JMXServiceURL(jmxUrl);

    String proto = url.getProtocol();
    if (proto.equals("t3") || proto.equals("t3s")) {
        //http://edocs.bea.com/wls/docs92/jmx/accessWLS.html
        //WebLogic support, requires:
        //cp $WLS_HOME/server/lib/wljmxclient.jar pdk/lib/
        //cp $WLS_HOME/server/lib/wlclient.jar pdk/lib/
        map.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote");
        map.put(Context.SECURITY_PRINCIPAL, user);
        map.put(Context.SECURITY_CREDENTIALS, pass);
    }

    JMXConnector connector = JMXConnectorFactory.connect(url, map);
    if (log.isDebugEnabled()) {
        log.debug("created new JMXConnector url=" + url + ", classloader="
                + Thread.currentThread().getContextClassLoader());
    }
    return connector;
}

From source file:org.eclipse.virgo.server.svt.hostedrepo.RemoteHostedRepositoryTests.java

private static MBeanServerConnection getMBeanServerConnection() throws Exception {
    String severDir = null;//www. j  a  va  2  s. c o m
    String[] creds = { "admin", "springsource" };
    Map<String, String[]> env = new HashMap<String, String[]>();

    File testExpanded = new File("src/test/resources");
    for (File mainDir : testExpanded.listFiles()) {
        if (mainDir.isDirectory() && mainDir.getName().equals("virgo-web-server")) {
            severDir = new File(mainDir.toURI()).getCanonicalPath();
        }
    }
    env.put(JMXConnector.CREDENTIALS, creds);
    System.setProperty("javax.net.ssl.trustStore", severDir + KEYSTORE);
    System.setProperty("javax.net.ssl.trustStorePassword", KEYPASSWORD);
    JMXServiceURL url = new JMXServiceURL(JMXURL);
    connection = JMXConnectorFactory.connect(url, env).getMBeanServerConnection();
    return connection;
}

From source file:com.continuent.tungsten.common.jmx.JmxManager.java

/**
 * Client helper method to return an RMI connection on the server whose
 * properties are the same as this manager instance.
 * //from   w w w .  j a va2s  .c om
 * @return a connection to the server
 */
public JMXConnector getLocalRMIConnector() {
    String serviceAddress = null;
    try {
        // --- Define security attributes ---
        HashMap<String, Object> env = new HashMap<String, Object>();

        // --- Authentication based on password and access files---
        if (authenticationInfo != null && authenticationInfo.isAuthenticationNeeded()) {
            // Build credentials
            String[] credentials;
            if (authenticationInfo.isUseTungstenAuthenticationRealm())
                credentials = new String[] { authenticationInfo.getUsername(),
                        authenticationInfo.getDecryptedPassword(),
                        AuthenticationInfo.TUNGSTEN_AUTHENTICATION_REALM };
            else
                credentials = new String[] { authenticationInfo.getUsername(),
                        authenticationInfo.getDecryptedPassword() };

            env.put("jmx.remote.credentials", credentials);
        }
        // --- SSL ---
        if (authenticationInfo != null && authenticationInfo.isEncryptionNeeded()) {
            // Truststore
            System.setProperty("javax.net.ssl.trustStore", authenticationInfo.getTruststoreLocation());
            System.setProperty("javax.net.ssl.trustStorePassword", authenticationInfo.getTruststorePassword());
        }

        serviceAddress = generateServiceAddress(host, beanPort, registryPort, serviceName);
        JMXServiceURL address = new JMXServiceURL(serviceAddress);
        JMXConnector connector = JMXConnectorFactory.connect(address, env);
        return connector;
    } catch (Exception e) {
        // --- Try to get more details on the connection problem
        // String errorMessage = String
        // .format("Cannot establish a connection with component '%s' at
        // address %s:%d\n",
        // serviceName, host, registryPort);
        String errorMessage = MessageFormat.format(
                "Cannot establish a connection with component {0} at address {1}:{2}\n{3}", serviceName, host,
                registryPort, e);
        String errorReason = null;
        AssertionError assertionError = null;

        // Authentication required by server
        if (e instanceof SecurityException) {
            errorReason = String.format("Reason=%s\n", e.toString());
            assertionError = new AssertionError("Authentication required by server");
        }
        // Encryption required by server
        else if (e.getCause() instanceof SSLHandshakeException) {
            errorReason = String
                    .format("Reason=" + "javax.net.ssl.SSLHandshakeException: Server requires SSL.\n");
            assertionError = new AssertionError("Encryption required by server");
        } else if (e instanceof ConfigurationException) {
            errorMessage = e.getMessage();
            assertionError = new AssertionError("Configuration error");
        }
        // Other IOException
        else if (e instanceof IOException) {
            errorMessage = String.format("A component of type '%s' at address %s:%d is not available.\n %s\n",
                    serviceName, host, registryPort, e);
            errorReason = "Check to be sure that the service is running.\n";
        }

        if (logger.isDebugEnabled()) {
            logger.debug(String.format(errorMessage + errorReason), e);
        }

        throw new ServerRuntimeException(String.format(errorMessage + errorReason),
                (assertionError != null) ? assertionError : e);
    }
}

From source file:org.eclipse.virgo.server.svt.hostedrepo.RemoteHostedRepositoryOtherThan8080Tests.java

private static MBeanServerConnection getMBeanServerConnection() throws Exception {
    String severDir = null;/*from  w  ww  . ja  va  2s  . co m*/
    String[] creds = { "admin", "springsource" };
    Map<String, String[]> env = new HashMap<String, String[]>();

    File testExpanded = new File("src/test/resources");
    for (File mainDir : testExpanded.listFiles()) {
        if (mainDir.isDirectory() && mainDir.getName().equals("virgo-web-server2")) {
            severDir = new File(mainDir.toURI()).getCanonicalPath();
        }
    }
    env.put(JMXConnector.CREDENTIALS, creds);
    System.setProperty("javax.net.ssl.trustStore", severDir + KEYSTORE);
    System.setProperty("javax.net.ssl.trustStorePassword", KEYPASSWORD);
    JMXServiceURL url = new JMXServiceURL(JMXURL);
    connection = JMXConnectorFactory.connect(url, env).getMBeanServerConnection();
    return connection;
}

From source file:com.mustardgrain.solr.SolrClient.java

private static Runnable getStatsRunner(final WeakReference<SolrClient> lbRef) {
    return new Runnable() {

        @Override/*from ww w.  j  a  va 2  s  .  c  om*/
        public void run() {
            SolrClient lb = lbRef.get();
            if (lb != null && lb.serverStats != null && LOG.isInfoEnabled()) {
                StringBuilder sb = new StringBuilder();
                sb.append("server responses over past ");
                sb.append(TimeUnit.MILLISECONDS.toMinutes(lb.statsInterval));
                sb.append(" mins (good/timeout/zero found) and cache hit ratio: ");
                boolean appendComma = false;

                for (Map.Entry<String, SolrStats> entry : lb.serverStats.entrySet()) {
                    if (appendComma)
                        sb.append(", ");

                    String server = entry.getKey();
                    SolrStats stats = entry.getValue();
                    String hitRatio = getHitRatio(server);

                    sb.append(server);
                    sb.append(": ");
                    sb.append(stats.getSuccesses());
                    sb.append("/");
                    sb.append(stats.getReadTimeouts());
                    sb.append("/");
                    sb.append(stats.getEmptyResults());
                    sb.append(" ");
                    sb.append(hitRatio);

                    appendComma = true;

                    stats.reset(); // Reset the counters once printed
                }

                LOG.info(sb);
            }
        }

        /**
         * Determines the hit ratio for the query result cache by calling
         * the SolrServer via JMX and reading its MBean containing that
         * information.
         * @param server Server from which to pull information
         * @return String form of hit ratio (either "n/a" or "xx%")
         */

        private String getHitRatio(String server) {
            String hitRatio = "n/a";
            JMXConnector jmxc = null;

            try {
                URL url = new URL(server);
                String domain = url.getPath();

                if (domain.startsWith("/"))
                    domain = domain.substring(1);

                ObjectName name = new ObjectName(
                        domain + ":id=org.apache.solr.search.LRUCache,type=queryResultCache");
                JMXServiceURL jmxUrl = new JMXServiceURL(
                        "service:jmx:rmi:///jndi/rmi://" + url.getHost() + ":7199/jmxrmi");
                jmxc = JMXConnectorFactory.connect(jmxUrl, null);
                MBeanServerConnection con = jmxc.getMBeanServerConnection();

                Object result = con.getAttribute(name, "hitratio");
                hitRatio = (int) (Float.parseFloat(String.valueOf(result)) * 100.0f) + "%";
            } catch (Exception e) {
                LOG.error(getNestedErrorMessages(e));
            } finally {
                if (jmxc != null) {
                    try {
                        jmxc.close();
                    } catch (Exception e) {
                        LOG.error(getNestedErrorMessages(e));
                    }
                }
            }

            return hitRatio;
        }

    };
}

From source file:org.rhq.storage.installer.StorageInstaller.java

boolean verifyNodeIsUp(String address, int jmxPort, int retries, long timeout) throws Exception {
    String url = "service:jmx:rmi:///jndi/rmi://" + address + ":" + jmxPort + "/jmxrmi";
    JMXServiceURL serviceURL = new JMXServiceURL(url);
    JMXConnector connector = null;
    MBeanServerConnection serverConnection = null;

    // Sleep a few seconds to work around https://issues.apache.org/jira/browse/CASSANDRA-5467
    try {/*w  w  w.  ja  v a2 s .  c o  m*/
        Thread.sleep(3000);
    } catch (InterruptedException e) {
    }

    Map<String, String> env = new HashMap<String, String>();
    for (int i = 0; i < retries; ++i) {
        try {
            connector = JMXConnectorFactory.connect(serviceURL, env);
            serverConnection = connector.getMBeanServerConnection();
            ObjectName storageService = new ObjectName("org.apache.cassandra.db:type=StorageService");
            Boolean nativeTransportRunning = (Boolean) serverConnection.getAttribute(storageService,
                    "NativeTransportRunning");

            return nativeTransportRunning;
        } catch (Exception e) {
            if (i < retries) {
                if (log.isDebugEnabled()) {
                    log.debug("The storage node is not up.", e);
                } else {
                    Throwable rootCause = ThrowableUtil.getRootCause(e);
                    log.info("The storage node is not up: " + rootCause.getClass().getName() + ": "
                            + rootCause.getMessage());
                }
                log.info("Checking storage node status again in " + (timeout * (i + 1)) + " ms...");
            }
            Thread.sleep(timeout * (i + 1));
        }
    }
    return false;
}

From source file:org.kuali.test.utils.Utils.java

public static JMXConnector getJMXConnector(String url, String username, String password)
        throws MalformedURLException, IOException {
    JMXConnector retval = null;//from   w ww. j ava 2  s.  c  om

    if (StringUtils.isNotBlank(url)) {
        JMXServiceURL serviceUrl = new JMXServiceURL(url);

        Map map = null;

        if (StringUtils.isNotBlank(username)) {
            map = new HashMap();
            map.put(JMXConnector.CREDENTIALS, new String[] { username, password });
        }

        retval = JMXConnectorFactory.connect(serviceUrl, map);
    }

    return retval;
}