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:com.citrix.g2w.webdriver.util.InvokeMBean.java

/**
 * Method to invoke m bean./*w w  w  .j  a v  a  2 s .  c  o m*/
 * 
 * @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.clustercontrol.HinemosManagerCli.java

private void invoke() {
    System.setProperty("sun.rmi.transport.connectionTimeout", String.valueOf(connectTimeout));
    System.setProperty("sun.rmi.transport.tcp.responseTimeout", String.valueOf(responseTimeout));

    try {/*  w w  w. ja v  a  2s . co m*/
        JMXServiceURL url = new JMXServiceURL(
                String.format("service:jmx:rmi:///jndi/rmi://%s:%s/jmxrmi", ip, port));
        Map<String, Object> env = new HashMap<String, Object>();
        if (user != null && password != null) {
            env.put(JMXConnector.CREDENTIALS, new String[] { user, password });
        }
        MBeanServerConnection mbsc = JMXConnectorFactory.connect(url, env).getMBeanServerConnection();

        ObjectName mbeanName = new ObjectName("com.clustercontrol.mbean:type=" + name);
        if (doesOutputInfo) {
            printMBeanInfo(mbsc.getMBeanInfo(mbeanName));
            return;
        }

        Object ret;
        if (attribute != null) {
            ret = mbsc.getAttribute(mbeanName, attribute);
        } else {
            String[] signature = new String[operationArgs.length];
            for (int i = 0; i < signature.length; i++) {
                signature[i] = String.class.getName();
            }
            ret = mbsc.invoke(mbeanName, operation, operationArgs, signature);
        }
        System.out.println(ret);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(2);
    }
}

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 2s .  co  m

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

    mbeanProxy.clearHelloStore();

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

