Example usage for javax.management.remote JMXConnector getMBeanServerConnection

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

Introduction

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

Prototype

public MBeanServerConnection getMBeanServerConnection() throws IOException;

Source Link

Document

Returns an MBeanServerConnection object representing a remote MBean 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 {//ww w .j  ava 2 s . c om
        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:com.magnet.mmx.server.plugin.mmxmgmt.util.MMXConfigurationTest.java

/**
 * Set the MBean attribute value via a remote JMX Connection and check whether the
 * returned value matches the set value/*ww w  .jav  a  2s .  c om*/
 *
 * @throws Exception
 */
@Test
public void testSetGetMBeanRemote() throws Exception {
    JMXServiceURL jmxServiceUrl = jmxConnectorServer.getAddress();
    JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxServiceUrl);
    MBeanServerConnection mbeanServerConnection = jmxConnector.getMBeanServerConnection();
    ObjectName name = new ObjectName(MMX_MBEAN_OBJECT_NAME);
    testSetGetAttribute(mbeanServerConnection, name);
}

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  va2s .c o  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.opennms.tools.jmxconfiggenerator.jmxconfig.JmxDatacollectionConfiggenerator.java

public MBeanServerConnection createMBeanServerConnection(String hostName, String port, String username,
        String password, Boolean ssl, Boolean jmxmp) throws MalformedURLException, IOException {
    JMXConnector jmxConnector = getJmxConnector(hostName, port, username, password, ssl, jmxmp);
    MBeanServerConnection jmxServerConnection = jmxConnector.getMBeanServerConnection();
    logger.debug("jmxServerConnection: '{}'", jmxServerConnection);
    logger.debug("count: " + jmxServerConnection.getMBeanCount());
    return jmxServerConnection;
    //TODO tak fragen, wie es aussieht mit dem Schlieen der Connection -> erledigt sich wahrscheinlich, da CLI
}

From source file:eu.itesla_project.online.tools.OnlineWorkflowTool.java

