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.adaptris.core.jmx.JmxConnection.java

private MBeanServerConnection createConnection() throws IOException, AdaptrisSecurityException {
    MBeanServerConnection result = null;
    if (!isBlank(getJmxServiceUrl())) {
        Map env = KeyValuePairBag.asMap(getJmxProperties());
        if (!isBlank(getUsername())) {
            if (!env.containsKey(JMX_REMOTE_PROFILES)) {
                env.put(JMX_REMOTE_PROFILES, SASL_PLAIN);
            }//from  w  w w .  j ava 2  s.  com
            env.put(JMXConnector.CREDENTIALS,
                    new String[] { getUsername(), Password.decode(ExternalResolver.resolve(getPassword())) });
        }
        connector = JMXConnectorFactory.connect(new JMXServiceURL(getJmxServiceUrl()),
                env.size() == 0 ? null : env);
        result = connector.getMBeanServerConnection();
    } else {
        result = JmxHelper.findMBeanServer();
    }
    return result;
}

From source file:org.chorusbdd.chorus.tools.webagent.JmxManagementServerExporter.java

public void startServer() throws Exception {

    // Ensure cryptographically strong random number generator used
    // to choose the object number - see java.rmi.server.ObjID
    ///* w w  w  .ja  v  a2 s .  c om*/
    //System.setProperty("java.rmi.server.randomIDs", "true");

    // Start an RMI registry on port 3000.
    //
    if (!registriesCreated.contains(port)) {
        log.info("Creating RMI registry on port " + port);
        LocateRegistry.createRegistry(port);
        registriesCreated.add(port);
    } else {
        //there's no way to shut it dnwn? So if we run a sequence of tests we clean up by unexporting the
        //listener object, and have to reuse the registry instance
        log.info("RMI registry was already running on port " + port);
    }

    // Retrieve the PlatformMBeanServer.
    //
    log.info(usePlatformMBeanServer ? "Using Platform MBean Server" : "Creating the MBean server");
    mBeanServer = usePlatformMBeanServer ? ManagementFactory.getPlatformMBeanServer()
            : MBeanServerFactory.createMBeanServer();

    // Environment map.
    //
    log.info("Initialize the environment map");
    HashMap<String, Object> env = new HashMap<String, Object>();

    // Provide SSL-based RMI socket factories.
    //
    // The protocol and cipher suites to be enabled will be the ones
    // defined by the default JSSE implementation and only server
    // authentication will be required.
    //
    //SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory();
    //SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory();
    //env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf);
    //env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, ssf);

    // Provide the password file used by the connector server to
    // perform user authentication. The password file is a properties
    // based text file specifying username/password pairs.
    //
    //env.put("jmx.remote.x.password.file", "password.properties");

    // Provide the access level file used by the connector server to
    // perform user authorization. The access level file is a properties
    // based text file specifying username/access level pairs where
    // access level is either "readonly" or "readwrite" access to the
    // MBeanServer operations.
    //
    //env.put("jmx.remote.x.access.file", "access.properties");

    // Create an RMI connector server.
    //
    // As specified in the JMXServiceURL the RMIServer stub will be
    // registered in the RMI registry running in the local host on
    // port 3000 with the name "jmxrmi". This is the same name the
    // out-of-the-box management agent uses to register the RMIServer
    // stub too.
    //
    log.info("Create an RMI connector server");
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:" + port + "/jmxrmi");
    jmxConnectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mBeanServer);

    // Start the RMI connector server.
    //
    log.info("Start the JMX connector server on port " + port);
    jmxConnectorServer.start();
}

From source file:org.fluentd.jvmwatcher.proxy.JvmClientProxy.java

/**
 * @return/*w w w. j  a  va2 s .  c  om*/
 */
