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:org.apache.hadoop.hbase.TestJMXListener.java

@Test
public void testStart() throws Exception {
    JMXConnector connector = JMXConnectorFactory
            .connect(JMXListener.buildJMXServiceURL(connectorPort, connectorPort));

    MBeanServerConnection mb = connector.getMBeanServerConnection();
    String domain = mb.getDefaultDomain();
    Assert.assertTrue("default domain is not correct", !domain.isEmpty());
    connector.close();//from  w w w .j  av a  2  s.  co m

}

From source file:org.eclipse.virgo.ide.runtime.internal.core.command.AbstractJmxServerCommand.java

protected final Object execute(final JmxServerCommandTemplate template) throws TimeoutException {

    Callable<Object> deployOperation = new Callable<Object>() {

        public Object call() throws Exception {
            JMXConnector connector = null;
            try {
                connector = getJmxConnector();
                return template.invokeOperation(connector.getMBeanServerConnection());
            } finally {
                if (connector != null) {
                    try {
                        connector.close();
                    } catch (IOException e) {
                        SpringCore.log(e);
                    }/*from   w  w w.j  a  v a2s .  c  o m*/
                }
            }
        }
    };

    FutureTask<Object> task = new FutureTask<Object>(deployOperation);
    ServerCorePlugin.EXECUTOR.submit(task);

    try {
        return task.get(30, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        // swallow exception here
    } catch (ExecutionException e) {
        // swallow exception here
    }

    return null;
}

From source file:org.novelang.outfit.shell.JmxBeanPool.java

private JmxConnectionBundle getOrCreateConnectionBundle(final JmxKit someJmxKit)
        throws IOException, InterruptedException {
    final JmxConnectionBundle connectionBundle;
    final JmxConnectionBundle maybeConnectionBundle = connectionBundles.get(someJmxKit);
    if (maybeConnectionBundle == null) {
        final JMXConnector jmxConnector = someJmxKit.createJmxConnector(host, port);
        connectionBundle = new JmxConnectionBundle(jmxConnector, jmxConnector.getMBeanServerConnection());
        connectionBundles.put(someJmxKit, connectionBundle);
    } else {//from  ww  w .j a va 2 s .  c o  m
        connectionBundle = maybeConnectionBundle;
    }
    return connectionBundle;
}

From source file:org.wso2.dss.integration.test.jira.issues.CARBON15928JMXDisablingTest.java

private MBeanInfo testMBeanForDatasource() throws Exception {
    Map<String, String[]> env = new HashMap<>();
    String[] credentials = { "admin", "admin" };
    env.put(JMXConnector.CREDENTIALS, credentials);
    try {//  w  w w .  jav  a  2s . c o  m
        String url = "service:jmx:rmi://localhost:12311/jndi/rmi://localhost:11199/jmxrmi";
        JMXServiceURL jmxUrl = new JMXServiceURL(url);
        JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxUrl, env);
        MBeanServerConnection mBeanServer = jmxConnector.getMBeanServerConnection();
        ObjectName mbeanObject = new ObjectName(dataSourceName + ",-1234:type=DataSource");
        MBeanInfo mBeanInfo = mBeanServer.getMBeanInfo(mbeanObject);
        return mBeanInfo;
    } catch (MalformedURLException | MalformedObjectNameException | IntrospectionException
            | ReflectionException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    }
}

From source file:uk.co.gidley.jmxmonitor.services.InternalJmxTest.java