From source file:com.tribloom.module.JmxClient.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("connectionSuccess", true);
    model.put("time", System.currentTimeMillis());
    try {//from  w  w  w  .  j  a  v  a  2  s.  c  o m
        // Create an RMI connector client and
        // connect it to the RMI connector server
        //
        echo("\nCreate an RMI connector client and " + "connect it to the RMI connector server");
        JMXServiceURL url = new JMXServiceURL(
                "service:jmx:rmi://ignored/jndi/rmi://localhost:50500/alfresco/jmxrmi");
        Map<String, Object> env = new HashMap<String, Object>();
        String[] creds = { "controlRole", "change_asap" };
        env.put(JMXConnector.CREDENTIALS, creds);
        JMXConnector jmxc = JMXConnectorFactory.connect(url, env);

        // Get an MBeanServerConnection
        //
        echo("\nGet an MBeanServerConnection");
        MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

        ObjectName memory = new ObjectName("java.lang:type=Memory");
        CompositeData heapMemUsage = (CompositeData) mbsc.getAttribute(memory, "HeapMemoryUsage");
        addCompositeData(model, heapMemUsage, "heapMemoryUsage");
        CompositeData nonHeapMemUsage = (CompositeData) mbsc.getAttribute(memory, "NonHeapMemoryUsage");
        addCompositeData(model, nonHeapMemUsage, "nonHeapMemoryUsage");

        ObjectName operatingSystem = new ObjectName("java.lang:type=OperatingSystem");
        model.put("openFileDescriptorCount", mbsc.getAttribute(operatingSystem, "OpenFileDescriptorCount"));
        model.put("maxFileDescriptorCount", mbsc.getAttribute(operatingSystem, "MaxFileDescriptorCount"));
        model.put("committedVirtualMemorySize",
                mbsc.getAttribute(operatingSystem, "CommittedVirtualMemorySize"));
        model.put("totalSwapSpaceSize", mbsc.getAttribute(operatingSystem, "TotalSwapSpaceSize"));
        model.put("freeSwapSpaceSize", mbsc.getAttribute(operatingSystem, "FreeSwapSpaceSize"));
        model.put("processCpuTime", mbsc.getAttribute(operatingSystem, "ProcessCpuTime"));
        model.put("freePhysicalMemorySize", mbsc.getAttribute(operatingSystem, "FreePhysicalMemorySize"));
        model.put("totalPhysicalMemorySize", mbsc.getAttribute(operatingSystem, "TotalPhysicalMemorySize"));
        model.put("operatingSystemName", mbsc.getAttribute(operatingSystem, "Name"));
        model.put("operatingSystemVersion", mbsc.getAttribute(operatingSystem, "Version"));
        model.put("operatingSystemArch", mbsc.getAttribute(operatingSystem, "Arch"));
        model.put("availableProcessors", mbsc.getAttribute(operatingSystem, "AvailableProcessors"));
        model.put("systemLoadAverage", mbsc.getAttribute(operatingSystem, "SystemLoadAverage"));

        try {
            ObjectName parNewGarbageCollector = new ObjectName("java.lang:type=GarbageCollector,name=ParNew");
            echo("\nparNewGarbageCollector = " + parNewGarbageCollector);
            CompositeData parNewLastGcInfo = (CompositeData) mbsc.getAttribute(parNewGarbageCollector,
                    "LastGcInfo");
            addCompositeData(model, parNewLastGcInfo, "parNewLastGcInfo");
        } catch (InstanceNotFoundException ex) {
            // No Garbage Collection has occurred yet
            echo("No Garbage Collection found: " + ex.getMessage());
        }
        try {
            ObjectName concurrentGarbageCollector = new ObjectName(
                    "java.lang:type=GarbageCollector,name=ConcurrentMarkSweep");
            echo("\nconcurrentGarbageCollector = " + concurrentGarbageCollector);
            CompositeData concurrentGarbageCollectorLastGcInfo = (CompositeData) mbsc
                    .getAttribute(concurrentGarbageCollector, "LastGcInfo");
            addCompositeData(model, concurrentGarbageCollectorLastGcInfo, "concurrentMarkSweepLastGcInfo");
        } catch (InstanceNotFoundException ex) {
            // No Garbage Collection has occurred yet
            echo("No Garbage Collection found: " + ex.getMessage());
        }

        ObjectName classLoading = new ObjectName("java.lang:type=ClassLoading");
        model.put("classLoadingLoadedClassCount", mbsc.getAttribute(classLoading, "LoadedClassCount"));
        model.put("classLoadingUnloadedClassCount", mbsc.getAttribute(classLoading, "UnloadedClassCount"));
        model.put("classLoadingTotalLoadedClassCount",
                mbsc.getAttribute(classLoading, "TotalLoadedClassCount"));

        ObjectName runtime = new ObjectName("java.lang:type=Runtime");
        model.put("runtimeName", mbsc.getAttribute(runtime, "Name"));
        model.put("runtimeClassPath", mbsc.getAttribute(runtime, "ClassPath"));

        // TODO: Tabular type...
        Object sysProps = mbsc.getAttribute(runtime, "SystemProperties");
        echo("\nsysProps = " + sysProps);

        model.put("runtimeStartTime", mbsc.getAttribute(runtime, "StartTime"));
        model.put("runtimeVmName", mbsc.getAttribute(runtime, "VmName"));
        model.put("runtimeVmVendor", mbsc.getAttribute(runtime, "VmVendor"));
        model.put("runtimeVmVersion", mbsc.getAttribute(runtime, "VmVersion"));
        model.put("runtimeLibraryPath", mbsc.getAttribute(runtime, "LibraryPath"));
        model.put("runtimeBootClassPath", mbsc.getAttribute(runtime, "BootClassPath"));
        model.put("runtimeManagementSpecVersion", mbsc.getAttribute(runtime, "ManagementSpecVersion"));
        model.put("runtimeSpecName", mbsc.getAttribute(runtime, "SpecName"));
        model.put("runtimeSpecVendor", mbsc.getAttribute(runtime, "SpecVendor"));
        model.put("runtimeSpecVersion", mbsc.getAttribute(runtime, "SpecVersion"));
        model.put("runtimeInputArguments", mbsc.getAttribute(runtime, "InputArguments")); // TODO: Array...
        model.put("runtimeUptime", mbsc.getAttribute(runtime, "Uptime"));

        try {
            ObjectName memoryPool = new ObjectName("java.lang:type=MemoryPool");
            model.put("memoryPoolName", mbsc.getAttribute(memoryPool, "Name"));
            model.put("memoryPoolType", mbsc.getAttribute(memoryPool, "Type"));
            CompositeData memoryPoolUsage = (CompositeData) mbsc.getAttribute(memoryPool, "Usage");
            addCompositeData(model, memoryPoolUsage, "memoryPoolUsage");
            CompositeData memoryPoolPeakUsage = (CompositeData) mbsc.getAttribute(memoryPool, "PeakUsage");
            addCompositeData(model, memoryPoolPeakUsage, "memoryPoolPeakUsage");
            model.put("memoryPoolMemoryManagerNames", mbsc.getAttribute(memoryPool, "MemoryManagerNames")); // Array of strings
            model.put("memoryPoolUsageThreshold", mbsc.getAttribute(memoryPool, "UsageThreshold"));
            model.put("memoryPoolUsageThresholdExceeded",
                    mbsc.getAttribute(memoryPool, "UsageThresholdExceeded"));
            model.put("memoryPoolUsageThresholdCount", mbsc.getAttribute(memoryPool, "UsageThresholdCount"));
            model.put("memoryPoolUsageThresholdSupported",
                    mbsc.getAttribute(memoryPool, "UsageThresholdSupported"));
            model.put("memoryPoolCollectionUsageThreshold",
                    mbsc.getAttribute(memoryPool, "CollectionUsageThreshold"));
            model.put("memoryPoolCollectionUsageThresholdExceeded",
                    mbsc.getAttribute(memoryPool, "CollectionUsageThresholdExceeded"));
            model.put("memoryPoolCollectionUsageThresholdCount",
                    mbsc.getAttribute(memoryPool, "CollectionUsageThresholdCount"));
            CompositeData collectionUsage = (CompositeData) mbsc.getAttribute(memoryPool, "CollectionUsage");
            addCompositeData(model, collectionUsage, "memoryPoolCollectionUsage");
            model.put("memoryPoolCollectionUsageThresholdSupported",
                    mbsc.getAttribute(memoryPool, "CollectionUsageThresholdSupported"));

        } catch (InstanceNotFoundException ex) {
            // Memory pool not initialized yet

        }

        echo("\nClose the connection to the server");
        jmxc.close();
        echo("\nBye! Bye!");
    } catch (Exception ex) {
        ex.printStackTrace();
        model.put("connectionSuccess", false);
        model.put("exception", ex.getMessage());
    }
    return model;
}

