Example usage for javax.management.remote JMXConnectorFactory connect

List of usage examples for javax.management.remote JMXConnectorFactory connect

Introduction

In this page you can find the example usage for javax.management.remote JMXConnectorFactory connect.

Prototype

public static JMXConnector connect(JMXServiceURL serviceURL, Map<String, ?> environment) throws IOException 

Source Link

Document

Creates a connection to the connector server at the given address.

This method is equivalent to:

 JMXConnector conn = JMXConnectorFactory.newJMXConnector(serviceURL, environment); conn.connect(environment); 

Usage

From source file:org.fabrician.enabler.KarafContainer.java

public synchronized MBeanServerConnection getMBeanServerConnection() throws Exception {
    if (this.mBeanServer == null) {
        Map<String, String[]> environment = new HashMap<String, String[]>();
        String user = getAdminName();
        String pwd = getAdminPassword();
        String jmxurl = getJmxClientUrl();
        String[] credentials = new String[] { user, pwd };
        environment.put(JMXConnector.CREDENTIALS, credentials);
        JMXServiceURL url = null;
        try {/*  w  ww. java 2s  .  co  m*/
            url = new JMXServiceURL(jmxurl);
            getEngineLogger().info("Establishing JMX connection to URL : [" + jmxurl + "]...");
            this.jmxc = JMXConnectorFactory.connect(url, environment);
            this.mBeanServer = jmxc.getMBeanServerConnection();
            getEngineLogger().info("JMX connection established.");
        } catch (Exception ex) {
            getEngineLogger().warning("[" + jmxurl + "] : " + ex.getMessage());
            throw ex;
        }
    }
    return this.mBeanServer;
}

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 {//from   ww  w.j  a  va2s  .c o  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.zenoss.jmx.JmxClient.java

/**
 * Connects to the JMX Agent/*from  www  .  j ava2 s .c  o  m*/
 * 
 * @throws JMXException
 *             if an exception occurs during connection
 */
public void connect() throws JmxException {

    // short-circuit to avoid re-connecting
    if (_connected) {
        return;
    }

    try {
        // honor the authentication credentials
        Map<String, Object> env = new HashMap<String, Object>();
        env.put(JMXConnector.CREDENTIALS, _creds);

        _connector = JMXConnectorFactory.connect(_url, env);
        _server = _connector.getMBeanServerConnection();
    } catch (IOException e) {
        throw new JmxException("Failed to connect to " + _url, e);
    }

    _connected = true;
}

From source file:io.github.albertopires.mjc.JConsoleM.java

private JConsoleM(ServerConfiguration serverConfiguration) throws Exception {
    JMXConnector jmxc = null;/*from  w  ww  .  j a  va2 s. com*/
    if (serverConfiguration.getAuthenticate()) {
        String urlStr = "service:jmx:http-remoting-jmx://" + serverConfiguration.getHost() + ":"
                + serverConfiguration.getPort();
        Map<String, Object> env = new HashMap<String, Object>();
        String[] creds = { serverConfiguration.getUser(), serverConfiguration.getPassword() };
        env.put(JMXConnector.CREDENTIALS, creds);
        jmxc = JMXConnectorFactory.connect(new JMXServiceURL(urlStr), env);
    } else {
        String urlStr = "service:jmx:rmi:///jndi/rmi://" + serverConfiguration.getHost() + ":"
                + serverConfiguration.getPort() + "/jmxrmi";
        //         String urlStr = "service:jmx:remote+http://" + serverConfiguration.getHost() + ":" + serverConfiguration.getPort();
        JMXServiceURL url = new JMXServiceURL(urlStr);
        jmxc = JMXConnectorFactory.connect(url, null);
    }
    mbsc = jmxc.getMBeanServerConnection();
    ncpu = getAvailableProcessors();
}

From source file:io.fabric8.cxf.endpoint.jaxrs.RestJsonSchemaJMXTest.java

private void connectToMBserver() throws IOException {
    jmxServerURL = jmxServerURL == null ? DEFAULT_JMXSERVICE_URL : jmxServerURL;
    JMXServiceURL url = new JMXServiceURL(jmxServerURL);
    JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
    mbsc = jmxc.getMBeanServerConnection();
}

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

public String execute(String hostport) throws Exception {
    Iterator i;//from w  w w.ja v a2  s .c  o  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.wso2.carbon.registry.subscription.test.util.JMXClient.java

/**
 * connect to org.wso2.carbon to invoke different operations
 *
 * @param userName       user name to connect to org.wso2.carbon
 * @param password       password to connect to org.wso2.carbon
 * @param connectionType//from  w ww . ja  v a2s  . co m
 * @param operation
 * @throws Exception
 */
public void connect(String userName, String password, String connectionType, String operation)
        throws Exception {
    try {
        JMXServiceURL url = new JMXServiceURL(
                "service:jmx:rmi://" + NetworkUtils.getLocalHostname() + ":" + RMIServerPort + "/jndi/rmi://"
                        + NetworkUtils.getLocalHostname() + ":" + RMIRegistryPort + "/jmxrmi");
        Hashtable<String, String[]> hashT = new Hashtable<String, String[]>();
        String[] credentials = new String[] { userName, password };
        hashT.put("jmx.remote.credentials", credentials);
        jmxc = JMXConnectorFactory.connect(url, hashT);
        mbsc = jmxc.getMBeanServerConnection();
        nodeAgent = new ObjectName(connectionType);
        mbsc.invoke(nodeAgent, operation, null, null);
    } catch (Exception ex) {
        log.error("infoAdminServiceStub Initialization fail ");
        throw new Exception("infoAdminServiceStub Initialization fail " + ex.getMessage());
    }
}

From source file:org.apache.helix.tools.JmxDumper.java

public JmxDumper(String jmxService, String domain, String beanClassName, String namePattern, int samplePeriod,
        List<String> fields, List<String> operations, String outputfile, int sampleCount) throws Exception {
    _jmxUrl = jmxService;/* w ww.j a  va  2  s  . c o  m*/
    _domain = domain;
    _beanClassName = beanClassName;
    _samplePeriod = samplePeriod;
    _outputFields.addAll(fields);
    _operations.addAll(operations);
    _outputFileName = outputfile;
    _namePattern = namePattern;
    _targetSamples = sampleCount;

    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + _jmxUrl + "/jmxrmi");
    JMXConnector jmxc = JMXConnectorFactory.connect(url, null);

    _mbeanServer = jmxc.getMBeanServerConnection();
    MBeanServerNotificationFilter filter = new MBeanServerNotificationFilter();
    filter.enableAllObjectNames();
    _mbeanServer.addNotificationListener(MBeanServerDelegate.DELEGATE_NAME, this, filter, null);
    init();
    _timer = new Timer(true);
    _timer.scheduleAtFixedRate(new SampleTask(), _samplePeriod, _samplePeriod);
}

From source file:com.tc.management.JMXConnectorProxy.java

private void determineConnector() throws Exception {
    JMXServiceURL url = new JMXServiceURL(getSecureJMXConnectorURL(m_host, m_port));

    if (m_secured) {
        RMIClientSocketFactory csf;
        if (Boolean.getBoolean("tc.ssl.trustAllCerts")) {
            csf = new TSASSLSocketFactory();
        } else {//from  ww  w .j a  v a  2s  .c o m
            csf = new SslRMIClientSocketFactory();
        }
        SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory();
        m_env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf);
        m_env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, ssf);

        // Needed to avoid "non-JRMP server at remote endpoint" error
        m_env.put("com.sun.jndi.rmi.factory.socket", csf);

        m_serviceURL = new JMXServiceURL("service:jmx:rmi://" + m_host + ":" + m_port + "/jndi/rmi://" + m_host
                + ":" + m_port + "/jmxrmi");
        m_connector = JMXConnectorFactory.connect(url, m_env);
    } else {
        try {
            m_connector = JMXConnectorFactory.connect(url, m_env);
            m_serviceURL = url;
        } catch (IOException ioe) {
            if (isConnectException(ioe)) {
                throw ioe;
            }
            if (isAuthenticationException(ioe)) {
                throw new SecurityException("Invalid login name or credentials");
            }
            url = new JMXServiceURL(getJMXConnectorURL(m_host, m_port));
            m_connector = JMXConnectorFactory.connect(url, m_env);
            m_serviceURL = url;
        }
    }
}