@Override
public void run(CommandLine line) throws Exception {

    OnlineWorkflowStartParameters startconfig = OnlineWorkflowStartParameters.loadDefault();

    String host = line.getOptionValue(OnlineWorkflowCommand.HOST);
    String port = line.getOptionValue(OnlineWorkflowCommand.PORT);
    String threads = line.getOptionValue(OnlineWorkflowCommand.THREADS);
    if (host != null)
        startconfig.setJmxHost(host);//  www. j  av a 2  s . co m
    if (port != null)
        startconfig.setJmxPort(Integer.valueOf(port));
    if (threads != null)
        startconfig.setThreads(Integer.valueOf(threads));

    Set<DateTime> baseCasesSet = null;

    OnlineWorkflowParameters params = OnlineWorkflowParameters.loadDefault();
    boolean atLeastOneBaseCaseLineParam = line.hasOption(OnlineWorkflowCommand.CASE_TYPE)
            || line.hasOption(OnlineWorkflowCommand.COUNTRIES)
            || line.hasOption(OnlineWorkflowCommand.BASE_CASE)
            || line.hasOption(OnlineWorkflowCommand.BASECASES_INTERVAL);
    boolean allNeededBaseCaseLineParams = line.hasOption(OnlineWorkflowCommand.CASE_TYPE)
            && line.hasOption(OnlineWorkflowCommand.COUNTRIES)
            && (line.hasOption(OnlineWorkflowCommand.BASE_CASE)
                    || line.hasOption(OnlineWorkflowCommand.BASECASES_INTERVAL));

    if (line.hasOption(OnlineWorkflowCommand.CASE_FILE)) {
        if (atLeastOneBaseCaseLineParam) {
            showHelp("parameter " + OnlineWorkflowCommand.CASE_FILE
                    + " cannot be used together with parameters: " + OnlineWorkflowCommand.CASE_TYPE + ", "
                    + OnlineWorkflowCommand.COUNTRIES + ", " + OnlineWorkflowCommand.BASE_CASE + ", "
                    + OnlineWorkflowCommand.BASECASES_INTERVAL);
            return;
        }
        params.setCaseFile(line.getOptionValue(OnlineWorkflowCommand.CASE_FILE));
    } else {
        if (params.getCaseFile() != null) {
            if (atLeastOneBaseCaseLineParam) {
                if (!allNeededBaseCaseLineParams) {
                    showHelp("to override default parameter " + OnlineWorkflowCommand.CASE_FILE
                            + ", all these parameters must be specified: " + OnlineWorkflowCommand.CASE_TYPE
                            + ", " + OnlineWorkflowCommand.COUNTRIES + ", " + OnlineWorkflowCommand.BASE_CASE
                            + " or " + OnlineWorkflowCommand.BASECASES_INTERVAL);
                    return;
                }
                params.setCaseFile(null);
            }
        }
        if (line.hasOption(OnlineWorkflowCommand.CASE_TYPE))
            params.setCaseType(CaseType.valueOf(line.getOptionValue(OnlineWorkflowCommand.CASE_TYPE)));
        if (line.hasOption(OnlineWorkflowCommand.COUNTRIES)) {
            params.setCountries(Arrays.stream(line.getOptionValue(OnlineWorkflowCommand.COUNTRIES).split(","))
                    .map(Country::valueOf).collect(Collectors.toSet()));
        }
        if (line.hasOption(OnlineWorkflowCommand.BASECASES_INTERVAL)) {
            Interval basecasesInterval = Interval
                    .parse(line.getOptionValue(OnlineWorkflowCommand.BASECASES_INTERVAL));
            OnlineConfig oConfig = OnlineConfig.load();
            CaseRepository caseRepo = oConfig.getCaseRepositoryFactoryClass().newInstance()
                    .create(new LocalComputationManager());
            baseCasesSet = caseRepo.dataAvailable(params.getCaseType(), params.getCountries(),
                    basecasesInterval);
            System.out.println("Base cases available for interval " + basecasesInterval.toString());
            baseCasesSet.forEach(x -> {
                System.out.println(" " + x);
            });
        }
        if (baseCasesSet == null) {
            baseCasesSet = new HashSet<>();
            String base = line.getOptionValue(OnlineWorkflowCommand.BASE_CASE);
            if (base != null) {
                baseCasesSet.add(DateTime.parse(base));
            } else {
                baseCasesSet.add(params.getBaseCaseDate());
            }
        }
    }

    String histo = line.getOptionValue(OnlineWorkflowCommand.HISTODB_INTERVAL);
    if (histo != null)
        params.setHistoInterval(Interval.parse(histo));

    String states = line.getOptionValue(OnlineWorkflowCommand.STATES);
    if (states != null)
        params.setStates(Integer.parseInt(states));

    String timeHorizon = line.getOptionValue(OnlineWorkflowCommand.TIME_HORIZON);
    if (timeHorizon != null)
        params.setTimeHorizon(TimeHorizon.fromName(timeHorizon));

    String workflowid = line.getOptionValue(OnlineWorkflowCommand.WORKFLOW_ID);
    if (workflowid != null)
        params.setOfflineWorkflowId(workflowid);

    String feAnalysisId = line.getOptionValue(OnlineWorkflowCommand.FEANALYSIS_ID);
    if (feAnalysisId != null)
        params.setFeAnalysisId(feAnalysisId);

    String rulesPurity = line.getOptionValue(OnlineWorkflowCommand.RULES_PURITY);
    if (rulesPurity != null)
        params.setRulesPurityThreshold(Double.parseDouble(rulesPurity));

    if (line.hasOption(OnlineWorkflowCommand.STORE_STATES))
        params.setStoreStates(true);

    if (line.hasOption(OnlineWorkflowCommand.ANALYSE_BASECASE))
        params.setAnalyseBasecase(true);

    if (line.hasOption(OnlineWorkflowCommand.VALIDATION)) {
        params.setValidation(true);
        params.setStoreStates(true); // if validation then store states
        params.setAnalyseBasecase(true); // if validation then analyze base case
    }

    Set<SecurityIndexType> securityIndexes = null;
    if (line.hasOption(OnlineWorkflowCommand.SECURITY_INDEXES)) {
        if (!"ALL".equals(line.getOptionValue(OnlineWorkflowCommand.SECURITY_INDEXES)))
            securityIndexes = Arrays
                    .stream(line.getOptionValue(OnlineWorkflowCommand.SECURITY_INDEXES).split(","))
                    .map(SecurityIndexType::valueOf).collect(Collectors.toSet());
        params.setSecurityIndexes(securityIndexes);
    }

    if (line.hasOption(OnlineWorkflowCommand.MERGE_OPTIMIZED))
        params.setMergeOptimized(true);

    String limitReduction = line.getOptionValue(OnlineWorkflowCommand.LIMIT_REDUCTION);
    if (limitReduction != null)
        params.setLimitReduction(Float.parseFloat(limitReduction));

    if (line.hasOption(OnlineWorkflowCommand.HANDLE_VIOLATION_IN_N)) {
        params.setHandleViolationsInN(true);
        params.setAnalyseBasecase(true); // if I need to handle violations in N, I need to analyze base case
    }

    String constraintMargin = line.getOptionValue(OnlineWorkflowCommand.CONSTRAINT_MARGIN);
    if (constraintMargin != null)
        params.setConstraintMargin(Float.parseFloat(constraintMargin));

    String urlString = "service:jmx:rmi:///jndi/rmi://" + startconfig.getJmxHost() + ":"
            + startconfig.getJmxPort() + "/jmxrmi";

    JMXServiceURL serviceURL = new JMXServiceURL(urlString);
    Map<String, String> jmxEnv = new HashMap<>();
    JMXConnector connector = JMXConnectorFactory.connect(serviceURL, jmxEnv);
    MBeanServerConnection mbsc = connector.getMBeanServerConnection();

    ObjectName name = new ObjectName(LocalOnlineApplicationMBean.BEAN_NAME);
    LocalOnlineApplicationMBean application = MBeanServerInvocationHandler.newProxyInstance(mbsc, name,
            LocalOnlineApplicationMBean.class, false);

    if (line.hasOption(OnlineWorkflowCommand.START_CMD)) {
        if (params.getCaseFile() != null) {
            System.out.println("starting Online Workflow, caseFile " + params.getCaseFile());
            String workflowId = application.startWorkflow(startconfig, params);
            System.out.println("workflowId=" + workflowId);

        } else {
            for (DateTime basecase : baseCasesSet) {
                params.setBaseCaseDate(basecase);
                System.out.println("starting Online Workflow, basecase " + basecase.toString());
                String workflowId = application.startWorkflow(startconfig, params);
                System.out.println("workflowId=" + workflowId);
            }
        }
    } else if (line.hasOption(OnlineWorkflowCommand.SHUTDOWN_CMD)) {
        application.shutdown();
    } else {
        showHelp("");
    }

}

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