From source file:org.pssframework.jmx.MBeanServerConnectionInterceptor.java

private void reconnect() throws IOException, MalformedURLException {
    JMXConnector connector = JMXConnectorFactory.connect(new JMXServiceURL(serviceUrl), null);
    this.connection = connector.getMBeanServerConnection();
}

From source file:com.xoriant.jmx.pool.JmxPoolFactory.java

/**
 * The create method will create the actual JMX connection.
 *///from w w  w  .java2 s . co  m
@SuppressWarnings("unchecked")
@Override
public Q create() throws Exception {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("In create method");
    }
    JMXServiceURL url = null;
    JMXConnector jmxConnector = null;
    StringBuilder vUrlString = new StringBuilder(ApplicationProperty.JMX_URL_FRONT);
    vUrlString.append(host);
    vUrlString.append(ApplicationProperty.COLON);
    vUrlString.append(port);
    vUrlString.append(ApplicationProperty.JMX_URL_BACK);
    try {
        url = new JMXServiceURL(vUrlString.toString());
        jmxConnector = JMXConnectorFactory.connect(url, null);
    } catch (IOException e) {
        LOGGER.error(e.getMessage());
        throw new ConnectionNotFoundException(host, port);
    }
    return (Q) jmxConnector;
}

From source file:io.mapzone.controller.um.launcher.ArenaLauncher.java

protected void configureInstance(ProjectInstanceRecord instance) throws MalformedURLException {
    // config via JMX
    String url = "service:jmx:rmi:///jndi/rmi://" + instance.host.get().inetAddress.get() + ":"
            + instance.process.get().jmxPort.get() + "/jmxrmi";
    JMXServiceURL serviceUrl = new JMXServiceURL(url);
    try (JMXConnector connector = JMXConnectorFactory.connect(serviceUrl, null);) {
        MBeanServerConnection conn = connector.getMBeanServerConnection();

        log.info(url);/*from ww w.  j a  va  2 s  .com*/
        while (conn.queryNames(ArenaConfigMBean.NAME.get(), null).isEmpty()) {
            log.info("No such MBean: " + ArenaConfigMBean.NAME.get());
            Thread.sleep(100);
        }

        String localHttpPort = ControllerPlugin.instance().httpPort();

        ArenaConfigMBean arenaConfig = JMX.newMBeanProxy(conn, ArenaConfigMBean.NAME.get(),
                ArenaConfigMBean.class);
        checked(() -> arenaConfig.setAppTitle(instance.project.get()));
        checked(() -> arenaConfig.setServiceAuthToken(project().serviceAuthToken.get())); // send before URLs!!!
        checked(() -> arenaConfig.setCatalogServerUrl("http://localhost:" + localHttpPort + "/csw"));
        checked(() -> arenaConfig.setProxyUrl(ProxyServlet.projectUrlBase(project())));
        checked(() -> arenaConfig.setProjectCatalogId(project().catalogId.get()));

        log.info("Instance process configured.");
    } catch (Throwable e) {
        log.warn("Error while configuring instance.", e);
    }
}

From source file:com.espertech.esper.example.servershellclient.ServerShellClientMain.java