public boolean connect() {
    if (this.localJvmInfo_ == null) {
        return false;
    }

    // connect the JVM server
    if (this.localJvmInfo_.isManageable() != true) {
        try {
            // get JVM Agent address
            this.localJvmInfo_.startManagementAgent();
        } catch (IOException ex) {
            log.error("startManagementAgent error.", ex);
            return false;
        } catch (Exception ex) {
            log.error("startManagementAgent error.", ex);
            return false;
        }
    }

    // connect JVM MBean Server 
    try {
        if (this.jmxUrl_ == null) {
            this.jmxUrl_ = new JMXServiceURL(this.localJvmInfo_.getAddress());
            this.jmxc_ = JMXConnectorFactory.connect(jmxUrl_, null);
            this.server_ = this.jmxc_.getMBeanServerConnection();
        }
    } catch (MalformedURLException ex) {
        log.error(" connect JVM MBean Server error.", ex);
        return false;
    } catch (IOException ex) {
        log.error(" connect JVM MBean Server error.", ex);
        return false;
    } catch (Exception ex) {
        log.error(" connect JVM MBean Server error.", ex);
        return false;
    }

    // this client have successfully connected to the JVM server.
    this.isDeadServer_ = false;

    try {
        ObjectName objName = new ObjectName(THREAD_MXBEAN_NAME);
        this.hasPlatformMXBeans_ = this.server_.isRegistered(objName);
        this.hasHotSpotDiagnosticMXBean_ = this.server_
                .isRegistered(new ObjectName(HOTSPOT_DIAGNOSTIC_MXBEAN_NAME));
        // check if it has 6.0 new APIs
        if (this.hasPlatformMXBeans_ = true) {
            MBeanOperationInfo[] mopis = this.server_.getMBeanInfo(objName).getOperations();
            // look for findDeadlockedThreads operations;
            for (MBeanOperationInfo op : mopis) {
                if (op.getName().equals("findDeadlockedThreads")) {
                    this.supportsLockUsage_ = true;
                    break;
                }
            }

            objName = new ObjectName(COMPILATION_MXBEAN_NAME);
            this.hasCompilationMXBean_ = this.server_.isRegistered(objName);
        }

        if (this.hasPlatformMXBeans_ == true) {
            // WORKAROUND for bug 5056632
            // Check if the access role is correct by getting a RuntimeMXBean
            getRuntimeMXBean();
        }
    } catch (MalformedObjectNameException ex) {
        log.error("connect error.", ex);
        return false;
    } catch (IntrospectionException ex) {
        log.error("connect error.", ex);
        return false;
    } catch (InstanceNotFoundException ex) {
        log.error("connect error.", ex);
        return false;
    } catch (ReflectionException ex) {
        log.error("connect error.", ex);
        return false;
    } catch (IOException ex) {
        log.error("connect error.", ex);
        return false;
    } catch (Exception ex) {
        log.error("connect error.", ex);
        return false;
    }

    // connect success.
    this.isConnect_ = true;

    return true;
}

From source file:uk.co.gidley.jmxmonitor.monitoring.MonitoringGroup.java

/**
 * Initialise the monitor. If possible we start the JMX connection now. If not we create a placeholder.
 *
 * @param monitorUrlKey//from  w  w w.j  a va2s .  co m
 * @param monitorsConfiguration
 * @throws MalformedObjectNameException
 * @throws MalformedURLException
 */
private void initialiseMonitorUrl(String monitorUrlKey, CompositeConfiguration monitorsConfiguration)
        throws MalformedObjectNameException, MalformedURLException {
    logger.debug("Initialising Monitor Connection {}", monitorUrlKey);

    String url = monitorsConfiguration.getString(ThreadManager.PROPERTY_PREFIX + monitorUrlKey + URL);
    try {
        // Create JMX connection
        JMXServiceURL serviceUrl = new JMXServiceURL(url);
        JMXConnector jmxc = JMXConnectorFactory.connect(serviceUrl, null);
        logger.debug("JMX connection made {}", jmxc);
        MonitoringGroup.MonitorUrlHolder monitorUrlHolder = monitorUrlHolders.get(monitorUrlKey);
        monitorUrlHolder.setmBeanServerConnection(jmxc.getMBeanServerConnection());
        monitorUrlHolder.getMonitors().clear();

        // Parse monitors inside this
        List<String> loadedMonitors = new ArrayList<String>();
        Iterator<String> monitorKeys = monitorsConfiguration
                .getKeys(ThreadManager.PROPERTY_PREFIX + monitorUrlKey);
        while (monitorKeys.hasNext()) {
            String key = monitorKeys.next();
            if (!key.endsWith(URL)) {
                String monitorName = key.substring(
                        ThreadManager.PROPERTY_PREFIX.length() + monitorUrlKey.length() + 1,
                        key.lastIndexOf("."));
                // Only load each on once (there will be n keys)
                if (!loadedMonitors.contains(monitorName)) {
                    constructMonitor(monitorUrlKey, monitorsConfiguration, monitorUrlHolder, monitorName);
                    loadedMonitors.add(monitorName);
                }
            }
        }
    } catch (IOException e) {
        if (e instanceof MalformedURLException) {
            throw (MalformedURLException) e;
        }
        logger.warn("Unable to connect to {}, {}", monitorUrlKey, e);
    }
}

From source file:com.redhat.poc.jdg.bankofchina.function.TestCase411RemoteMultiThreadsCustomMarshal.java

