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: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//  w ww.  j  av  a2 s.  c o  m
 * @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.rhq.plugins.jmx.JMXDiscoveryComponent.java

protected DiscoveredResourceDetails discoverResourceDetails(ResourceDiscoveryContext context,
        ProcessInfo process) {/*  w ww. java  2  s  .com*/
    Integer jmxRemotingPort = getJmxRemotingPort(process);
    JMXServiceURL jmxServiceURL = null;
    if (jmxRemotingPort != null) {
        // Use JMX Remoting when possible, since it doesn't require the RHQ Agent to have OS-level permissions to
        // communicate with the remote JVM via IPC.
        try {
            jmxServiceURL = new JMXServiceURL(
                    "service:jmx:rmi:///jndi/rmi://127.0.0.1:" + jmxRemotingPort + "/jmxrmi");
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    } else {
        // If JMX Remoting is not enabled, it's required that a Resource key is explicitly specified via the org.rhq.resourceKey sysprop.
        String keyString = getSystemPropertyValue(process, SYSPROP_RHQ_RESOURCE_KEY);
        if (keyString != null && !keyString.equals("")) {
            // Start up a JMX agent within the JVM via the Sun Attach API, and return a URL that can be used to connect
            // to that agent.
            // Note, this will only work if the remote JVM is Java 6 or later, and maybe some 64 bit Java 5 - see
            // JBNADM-3332. Also, the RHQ Agent will have to be running on a JDK, not a JRE, so that we can access
            // the JDK's tools.jar, which contains the Sun JVM Attach API classes.
            jmxServiceURL = JvmUtility.extractJMXServiceURL(process);
            if (jmxServiceURL == null) {
                return null;
            }
        }
    }
    log.debug("JMX service URL for java process [" + process + "] is [" + jmxServiceURL + "].");

    return buildResourceDetails(context, process, jmxServiceURL, jmxRemotingPort);
}

From source file:com.webobjects.monitor.wotaskd.Application.java

/**
 * ============================================================================================
 *                  Methods Added for Enabling JMX in Wotaskd
 * ============================================================================================
 * This methods sets up this application for remote monitoring. This method creates a new 
 * connector server and associates it with the MBean Server. The server is started by calling
 * the start() method. The connector server listens for the client connection requests and
 * creates a connection for each one.// ww  w  .  ja  v  a 2  s.c o  m
 */
public void setupRemoteMonitoring() {
    if (_jmxPort != null) {
        // Create an RMI connector and start it
        try {
            // Get the port difference to use when creating our new jmx listener
            int intWotaskdJmxPort = Integer.parseInt(_jmxPort);

            // Set up the Password and Access file
            HashMap<String, String> envPwd = new HashMap<String, String>();
            envPwd.put("jmx.remote.x.password.file", _jmxPasswordFile);
            envPwd.put("jmx.remote.x.access.file", _jmxAccessFile);

            // setup our listener
            java.rmi.registry.LocateRegistry.createRegistry(intWotaskdJmxPort);
            JMXServiceURL jsUrl = new JMXServiceURL(
                    "service:jmx:rmi:///jndi/rmi://" + host() + ":" + intWotaskdJmxPort + "/jmxrmi");
            NSLog.debug.appendln("Setting up monitoring on url : " + jsUrl);

            // Create an RMI Connector Server
            JMXConnectorServer jmxCS = JMXConnectorServerFactory.newJMXConnectorServer(jsUrl, envPwd,
                    getMBeanServer());

            jmxCS.start();
        } catch (Exception anException) {
            NSLog.err.appendln("Error starting remote monitoring: " + anException);
        }
    }
}

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

private static MBeanServerConnection getMBeanServerConnection() throws Exception {
    String severDir = null;//from  w ww.  j  a v  a  2s  .  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.
 * /*  w  w  w . jav a  2s  .  c  o m*/
 * @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.apache.geode.management.internal.ManagementAgent.java

/**
 * http://docs.oracle.com/javase/6/docs/technotes/guides/management/agent.html #gdfvq
 * https://blogs.oracle.com/jmxetc/entry/java_5_premain_rmi_connectors
 * https://blogs.oracle.com/jmxetc/entry/building_a_remotely_stoppable_connector
 * https://blogs.oracle.com/jmxetc/entry/jmx_connecting_through_firewalls_using
 * https://blogs.oracle.com/jmxetc/entry/java_5_premain_rmi_connectors
 */// www  .j ava2 s.  c  om
private void configureAndStart() throws IOException {
    // get the port for RMI Registry and RMI Connector Server
    final int port = this.config.getJmxManagerPort();
    final String hostname;
    final InetAddress bindAddr;
    if (StringUtils.isBlank(this.config.getJmxManagerBindAddress())) {
        hostname = SocketCreator.getLocalHost().getHostName();
        bindAddr = null;
    } else {
        hostname = this.config.getJmxManagerBindAddress();
        bindAddr = InetAddress.getByName(hostname);
    }

    String jmxManagerHostnameForClients = this.config.getJmxManagerHostnameForClients();
    if (StringUtils.isNotBlank(jmxManagerHostnameForClients)) {
        System.setProperty("java.rmi.server.hostname", jmxManagerHostnameForClients);
    }

    final SocketCreator socketCreator = SocketCreatorFactory
            .getSocketCreatorForComponent(SecurableCommunicationChannel.JMX);

    final boolean ssl = socketCreator.useSSL();

    if (logger.isDebugEnabled()) {
        logger.debug("Starting jmx manager agent on port {}{}", port,
                (bindAddr != null ? (" bound to " + bindAddr) : "") + (ssl ? " using SSL" : ""));
    }
    RMIClientSocketFactory rmiClientSocketFactory = ssl ? new SslRMIClientSocketFactory() : null;
    RMIServerSocketFactory rmiServerSocketFactory = new GemFireRMIServerSocketFactory(socketCreator, bindAddr);

    // Following is done to prevent rmi causing stop the world gcs
    System.setProperty("sun.rmi.dgc.server.gcInterval", Long.toString(Long.MAX_VALUE - 1));

    // Create the RMI Registry using the SSL socket factories above.
    // In order to use a single port, we must use these factories
    // everywhere, or nowhere. Since we want to use them in the JMX
    // RMI Connector server, we must also use them in the RMI Registry.
    // Otherwise, we wouldn't be able to use a single port.

    // Start an RMI registry on port <port>.
    registry = LocateRegistry.createRegistry(port, rmiClientSocketFactory, rmiServerSocketFactory);

    // Retrieve the PlatformMBeanServer.
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

    // Environment map. why is this declared as HashMap?
    final HashMap<String, Object> env = new HashMap<>();

    // Manually creates and binds a JMX RMI Connector Server stub with the
    // registry created above: the port we pass here is the port that can
    // be specified in "service:jmx:rmi://"+hostname+":"+port - where the
    // RMI server stub and connection objects will be exported.
    // Here we choose to use the same port as was specified for the
    // RMI Registry. We can do so because we're using \*the same\* client
    // and server socket factories, for the registry itself \*and\* for this
    // object.
    final RMIServerImpl stub = new RMIJRMPServerImpl(port, rmiClientSocketFactory, rmiServerSocketFactory, env);

    // Create an RMI connector server.
    //
    // As specified in the JMXServiceURL the RMIServer stub will be
    // registered in the RMI registry running in the local host on
    // port <port> with the name "jmxrmi". This is the same name the
    // out-of-the-box management agent uses to register the RMIServer
    // stub too.
    //
    // The port specified in "service:jmx:rmi://"+hostname+":"+port
    // is the second port, where RMI connection objects will be exported.
    // Here we use the same port as that we choose for the RMI registry.
    // The port for the RMI registry is specified in the second part
    // of the URL, in "rmi://"+hostname+":"+port
    //
    // We construct a JMXServiceURL corresponding to what we have done
    // for our stub...
    final JMXServiceURL url = new JMXServiceURL(
            "service:jmx:rmi://" + hostname + ":" + port + "/jndi/rmi://" + hostname + ":" + port + "/jmxrmi");

    // Create an RMI connector server with the JMXServiceURL
    //
    // JDK 1.5 cannot use JMXConnectorServerFactory because of
    // http://bugs.sun.com/view_bug.do?bug_id=5107423
    // but we're using JDK 1.6
    jmxConnectorServer = new RMIConnectorServer(new JMXServiceURL("rmi", hostname, port), env, stub, mbs) {
        @Override
        public JMXServiceURL getAddress() {
            return url;
        }

        @Override
        public synchronized void start() throws IOException {
            try {
                registry.bind("jmxrmi", stub);
            } catch (AlreadyBoundException x) {
                throw new IOException(x.getMessage(), x);
            }
            super.start();
        }
    };

    if (securityService.isIntegratedSecurity()) {
        shiroAuthenticator = new JMXShiroAuthenticator(this.securityService);
        env.put(JMXConnectorServer.AUTHENTICATOR, shiroAuthenticator);
        jmxConnectorServer.addNotificationListener(shiroAuthenticator, null,
                jmxConnectorServer.getAttributes());
        // always going to assume authorization is needed as well, if no custom AccessControl, then
        // the CustomAuthRealm
        // should take care of that
        MBeanServerWrapper mBeanServerWrapper = new MBeanServerWrapper(this.securityService);
        jmxConnectorServer.setMBeanServerForwarder(mBeanServerWrapper);
        registerAccessControlMBean();
    } else {
        /* Disable the old authenticator mechanism */
        String pwFile = this.config.getJmxManagerPasswordFile();
        if (pwFile != null && pwFile.length() > 0) {
            env.put("jmx.remote.x.password.file", pwFile);
        }

        String accessFile = this.config.getJmxManagerAccessFile();
        if (accessFile != null && accessFile.length() > 0) {
            // Rewire the mbs hierarchy to set accessController
            ReadOpFileAccessController controller = new ReadOpFileAccessController(accessFile);
            controller.setMBeanServer(mbs);
        }
    }

    jmxConnectorServer.start();
    if (logger.isDebugEnabled()) {
        logger.debug("Finished starting jmx manager agent.");
    }
}

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

private static MBeanServerConnection getMBeanServerConnection() throws Exception {
    String severDir = null;/*ww w .ja  v  a 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-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.betfair.testing.utils.cougar.helpers.CougarHelpers.java

public JMXConnector createJMXConnector(String id)
        throws IOException, AgentLoadException, AgentInitializationException, AttachNotSupportedException {

    // attach to the target application
    VirtualMachine vm = VirtualMachine.attach(id);

    // get the connector address
    String connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);

    // no connector address, so we start the JMX agent
    if (connectorAddress == null) {
        String agent = vm.getSystemProperties().getProperty("java.home") + File.separator + "lib"
                + File.separator + "management-agent.jar";
        vm.loadAgent(agent);/*from  ww  w. ja v a  2 s  .c o m*/

        // agent is started, get the connector address
        connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
    }

    // establish connection to connector server
    JMXServiceURL url = new JMXServiceURL(connectorAddress);
    return JMXConnectorFactory.connect(url);
}

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

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

        @Override/*from   w  w  w.j  a  v a2  s.  co m*/
        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 {/*from   ww w.j  a v a  2  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;
}