@Test
public void testStartupShutdown()
        throws MalformedObjectNameException, InitialisationException, ConfigurationException {

    MainConfiguration mainConfiguration = mock(MainConfiguration.class);
    RegistryShutdownHub registryShutdownHub = mock(RegistryShutdownHub.class);

    Configuration configuration = new PropertiesConfiguration(
            "src/test/resources/jmxLocalMonitoringTestConfiguration.properties");
    when(mainConfiguration.getConfiguration()).thenReturn(configuration);

    InternalJmx internalJmx = new InternalJmx(mainConfiguration, registryShutdownHub);

    verify(registryShutdownHub).addRegistryShutdownListener(internalJmx);

    // Internal JMX should now be not running

    try {//  w w w.  j  a v a 2  s .  co  m
        ManagementFactory.getPlatformMBeanServer().getObjectInstance(internalJmx.getConnectorServerName());
    } catch (InstanceNotFoundException e) {
        assertThat("Exception should not have thrown", false);
    }

    try {
        JMXServiceURL serviceUrl = new JMXServiceURL(configuration.getString("jmxmonitor.localJmx"));
        JMXConnector jmxc = JMXConnectorFactory.connect(serviceUrl, null);
        MBeanServerConnection mBeanServerConnection = jmxc.getMBeanServerConnection();
        assertThat(mBeanServerConnection, notNullValue());
    } catch (IOException e) {
        assertThat("Exception should not have thrown", false);
    }

    // Fire shutdown anyhow
    internalJmx.registryDidShutdown();

    // Check JMX actually closed
    try {
        ManagementFactory.getPlatformMBeanServer().getObjectInstance(internalJmx.getConnectorServerName());
        assertThat("Exception should have thrown", false);
    } catch (InstanceNotFoundException e) {

    }

    try {
        JMXServiceURL serviceUrl = new JMXServiceURL(configuration.getString("jmxmonitor.localJmx"));
        JMXConnector jmxc = JMXConnectorFactory.connect(serviceUrl, null);
        MBeanServerConnection mBeanServerConnection = jmxc.getMBeanServerConnection();
        assertThat("Exception should have thrown", false);
    } catch (IOException e) {

    }

}

From source file:com.citrix.g2w.webdriver.util.InvokeMBean.java

/**
 * Method to invoke m bean.// ww w  . j  a va2  s.com
 * 
 * @param userName
 *            (user name)
 * @param password
 *            (password)
 * @param rmiHost
 *            (rmi host)
 * @param rmiPort
 *            (rmi port)
 * @param objectName
 *            (object name)
 * @param methodName
 *            (method name)
 * @param params
 *            (array of objects)
 * @param signature
 *            (array of params type)
 * @return mBeanResult 
 *            (list of string containing mbean result)
 */
public List<String> invokeMBean(final String userName, final String password, final String rmiHost,
        final int rmiPort, final String objectName, final String methodName, final Object[] params,
        final String[] signature) {
    List<String> mBeanResult = new ArrayList<String>(2);
    try {
        String[] credentials = { userName, password };

        Map<String, String[]> env = new HashMap<String, String[]>();
        env.put("jmx.remote.credentials", credentials);

        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://" + rmiHost + ":" + rmiPort + "/jndi/rmi://"
                + rmiHost + ":" + rmiPort + "/jmxrmi");

        JMXConnector connector = JMXConnectorFactory.connect(url, env);

        MBeanServerConnection connection = connector.getMBeanServerConnection();
        ObjectName destConfigName = new ObjectName(objectName);

        Object returnValue = connection.invoke(destConfigName, methodName, params, signature);

        if (returnValue != null) {
            if (returnValue instanceof Collection) {
                Collection c = (Collection) returnValue;
                if (CollectionUtils.isNotEmpty(c)) {
                    for (Object val : c) {
                        mBeanResult.add(val.toString());
                    }
                }
            } else {
                mBeanResult.add(returnValue.toString());
            }
        }
        connector.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return mBeanResult;
}

From source file:com.dsf.dbxtract.cdc.AppJournalWindowTest.java

@Test(dependsOnMethods = { "testAppWithJournalWindow" })
public void testInfoStatistics() throws Exception {

    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:5000/jmxrmi");
    JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

    ObjectName mbeanName = new ObjectName("com.dsf.dbxtract:type=InfoMBean");

    TabularDataSupport info = (TabularDataSupport) mbsc.getAttribute(mbeanName, InfoMBean.ATTR_INFO);
    Collection<?> list = info.values();
    boolean hasHandlerEntry = false;
    for (Iterator<?> it = list.iterator(); it.hasNext();) {
        CompositeDataSupport entry = (CompositeDataSupport) it.next();

        if (entry.get("handler").equals(TestWindowHandler.class.getName())) {
            assert (((Long) entry.get("readCount")).longValue() == TEST_SIZE);
            hasHandlerEntry = true;//from  w w w .  ja  v  a 2  s  .  co  m
        }
    }
    assert (hasHandlerEntry);
    jmxc.close();
}

From source file:de.iew.spring.integration.SpringIntegrationJmxTest.java

