Example usage for javax.management.remote JMXConnector close

List of usage examples for javax.management.remote JMXConnector close

Introduction

In this page you can find the example usage for javax.management.remote JMXConnector close.

Prototype

public void close() throws IOException;

Source Link

Document

Closes the client connection to its server.

Usage

From source file:io.fabric8.test.smoke.JolokiaEndpointTestBase.java

@Test
public void testMXBeanProxy() throws Exception {

    ContainerManager cntManager = ContainerManagerLocator.getContainerManager();
    Container cnt = cntManager.getCurrentContainer();

    ServiceEndpoint sep = cnt.getServiceEndpoint(URLServiceEndpoint.JMX_SERVICE_ENDPOINT_IDENTITY);
    JMXServiceEndpoint jmxEndpoint = sep.adapt(JMXServiceEndpoint.class);
    String serviceURL = jmxEndpoint.getServiceURL();
    Assert.assertNotNull("JMX URL not null", serviceURL);

    // Get the local MBeanServer
    MBeanServer server = ServiceLocator.getRequiredService(MBeanServer.class);
    server.registerMBean(new Simple(), SimpleMXBean.OBJECT_NAME);
    try {//  w ww.ja v a 2 s  .co  m
        String[] userpass = RuntimeType.KARAF == RuntimeType.getRuntimeType() ? karafJmx : otherJmx;
        JMXConnector jmxConnector = jmxEndpoint.getJMXConnector(userpass[0], userpass[1], 200,
                TimeUnit.MILLISECONDS);
        MBeanServerConnection con = jmxConnector.getMBeanServerConnection();
        try {
            SimpleMXBean proxy = ManagementUtils.getMXBeanProxy(con, SimpleMXBean.OBJECT_NAME,
                    SimpleMXBean.class);

            // Simple string echo
            Assert.assertEquals("Hello: Kermit", proxy.echo("Kermit"));

            // Set Bean attribute using CompositeData
            Bean bean = new Bean("Hello", "Foo");
            proxy.setBean(bean);

            // Get Bean attribute using CompositeData
            Assert.assertEquals(bean, proxy.getBean());

            // Simple Bean echo using CompositeData
            Assert.assertEquals(bean, proxy.echoBean(bean));
        } finally {
            jmxConnector.close();
        }
    } finally {
        server.unregisterMBean(SimpleMXBean.OBJECT_NAME);
    }
}

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

/**
 * @param url      : The URL for the JMX server
 * @param userName : The User name for the JMX server
 * @param password : The password for the JMX server
 * @return : The name array of the MBeans which the JMX server. The format of the array is
 *         [Domain name][MBean Canonical name]
 * @throws IOException/* w  w w  . j  a  v  a2 s . c  om*/
 */
public String[][] getMBeans(String url, String userName, String password) throws IOException {

    JMXConnector jmxc = null;

    try {
        jmxc = getJmxConnector(url, userName, password);

        MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

        int count = 0;
        Set<ObjectName> names = new TreeSet<ObjectName>(mbsc.queryNames(null, null));
        String[][] nameArr = new String[names.size()][2];

        for (ObjectName name : names) {
            nameArr[count][0] = name.getDomain();
            nameArr[count][1] = name.getCanonicalName();
            count++;
        }

        return nameArr;

    } catch (MalformedURLException e) {
        log.error(e);
        throw e;
    } catch (IOException e) {
        log.error(e);
        throw e;
    } finally {
        if (jmxc != null) {
            jmxc.close();
        }
    }
}

From source file:org.rhq.plugins.cassandra.CassandraNodeComponent.java