public ServerShellClientMain() throws Exception {
    log.info("Loading properties");
    Properties properties = new Properties();
    InputStream propertiesIS = ServerShellClientMain.class.getClassLoader()
            .getResourceAsStream(ServerShellConstants.CONFIG_FILENAME);
    if (propertiesIS == null) {
        throw new RuntimeException(
                "Properties file '" + ServerShellConstants.CONFIG_FILENAME + "' not found in classpath");
    }//  ww w. j  a va  2 s .  co  m
    properties.load(propertiesIS);

    // Attached via JMX to running server
    log.info("Attach to server via JMX");
    JMXServiceURL url = new JMXServiceURL(properties.getProperty(ServerShellConstants.MGMT_SERVICE_URL));
    JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
    ObjectName mBeanName = new ObjectName(ServerShellConstants.MGMT_MBEAN_NAME);
    EPServiceProviderJMXMBean proxy = (EPServiceProviderJMXMBean) MBeanServerInvocationHandler
            .newProxyInstance(mbsc, mBeanName, EPServiceProviderJMXMBean.class, true);

    // Connect to JMS
    log.info("Connecting to JMS server");
    String factory = properties.getProperty(ServerShellConstants.JMS_CONTEXT_FACTORY);
    String jmsurl = properties.getProperty(ServerShellConstants.JMS_PROVIDER_URL);
    String connFactoryName = properties.getProperty(ServerShellConstants.JMS_CONNECTION_FACTORY_NAME);
    String user = properties.getProperty(ServerShellConstants.JMS_USERNAME);
    String password = properties.getProperty(ServerShellConstants.JMS_PASSWORD);
    String destination = properties.getProperty(ServerShellConstants.JMS_INCOMING_DESTINATION);
    boolean isTopic = Boolean.parseBoolean(properties.getProperty(ServerShellConstants.JMS_IS_TOPIC));
    JMSContext jmsCtx = JMSContextFactory.createContext(factory, jmsurl, connFactoryName, user, password,
            destination, isTopic);

    // Create statement via JMX
    log.info("Creating a statement via Java Management Extensions (JMX) MBean Proxy");
    proxy.createEPL("select * from SampleEvent where duration > 9.9", "filterStatement",
            new ClientSideUpdateListener());

    // Get producer
    jmsCtx.getConnection().start();
    MessageProducer producer = jmsCtx.getSession().createProducer(jmsCtx.getDestination());

    Random random = new Random();
    String[] ipAddresses = { "127.0.1.0", "127.0.2.0", "127.0.3.0", "127.0.4.0" };
    NumberFormat format = NumberFormat.getInstance();

    // Send messages
    for (int i = 0; i < 1000; i++) {
        String ipAddress = ipAddresses[random.nextInt(ipAddresses.length)];
        double duration = 10 * random.nextDouble();
        String durationStr = format.format(duration);
        String payload = ipAddress + "," + durationStr;

        BytesMessage bytesMessage = jmsCtx.getSession().createBytesMessage();
        bytesMessage.writeBytes(payload.getBytes());
        bytesMessage.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT);
        producer.send(bytesMessage);

        if (i % 100 == 0) {
            log.info("Sent " + i + " messages");
        }
    }

    // Create statement via JMX
    log.info("Destroing statement via Java Management Extensions (JMX) MBean Proxy");
    proxy.destroy("filterStatement");

    log.info("Shutting down JMS client connection");
    jmsCtx.destroy();

    log.info("Exiting");
    System.exit(-1);
}

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

private JMXConnector getJmxConnector() throws IOException {
    Hashtable<String, Object> h = new Hashtable<String, Object>();
    //      String username = behaviour.getDmServer().getDeployerUsername();
    //      String password = behaviour.getDmServer().getDeployerPassword();
    //      if (StringUtils.hasText(username)) {
    //         String[] credentials = new String[] { username, password };
    //         h.put(JMX_REMOTE_CREDENTIALS, credentials);
    //      }/*from   ww  w  . ja va  2 s . c  o m*/
    Server server = ServerUtils.getServer(serverBehaviour);

    if (serverBehaviour.getMBeanServerIp() == null) {
        throw new IOException("MBean server not open for connection");
    }
    String connectorUrl = String.format(JMX_CONNECTOR_URL, serverBehaviour.getMBeanServerIp(),
            server.getMBeanServerPort());
    return JMXConnectorFactory.connect(new JMXServiceURL(connectorUrl), h);
}

From source file:org.wso2.carbon.registry.subscription.test.util.JMXClient.java

/**
 * connect to org.wso2.carbon for JMX monitoring
 *
 * @param userName user name to connect to org.wso2.carbon
 * @param password password to connect to org.wso2.carbon
 * @throws Exception//from   w w  w  . j a  v  a 2 s . c o  m
 */
public void connect(String userName, String password) 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(CONNECTION_NAME);
    } catch (Exception ex) {
        log.error("infoAdminServiceStub Initialization fail ");
        throw new Exception("infoAdminServiceStub Initialization fail " + ex.getMessage());
    }
}