From source file:org.wso2.carbon.esb.mediator.test.property.PropertyIntegrationAxis2PropertiesTestCase.java

@Test(groups = { "wso2.esb" }, description = "Send messages using  ConcurrentConsumers "
        + "and MaxConcurrentConsumers Axis2 level properties")
public void maxConcurrentConsumersTest() throws Exception {

    String carbonHome = System.getProperty(ServerConstants.CARBON_HOME);
    String confDir = carbonHome + File.separator + "repository" + File.separator + "conf" + File.separator;

    //enabling jms transport with ActiveMQ
    File originalConfig = new File(
            TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts" + File.separator
                    + "AXIS2" + File.separator + "config" + File.separator + "property_axis2_server.xml");
    File destDir = new File(confDir + "axis2" + File.separator);
    FileUtils.copyFileToDirectory(originalConfig, destDir);

    serverManager.restartGracefully();//from  w w  w.j av a2s.c  o m

    super.init(); // after restart the server instance initialization
    JMXServiceURL url = new JMXServiceURL(
            "service:jmx:rmi://" + context.getDefaultInstance().getHosts().get("default") + ":11311/jndi/rmi://"
                    + context.getDefaultInstance().getHosts().get("default") + ":10199/jmxrmi");

    HashMap<String, String[]> environment = new HashMap<String, String[]>();
    String[] credentials = new String[] { "admin", "admin" };
    environment.put(JMXConnector.CREDENTIALS, credentials);

    MBeanServerConnection mBeanServerConnection = JMXConnectorFactory.connect(url, environment)
            .getMBeanServerConnection();

    int beforeThreadCount = (Integer) mBeanServerConnection
            .getAttribute(new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME), "ThreadCount");

    String queueName = "SimpleStockQuoteService";

    for (int x = 0; x < 200; x++) {
        JMSQueueMessageProducer sender = new JMSQueueMessageProducer(
                JMSBrokerConfigurationProvider.getInstance().getBrokerConfiguration());

        try {
            sender.connect(queueName);
            for (int i = 0; i < 3; i++) {
                sender.pushMessage("<?xml version='1.0' encoding='UTF-8'?>"
                        + "<soapenv:Envelope xmlns:soapenv=\"http://schemas." + "xmlsoap.org/soap/envelope/\""
                        + " xmlns:ser=\"http://services.samples\" xmlns:xsd=\""
                        + "http://services.samples/xsd\">" + "   <soapenv:Header/>" + "   <soapenv:Body>"
                        + "      <ser:placeOrder>" + "         <ser:order>"
                        + "            <xsd:price>100</xsd:price>"
                        + "            <xsd:quantity>2000</xsd:quantity>"
                        + "            <xsd:symbol>JMSTransport</xsd:symbol>" + "         </ser:order>"
                        + "      </ser:placeOrder>" + "   </soapenv:Body>" + "</soapenv:Envelope>");
            }
        } finally {
            sender.disconnect();
        }
    }

    OMElement synapse = esbUtils
            .loadResource("/artifacts/ESB/mediatorconfig/property/" + "ConcurrentConsumers.xml");
    updateESBConfiguration(JMSEndpointManager.setConfigurations(synapse));

    int afterThreadCount = (Integer) mBeanServerConnection
            .getAttribute(new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME), "ThreadCount");

    assertTrue((afterThreadCount - beforeThreadCount) <= 150, "Expected thread count range" + " not met");
}