private boolean isStorageServiceReachable() {
    JMXConnector connector = null;
    try {/*from  w ww  . j a v a2 s. c  om*/
        Configuration pluginConfig = getResourceContext().getPluginConfiguration();
        String url = pluginConfig.getSimpleValue("connectorAddress");
        JMXServiceURL serviceURL = new JMXServiceURL(url);
        connector = JMXConnectorFactory.connect(serviceURL, null);

        MBeanServerConnection serverConnection = connector.getMBeanServerConnection();
        ObjectName storageService = new ObjectName("org.apache.cassandra.db:type=StorageService");

        // query an attribute to make sure it is in fact available
        serverConnection.getAttribute(storageService, "NativeTransportRunning");

        return true;
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Failed to make JMX connection to StorageService", e);
        }
        return false;
    } finally {
        if (connector != null) {
            try {
                connector.close();
            } catch (IOException e) {
                if (log.isDebugEnabled()) {
                    log.debug("An error occurred closing the JMX connector", e);
                }
            }
        }
    }
}

From source file:org.talend.esb.monitoring.hq.AbstractEmbeddedServerDetector.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override// w ww. j  a  v  a 2s.  c  o  m
public List getServerResources(final ConfigResponse platformConfig) throws PluginException {

    final List<ServerResource> discoveredServers = super.getServerResources(platformConfig);
    final List<ServerResource> serversToReturn = new ArrayList<ServerResource>();

    for (final ServerResource serverRes : discoveredServers) {
        JMXConnector jmxConnector = null;

        try {
            jmxConnector = MxUtil.getMBeanConnector(serverRes.getProductConfig().toProperties());

            Set<ObjectName> objNames = jmxConnector.getMBeanServerConnection().queryNames(targetDomainPattern,
                    null);

            if (objNames.size() > 0) {

                if (absentDomainPattern != null) {
                    objNames = jmxConnector.getMBeanServerConnection().queryNames(absentDomainPattern, null);

                    if (objNames.size() > 0) {
                        continue;
                    }
                }

                final StringBuilder sb = new StringBuilder();

                sb.append(title);
                sb.append("at");
                sb.append(serverRes.getInstallPath());

                serverRes.setIdentifier(sb.toString());
                serversToReturn.add(serverRes);
            }
        } catch (IOException e) {
            log.debug("Unable to check whether destination MBeanServer contains domain "
                    + targetDomainPattern.toString(), e);
        } finally {
            try {
                if (jmxConnector != null) {
                    jmxConnector.close();
                }
            } catch (IOException e) {
                log.debug("Exception during closing the connection to MBeanServer.", e);
            }
        }
    }

    return serversToReturn;
}

From source file:org.hyperic.hq.plugin.weblogic.WeblogicServiceControlPlugin.java

protected void invokeMethod(ControlPlugin plugin, String objectName, String action, String[] args) {
    log.debug("invoking " + action + " " + MBeanUtil.anyToString(args));
    JMXConnector jmxConnector;
    try {//from   w  w  w  . ja  v  a2  s.co  m
        jmxConnector = WeblogicUtil.getManagedServerConnection(plugin.getConfig().toProperties());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        plugin.setMessage(e.getMessage());
        plugin.setResult(RESULT_FAILURE);
        return;
    }
    try {
        String result = null;
        Object obj = invoke(jmxConnector.getMBeanServerConnection(), objectName, action, args, new String[0]);
        if (obj != null) {
            result = MBeanUtil.anyToString(obj);
        }
        log.debug(objectName + "." + action + "() returned: " + obj);
        plugin.setResult(RESULT_SUCCESS);
        if (result != null) {
            plugin.setMessage(result);
        }
    } catch (PluginException e) {
        log.error(e.getMessage(), e);
        plugin.setMessage(e.getMessage());
        plugin.setResult(RESULT_FAILURE);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        // anything not explicitly thrown by invoke
        // needs to have the full stack trace logged for debugging.
        plugin.setMessage(e.getMessage());
        plugin.setResult(RESULT_FAILURE);
    } finally {
        try {
            jmxConnector.close();
        } catch (IOException e) {
            log.warn("Error closing remote JMX connection", e);
        }
    }
}

From source file:org.opennms.features.jmxconfiggenerator.Starter.java