public static void registerProtofile(String jmxHost, int jmxPort, String cacheContainerName) throws Exception {
    JMXConnector jmxConnector = JMXConnectorFactory
            .connect(new JMXServiceURL("service:jmx:remoting-jmx://" + jmxHost + ":" + jmxPort));
    MBeanServerConnection jmxConnection = jmxConnector.getMBeanServerConnection();

    ObjectName protobufMetadataManagerObjName = new ObjectName("jboss.infinispan:type=RemoteQuery,name="
            + ObjectName.quote(cacheContainerName) + ",component=ProtobufMetadataManager");

    // initialize client-side serialization context via JMX
    byte[] descriptor = readClasspathResource("/model/userbaseinfo.protobin");
    jmxConnection.invoke(protobufMetadataManagerObjName, "registerProtofile", new Object[] { descriptor },
            new String[] { byte[].class.getName() });
    jmxConnector.close();// w  w w .j a  v  a 2  s .com
}

From source file:gr.cslab.Metric_test.java

static public void list() {
    String host = hosts.remove(0);
    try {//from   w ww . ja va2s. c  o m

        String url = "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi";
        System.out.println("RMI URL:\t" + url + "");
        JMXServiceURL serviceUrl = new JMXServiceURL(url);
        try (JMXConnector jmxc = JMXConnectorFactory.connect(serviceUrl, null)) {
            MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

            System.out.println("List of available names");

            Set<ObjectName> names;
            names = new TreeSet<>(mbsc.queryNames(null, null));
            System.out.println("Available names:");
            for (ObjectName name : names) {
                System.out.println("\tObjectName = " + name);
            }
        }
    } catch (IOException ex) {
        System.err.println("ERROR: failed to query the server " + host);
    }

}

From source file:org.wso2.appserver.integration.tests.config.EnvironmentVariableReadTestCase.java

@Test(groups = "wso2.as", description = "Try to persist a Employee obj through the Sessionfactory")
public void testConnectingToJMXServer() throws Exception {
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://localhost:" + (SERVER_PORT + portOffset)
            + "/jndi/rmi://localhost:" + (REGISTRY_PORT + portOffset) + "/jmxrmi");
    Map<String, Object> environment = new HashMap<>();
    String[] credentials = { "admin", "admin" };
    environment.put(JMXConnector.CREDENTIALS, credentials);
    JMXConnector jmxc = JMXConnectorFactory.connect(url, environment);
    log.info("Connection Id =" + jmxc.getConnectionId());
}

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;// w w  w  .j a  v a  2s .  c om
        }
    }
    assert (hasHandlerEntry);
    jmxc.close();
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.util.MMXConfigurationTest.java

@Before
public void setup() throws Exception {
    MMXManagedConfiguration mmxConfigMBean = new MMXManagedConfiguration(MMXConfiguration.getConfiguration());
    ObjectName name = new ObjectName(MMX_MBEAN_OBJECT_NAME);
    server.registerMBean(mmxConfigMBean, name);
    url = new JMXServiceURL(JMX_SERVICE_URI);
    JiveGlobalsMock.setup();/*from w w w .j  a v  a 2 s .  com*/
    jmxConnectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server);
    jmxConnectorServer.start();

    new MockUp<JiveGlobals>() {
        @Mock
        public boolean isPropertyEncrypted(String name) {
            return false;
        }
    };
}

From source file:io.mapzone.arena.ArenaPlugin.java

protected void testMBeanConnection() throws Exception {
    // test connection
    String port = System.getProperty("com.sun.management.jmxremote.port");
    if (port != null) {
        String url = "service:jmx:rmi:///jndi/rmi://localhost:" + port + "/jmxrmi";
        JMXServiceURL serviceUrl = new JMXServiceURL(url);
        try (JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceUrl, null);) {
            MBeanServerConnection conn = jmxConnector.getMBeanServerConnection();
            Set<ObjectName> beanSet = conn.queryNames(null, null);
            beanSet.forEach(n -> log.debug("    MBean: " + n));

            beanSet = conn.queryNames(ArenaConfigMBean.NAME.get(), null);
            beanSet.forEach(n -> log.debug("    MBean: " + n));

            ArenaConfigMBean arenaConfig = JMX.newMBeanProxy(conn, ArenaConfigMBean.NAME.get(),
                    ArenaConfigMBean.class);
            arenaConfig.setAppTitle("Arena");
        }// w w  w . j a v a2 s .  c  o m
    } else {
        log.info("No jmxremote.port specified.");
    }
}