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:com.stumbleupon.hbaseadmin.JMXQuery.java

public String execute(String hostport) throws Exception {
    Iterator i;//from  ww  w .j a v  a  2s . 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: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:net.timewalker.ffmq4.jmx.rmi.JMXOverRMIAgent.java

private void init() throws JMSException {
    try {//from w  w w.ja  v a 2  s  . co  m
        log.info("Starting JMX agent");

        // Get or create an RMI registry
        if (rmiListenAddr == null || rmiListenAddr.equals("auto"))
            rmiListenAddr = InetAddress.getLocalHost().getHostName();

        // Connector JNDI name
        String jndiName = "jmxconnector-" + agentName;

        try {
            registry = LocateRegistry.getRegistry(rmiListenAddr, jndiRmiPort);
            registry.lookup(jndiName);

            // Remove the old registered connector
            registry.unbind(jndiName);

            log.debug("RMI registry found at " + rmiListenAddr + ":" + jndiRmiPort
                    + " with connector already registered");
        } catch (NotBoundException e) {
            // Registry already exists
            log.debug("RMI registry found at " + rmiListenAddr + ":" + jndiRmiPort);
        } catch (RemoteException e) {
            log.debug("Creating RMI registry at " + rmiListenAddr + ":" + jndiRmiPort);
            RMIServerSocketFactory ssf = new JMXOverRMIServerSocketFactory(10, rmiListenAddr, false);
            registry = LocateRegistry.createRegistry(jndiRmiPort, null, ssf);
        }

        // Get the JVM MBean server
        mBeanServer = ManagementFactory.getPlatformMBeanServer();

        // Service URL
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://" + rmiListenAddr + "/jndi/rmi://"
                + rmiListenAddr + ":" + jndiRmiPort + "/" + jndiName);
        log.info("JMX Service URL : " + url);

        // Create and start the RMIConnectorServer
        Map<String, Object> env = new HashMap<>();
        mBeanServerSocketFactory = new JMXOverRMIServerSocketFactory(10, rmiListenAddr, true);
        env.put(RMIConnectorServer.JNDI_REBIND_ATTRIBUTE, "true");
        //env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, new JMXRMIClientSocketFactory(rmiListenAddr));
        env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, mBeanServerSocketFactory);
        connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mBeanServer);
        connectorServer.start();
    } catch (Exception e) {
        throw new FFMQException("Could not initialize JMX agent", "JMX_ERROR", e);
    }
}

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  ava2  s .  co 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:io.github.albertopires.mjc.JConsoleM.java

private JConsoleM(ServerConfiguration serverConfiguration) throws Exception {
    JMXConnector jmxc = null;//from w ww . java  2s .  c  om
    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:uk.co.gidley.jmxmonitor.services.InternalJmx.java

private void startJmxConnector(Configuration configuration) throws InitialisationException {
    try {//  w ww .  j  a  v  a2 s  .  c  o  m
        String url = configuration.getString(PROPERTY_PREFIX + "localJmx");
        logger.debug("Initialising local JMX server on URL {}", url);
        JMXServiceURL address = new JMXServiceURL(url);
        jmxConnectorServer = JMXConnectorServerFactory.newJMXConnectorServer(address, null, MBEAN_SERVER);

        MBEAN_SERVER.registerMBean(jmxConnectorServer, connectorServerName);
        jmxConnectorServer.start();
    } catch (IOException e) {
        logger.error("{}", e);
        throw new InitialisationException(e);
    } catch (InstanceAlreadyExistsException e) {
        logger.error("{}", e);
        throw new InitialisationException(e);
    } catch (MBeanRegistrationException e) {
        logger.error("{}", e);
        throw new InitialisationException(e);
    } catch (NotCompliantMBeanException e) {
        logger.error("{}", e);
        throw new InitialisationException(e);
    }
}

From source file:org.openadaptor.util.JVMNeutralMBeanServerFactory.java

/**
 * Use reflection to get an MBeanServer. Avoids compile issue where 1.4 jdk doesn't
 * have java.lang.management.ManagementFactory
 *
 * <pre>//from  w w w  .j a  v a2s. c o m
 *
 * Note: For 1.4, an RMI registry may have to be manually started.
 * This may be achieved by something similar to ...
 * RJMX_LIB=<i>oa3_lib</i>
 * JMX_LIB=<i>oa3_lib</i>
 * CP=${RJMXLIB}/jmxremote.jar:${JMXLIB}/jmxri.jar
 * export CLASSPATH=.:$CP ; rmiregistry 51410 &
 *
 * Does <b>not</b> apply to 1.5+
 * </pre>
 * @return MBeanServer instance.
 */
public static MBeanServer getMBeanServer() {
    String jvmVersion = System.getProperties().getProperty("java.version");
    log.info("Getting MBeanServer [for jvm " + jvmVersion + "]");
    boolean isjvm1_4 = jvmVersion.startsWith("1.4.");
    String factory = isjvm1_4 ? FACTORY_1_4 : FACTORY_1_5;
    String method = isjvm1_4 ? METHOD_1_4 : METHOD_1_5;
    if (server == null) {
        server = getMBeanServer(factory, method);
        if (isjvm1_4) {
            //Todo: Add some kind of access mechanism to change the port!
            int port = DEFAULT_RMI_PORT;

            String serviceURLString = "service:jmx:rmi:///jndi/rmi://localhost:" + port + "/server";
            try {
                log.info("starting rmi registry on " + port);
                rmiRegistry = LocateRegistry.createRegistry(port);
                Runtime.getRuntime().addShutdownHook(new Thread() {
                    public void run() {
                    }
                });
            } catch (RemoteException e) {
                log.warn(e);
            }
            JMXServiceURL url;
            try {
                url = new JMXServiceURL(serviceURLString);
                //url = new JMXServiceURL("jmxmp", null, 5555);
                jmxConnectorServer_1_4 = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server);

                // Start the RMI connector server
                log.info("Starting the RMI connector server");
                jmxConnectorServer_1_4.start();
                //Add a shutdownHook to make sure it stops also.
                addJMXShutdownHook();
                //ToDo: Remember to shut this baby down also!
                log.info("RMI connector server successfully started.");
                log.info("JMX clients may use the serviceURL: " + serviceURLString);

                //Start a Html Connection server - disabled for now.
                //It's just being explored.
                //startHtmlConnectorServer();
            } catch (Exception e) {
                log.warn("Failed to get RMI connector server started - " + e);
                e.printStackTrace();
            }
        }
    }
    return server;
}

From source file:org.skfiy.typhon.jmx.BuiltinJmxListener.java

private JMXServiceURL newUrl() {
    try {/*from   w  ww.  j  a v  a2 s.  co  m*/
        return new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi");
    } catch (MalformedURLException ex) {
        throw new IllegalArgumentException(ex);
    }
}

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;//from w  w w .ja  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: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  .  java  2s  .  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");
}