public void doMain(String[] args) {

    CmdLineParser parser = new CmdLineParser(this);

    parser.setUsageWidth(80);/*  w  w w  . ja  v  a 2s . c  o  m*/

    try {
        parser.parseArgument(args);
        if (jmx && graph) {
            throw new CmdLineException(parser, "jmx and graph is set. Just use one at a time.");
        } else if (!jmx && !graph) {
            throw new CmdLineException(parser, "set jmx or graph.");
        }

        Map<String, String> dictionary = loadInternalDictionary();
        if (dictionaryFile != null) {
            dictionary = loadExternalDictionary(dictionaryFile);
        }

        if (jmx) {
            JMXConnector jmxConnector = null;
            JmxDatacollectionConfiggenerator jmxConfigGenerator = new JmxDatacollectionConfiggenerator();

            JMXServiceURL jmxServiceURL = null;
            if (hostName != null && port != null && outFile != null) {
                jmxServiceURL = jmxConfigGenerator.getJmxServiceURL(jmxmp, hostName, port);
            } else if (url != null && outFile != null) {
                jmxServiceURL = new JMXServiceURL(url);
            } else {
                throw new CmdLineException(parser, "no valid call found.");
            }

            jmxConnector = jmxConfigGenerator.getJmxConnector(username, password, jmxServiceURL);
            MBeanServerConnection mBeanServerConnection = jmxConfigGenerator
                    .createMBeanServerConnection(jmxConnector);
            JmxDatacollectionConfig generateJmxConfigModel = jmxConfigGenerator.generateJmxConfigModel(
                    mBeanServerConnection, serviceName, !skipDefaultVM, runWritableMBeans, dictionary);
            jmxConfigGenerator.writeJmxConfigFile(generateJmxConfigModel, outFile);

            if (jmxConnector != null) {
                logger.debug("closing connection");
                jmxConnector.close();
                logger.debug("connection closed");
            }

            return;

        } else if (graph) {
            if (inputFile != null && outFile != null) {

                JmxConfigReader jmxToSnmpGraphConfigGen = new JmxConfigReader();
                Collection<Report> reports = jmxToSnmpGraphConfigGen
                        .generateReportsByJmxDatacollectionConfig(inputFile);

                GraphConfigGenerator graphConfigGenerator = new GraphConfigGenerator();

                String snmpGraphConfig;
                if (templateFile != null) {
                    snmpGraphConfig = graphConfigGenerator.generateSnmpGraph(reports, templateFile);
                } else {
                    snmpGraphConfig = graphConfigGenerator.generateSnmpGraph(reports);
                }

                System.out.println(snmpGraphConfig);
                FileUtils.writeStringToFile(new File(outFile), snmpGraphConfig, "UTF-8");
                return;
            } else {
                throw new CmdLineException(parser, "no valid call found.");
            }
        } else {
            throw new CmdLineException(parser, "no valid call found.");
        }
    } catch (Exception e) {
        logger.error("An exception occured", e);
        System.err.println("JmxConfigGenerator [options...] arguments...");
        parser.printUsage(System.err);
        System.err.println();
        // System.err.println("  Example: java -jar JmxConfigGenerator" +
        // parser.printExample(ALL));
        System.err.println("Examples:");
        System.err.println(
                " Generation of jmx-datacollection.xml: java -jar JmxConfigGenerator.jar -jmx -host localhost -port 7199 -out JMX-DatacollectionDummy.xml [-service cassandra] [-skipDefaultVM] [-runWritableMBeans] [-dictionary dictionary.properties]");
        System.err.println(
                " Generation of snmp-graph.properties: java -jar JmxConfigGenerator.jar -graph -input test.xml -out test.properies [-template graphTemplate.vm] [-service cassandra]");
    }
}

From source file:com.stumbleupon.hbaseadmin.JMXQuery.java

