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.rhq.cassandra.ClusterInitService.java

public boolean isNativeTransportRunning(String storageNode, int jmxPort) throws Exception {
    Boolean nativeTransportRunning = false;
    String url = getJMXConnectionURL(storageNode, jmxPort);
    JMXServiceURL serviceURL = new JMXServiceURL(url);
    Map<String, String> env = new HashMap<String, String>();
    JMXConnector connector = null;

    try {//from w ww  .ja  v a  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 = "NativeTransportRunning";
        try {
            nativeTransportRunning = (Boolean) 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 nativeTransportRunning;
}

From source file:net.sf.ehcache.management.ManagementServiceTest.java

/**
 * Creates an RMI JMXConnectorServer, connects to it and demonstrates what attributes are traversable.
 * The answer is not all.//from  w ww.j ava2  s.c  o  m
 *
 * Note that this test creates a Registry which will keep running until the JVM Exists. There
 * is no way to stop it but it should do no harm.
 *
 *
 */
public void testJMXConnectorServer() throws Exception {

    ManagementService.registerMBeans(manager, mBeanServer, true, true, true, true);

    LocateRegistry.createRegistry(55000);
    String serverUrl = "service:jmx:rmi:///jndi/rmi://localhost:55000/server";
    JMXServiceURL url = new JMXServiceURL(serverUrl);
    JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mBeanServer);
    cs.start();
    JMXConnector connector = cs.toJMXConnector(null);
    connector.connect(null);
    MBeanServerConnection connection = connector.getMBeanServerConnection();
    assertEquals(OBJECTS_IN_TEST_EHCACHE,
            connection.queryNames(new ObjectName("net.sf.ehcache:*"), null).size());

    Ehcache ehcache = manager.getCache("sampleCache1");

    ehcache.put(new Element("key1", "value1"));
    ehcache.put(new Element("key2", "value1"));
    assertNotNull(ehcache.get("key1"));
    assertNotNull(ehcache.get("key2"));

    //Test CacheManager
    //not all attributes are accessible due to serializability constraints
    //traverseMBeanAttributes(connection, "CacheManager");

    //Test Cache
    //not all attributes are accessible due to serializability constraints
    //traverseMBeanAttributes(connection, "Cache");

    //Test CacheStatistics
    traverseMBeanAttributes(connection, "CacheStatistics");

    //Test CacheConfiguration
    traverseMBeanAttributes(connection, "CacheConfiguration");

    cs.stop();
}

From source file:org.lsc.jmx.LscAgent.java

/**
 * Bind to the JMX Server /* ww  w . j av a 2 s. co m*/
 */
public boolean jmxBind() {
    try {
        String sUrl = "service:jmx:rmi:///jndi/rmi://" + hostname + ":" + port + "/jmxrmi";
        LOGGER.info("Connecting to remote engine on : " + sUrl);
        url = new JMXServiceURL(sUrl);
        jmxC = new RMIConnector(url, null);
        jmxC.connect();
        jmxc = jmxC.getMBeanServerConnection();
        ObjectName lscServerName = new ObjectName("org.lsc.jmx:type=LscServer");
        lscServer = JMX.newMXBeanProxy(jmxc, lscServerName, LscServer.class, true);
        return true;
    } catch (MalformedObjectNameException e) {
        LOGGER.error(e.toString(), e);
    } catch (NullPointerException e) {
        LOGGER.error(e.toString(), e);
    } catch (MalformedURLException e) {
        LOGGER.error(e.toString(), e);
    } catch (IOException e) {
        LOGGER.error(e.toString(), e);
    }
    return false;
}

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 . j a v  a2s.c  om*/

        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//from  w w  w  .  jav  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.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.apache.geode.internal.process.MBeanProcessController.java

/**
 * Uses the Attach API to connect to the local process and ensures that it has loaded the JMX
 * management agent. The JMXServiceURL identifying the local connector address for the JMX agent
 * in the process is returned.//from  www . j  av a  2  s . c  om
 * 
 * @return the address of the JMX API connector server for connecting to the local process
 * 
 * @throws AttachNotSupportedException if unable to use the Attach API to connect to the process
 * @throws IOException if the JDK management agent cannot be found and loaded
 */
private JMXServiceURL getJMXServiceURL() throws AttachNotSupportedException, IOException {
    String connectorAddress;
    VirtualMachine vm = VirtualMachine.attach(String.valueOf(pid));
    try {
        Properties agentProps = vm.getAgentProperties();
        connectorAddress = agentProps.getProperty(PROPERTY_LOCAL_CONNECTOR_ADDRESS);

        if (connectorAddress == null) {
            // need to load the management-agent and get the address

            String javaHome = vm.getSystemProperties().getProperty("java.home");

            // assume java.home is JDK and look in JRE for agent
            String managementAgentPath = javaHome + File.separator + "jre" + File.separator + "lib"
                    + File.separator + "management-agent.jar";
            File managementAgent = new File(managementAgentPath);
            if (!managementAgent.exists()) {
                // assume java.home is JRE and look in lib for agent
                managementAgentPath = javaHome + File.separator + "lib" + File.separator
                        + "management-agent.jar";
                managementAgent = new File(managementAgentPath);
                if (!managementAgent.exists()) {
                    throw new IOException("JDK management agent not found");
                }
            }

            // attempt to load the management agent
            managementAgentPath = managementAgent.getCanonicalPath();
            try {
                vm.loadAgent(managementAgentPath, "com.sun.management.jmxremote");
            } catch (AgentLoadException | AgentInitializationException e) {
                throw new IOException(e);
            }

            // get the connector address
            agentProps = vm.getAgentProperties();
            connectorAddress = agentProps.getProperty(PROPERTY_LOCAL_CONNECTOR_ADDRESS);
        }
    } finally {
        vm.detach();
    }

    if (connectorAddress == null) {
        // should never reach here
        throw new IOException("Failed to find address to attach to process");
    }

    return new JMXServiceURL(connectorAddress);
}

From source file:org.opennms.tools.jmxconfiggenerator.jmxconfig.JmxDatacollectionConfiggenerator.java

/**
 * determines the jmxServiceUrl depending on jmxmp.
 * @param jmxmp// ww w.  j a v a  2  s  .  co  m
 * @param hostName
 * @param port
 * @return
 * @throws MalformedURLException 
 */
public JMXServiceURL getJmxServiceURL(Boolean jmxmp, String hostName, String port)
        throws MalformedURLException {
    if (jmxmp)
        return new JMXServiceURL("service:jmx:jmxmp://" + hostName + ":" + port);
    return new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + hostName + ":" + port + "/jmxrmi");
}

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);//  w  w  w  . ja va2  s .c  o  m
    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:com.googlecode.jmxtrans.model.Server.java

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