@Test
public void testJmxClientClassic() throws Exception {
    JMXServiceURL clientURL = new JMXServiceURL(this.serviceUrl);
    Map clientEnv = new HashMap();

    JMXConnector connector = JMXConnectorFactory.connect(clientURL, clientEnv);
    MBeanServerConnection connection = connector.getMBeanServerConnection();

    ObjectName mbeanName = new ObjectName(this.jmxTestServiceObjectName);
    JmxTestService mbeanProxy = JMX.newMBeanProxy(connection, mbeanName, JmxTestService.class, true);

    mbeanProxy.setName("Foo Bar");
    mbeanProxy.sayHello();//from w  w  w . j a  v  a  2 s  .c o m

    String[] hellos = mbeanProxy.getStoredHellos();
    Assert.assertEquals(1, hellos.length);

    mbeanProxy.clearHelloStore();

    hellos = mbeanProxy.getStoredHellos();
    Assert.assertEquals(0, hellos.length);
}

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//  w ww .j a  v 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:eu.itesla_project.online.tools.RunForecastErrorsAnalysisMpiTool.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);/*  w  w  w  .ja  va2  s  .  co m*/
    if (port != null)
        startconfig.setJmxPort(Integer.valueOf(port));
    if (threads != null)
        startconfig.setThreads(Integer.valueOf(threads));

    String analysisId = line.getOptionValue("analysis");
    DateTime baseCaseDate = line.hasOption("base-case-date")
            ? DateTime.parse(line.getOptionValue("base-case-date"))
            : getDefaultParameters().getBaseCaseDate();
    Interval histoInterval = line.hasOption("history-interval")
            ? Interval.parse(line.getOptionValue("history-interval"))
            : getDefaultParameters().getHistoInterval();
    double ir = line.hasOption("ir") ? Double.parseDouble(line.getOptionValue("ir"))
            : getDefaultParameters().getIr();
    int flagPQ = line.hasOption("flagPQ") ? Integer.parseInt(line.getOptionValue("flagPQ"))
            : getDefaultParameters().getFlagPQ();
    int method = line.hasOption("method") ? Integer.parseInt(line.getOptionValue("method"))
            : getDefaultParameters().getMethod();
    Integer nClusters = line.hasOption("nClusters") ? Integer.parseInt(line.getOptionValue("nClusters"))
            : getDefaultParameters().getnClusters();
    double percentileHistorical = line.hasOption("percentileHistorical")
            ? Double.parseDouble(line.getOptionValue("percentileHistorical"))
            : getDefaultParameters().getPercentileHistorical();
    Integer modalityGaussian = line.hasOption("modalityGaussian")
            ? Integer.parseInt(line.getOptionValue("modalityGaussian"))
            : getDefaultParameters().getModalityGaussian();
    Integer outliers = line.hasOption("outliers") ? Integer.parseInt(line.getOptionValue("outliers"))
            : getDefaultParameters().getOutliers();
    Integer conditionalSampling = line.hasOption("conditionalSampling")
            ? Integer.parseInt(line.getOptionValue("conditionalSampling"))
            : getDefaultParameters().getConditionalSampling();
    Integer nSamples = line.hasOption("nSamples") ? Integer.parseInt(line.getOptionValue("nSamples"))
            : getDefaultParameters().getnSamples();
    Set<Country> countries = line.hasOption("countries")
            ? Arrays.stream(line.getOptionValue("countries").split(",")).map(Country::valueOf).collect(
                    Collectors.toSet())
            : getDefaultParameters().getCountries();
    CaseType caseType = line.hasOption("case-type") ? CaseType.valueOf(line.getOptionValue("case-type"))
            : getDefaultParameters().getCaseType();

    ForecastErrorsAnalysisParameters parameters = new ForecastErrorsAnalysisParameters(baseCaseDate,
            histoInterval, analysisId, ir, flagPQ, method, nClusters, percentileHistorical, modalityGaussian,
            outliers, conditionalSampling, nSamples, countries, caseType);

    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);
    String timeHorizonS = "";
    if (line.hasOption("time-horizon")) {
        timeHorizonS = line.getOptionValue("time-horizon");
    }
    application.runFeaAnalysis(startconfig, parameters, timeHorizonS);

}