public String execute(String hostport) throws Exception {
    Iterator i;/*from   w w  w  . ja  v  a  2  s  . co  m*/
    String result = "";
    final JMXServiceURL rmiurl = new JMXServiceURL(
            "service:jmx:rmi://" + hostport + "/jndi/rmi://" + hostport + "/jmxrmi");
    final JMXConnector jmxc = JMXConnectorFactory.connect(rmiurl, getCredentials(password_file));
    try {
        final MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

        final ObjectName objName = new ObjectName(beanName);
        final Set beans = mbsc.queryMBeans(objName, null);

        if (beans.size() == 0) {
            logger.warn(objName.getCanonicalName() + " is not a registered bean");
        } else if (beans.size() == 1) {
            final ObjectInstance instance = (ObjectInstance) beans.iterator().next();
            result = doBean(mbsc, instance, command);
        } else {

            for (i = beans.iterator(); i.hasNext();) {
                final Object obj = i.next();

                if (obj instanceof ObjectName)
                    System.out.println(((ObjectName) obj).getCanonicalName());
                else if (obj instanceof ObjectInstance) {
                    System.out.println(((ObjectInstance) obj).getObjectName().getCanonicalName());
                } else
                    logger.error("Unexpected object type: " + obj);
            }
        }
    } finally {
        jmxc.close();
    }
    return result;
}

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 {/*from w w  w  . ja v  a  2s.c o m*/
        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:io.fabric8.test.smoke.JolokiaEndpointTestBase.java

@Test
public void testMXBeanEndpoint() throws Exception {

    ContainerManager cntManager = ContainerManagerLocator.getContainerManager();
    Container cnt = cntManager.getCurrentContainer();

    ServiceEndpoint sep = cnt.getServiceEndpoint(URLServiceEndpoint.JMX_SERVICE_ENDPOINT_IDENTITY);
    JMXServiceEndpoint jmxEndpoint = sep.adapt(JMXServiceEndpoint.class);
    String serviceURL = jmxEndpoint.getServiceURL();
    Assert.assertNotNull("JMX URL not null", serviceURL);

    // Get the local MBeanServer
    MBeanServer server = ServiceLocator.getRequiredService(MBeanServer.class);
    server.registerMBean(new Simple(), SimpleMXBean.OBJECT_NAME);
    try {//from   w  w  w .j  a  v a2 s.  co m
        String[] userpass = RuntimeType.KARAF == RuntimeType.getRuntimeType() ? karafJmx : otherJmx;
        JMXConnector jmxConnector = jmxEndpoint.getJMXConnector(userpass[0], userpass[1], 200,
                TimeUnit.MILLISECONDS);
        MBeanServerConnection con = jmxConnector.getMBeanServerConnection();
        try {
            // Simple string echo
            Object[] params = new Object[] { "Kermit" };
            String[] signature = new String[] { String.class.getName() };
            Object result = con.invoke(SimpleMXBean.OBJECT_NAME, "echo", params, signature);
            Assert.assertEquals("Hello: Kermit", result);

            // Set Bean attribute using CompositeData
            Bean bean = new Bean("Hello", "Foo");
            CompositeData cdata = OpenTypeGenerator.toCompositeData(bean);
            con.setAttribute(SimpleMXBean.OBJECT_NAME, new Attribute("Bean", cdata));

            // Get Bean attribute using CompositeData
            cdata = (CompositeData) con.getAttribute(SimpleMXBean.OBJECT_NAME, "Bean");
            Assert.assertEquals(bean, OpenTypeGenerator.fromCompositeData(Bean.class, cdata));

            // Simple Bean echo using CompositeData
            params = new Object[] { cdata };
            signature = new String[] { CompositeData.class.getName() };
            cdata = (CompositeData) con.invoke(SimpleMXBean.OBJECT_NAME, "echoBean", params, signature);
            Assert.assertEquals(bean, OpenTypeGenerator.fromCompositeData(Bean.class, cdata));
        } finally {
            jmxConnector.close();
        }
    } finally {
        server.unregisterMBean(SimpleMXBean.OBJECT_NAME);
    }
}

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 {//  ww w.j av  a 2s .co m
        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;
}