public MBeanServerConnection createMBeanServerConnection(String hostName, String port, String username,
        String password, Boolean ssl, Boolean jmxmp) throws MalformedURLException, IOException {
    JMXConnector jmxConnector = getJmxConnector(hostName, port, username, password, ssl, jmxmp);
    MBeanServerConnection jmxServerConnection = jmxConnector.getMBeanServerConnection();
    logger.debug("jmxServerConnection: '{}'", jmxServerConnection);
    logger.debug("count: " + jmxServerConnection.getMBeanCount());
    return jmxServerConnection;
}

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);// www  . ja va  2 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:net.sf.ehcache.management.ManagementServiceTest.java

/**
 * Creates an RMI JMXConnectorServer, connects to it and demonstrates what attributes are traversable.
 * The answer is not all./*www  . j  a  v a2  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:com.lmig.cf.metrics.opsmetrics.OpsMetrics.java

private <T> T execute(JmxTemplate<T> template) throws OpsMetricsException {
    LOG.debug("Connecting to {}:{}", host, port);
    JMXConnector connector = null;
    try {//from w  ww .ja  v  a 2  s .c  o m
        JMXServiceURL address = new JMXServiceURL(
                "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi");
        HashMap<String, String[]> env = getCredentials();
        connector = JMXConnectorFactory.connect(address, env);
        MBeanServerConnection mbs = connector.getMBeanServerConnection();
        return template.execute(mbs);
    } catch (Exception e) {
        LOG.error("Unabled to execute JMX command", e);
        throw new OpsMetricsException(e);
    } finally {
        close(connector);
    }
}

From source file:org.apache.hadoop.hdfs.tools.JMXGet.java

/**
 * @throws Exception// w ww. j av  a 2 s.c  o m
 *     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);
    }

}