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

public static JMXServiceURL buildJMXServiceURL(int rmiRegistryPort, int rmiConnectorPort) throws IOException {
    // Build jmxURL
    StringBuilder url = new StringBuilder();
    url.append("service:jmx:rmi://localhost:");
    url.append(rmiConnectorPort);/*w  ww.j ava  2s .co  m*/
    url.append("/jndi/rmi://localhost:");
    url.append(rmiRegistryPort);
    url.append("/jmxrmi");

    return new JMXServiceURL(url.toString());

}

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 {/*  ww  w . j a  v  a  2  s.c om*/
        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:com.citrix.g2w.webdriver.util.InvokeMBean.java

/**
 * Method to invoke m bean.// w  w w . j a  v  a  2s  . 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:org.rhq.plugins.jmx.util.JvmUtility.java

/**
 * TODO//from w  ww  .j av a2  s.  c o m
 *
 * @param process a java process
 * @return the JMX service URL that can be used to obtain the java process' MBeanServer, or null if connecting to
 *         the process is not possible
 */
public static JMXServiceURL extractJMXServiceURL(ProcessInfo process) {
    if (!attachApiAvailable) {
        LOG.debug("Returning null, since the Attach API is not available...");
        return null;
    }

    JMXServiceURL url;
    try {
        VirtualMachine vm = attachToVirtualMachine(process);

        if (vm == null) {
            return null;
        }

        String jmxConnectorAddress = getJmxConnectorAddress(vm);

        try {
            vm.detach();
        } catch (Exception e) {
            // We already succeeded in obtaining the connector address, so just log this, rather than throwing an exception.
            LOG.error("Failed to detach from JVM [" + vm + "].", e);
        }

        url = new JMXServiceURL(jmxConnectorAddress);
    } catch (Exception e) {
        throw new RuntimeException(
                "Failed to extract JMX service URL for process with PID [" + process.getPid() + "].", e);
    }

    LOG.debug("JMX service URL for java process with PID [" + process.getPid() + "]: " + url);
    return url;
}

From source file:net.tzolov.geode.jmx.JmxToGrafanaApplication.java

@Bean
public MBeanServerConnection jmxConnection(@Value("${mbeanHostName}") String mbeanHostName,
        @Value("${mbeanPort}") String mbeanPort) {

    try {//  ww  w.j  av  a  2 s  .c o m
        String mbeanServerUrl = "service:jmx:rmi:///jndi/rmi://" + mbeanHostName.trim() + ":" + mbeanPort.trim()
                + "/jmxrmi";
        JMXServiceURL url = new JMXServiceURL(mbeanServerUrl);

        JMXConnector jmxConnector = JMXConnectorFactory.connect(url, null);
        return jmxConnector.getMBeanServerConnection();
    } catch (Exception ex) {
        throw new RuntimeException((ex));
    }
}

From source file:org.jbosson.plugins.amq.JvmStatUtility.java

public static JMXServiceURL extractJMXServiceURL(ProcessInfo process) {
    if (!jvmstatApiAvailable) {
        LOG.debug("Returning null, since the jvmstat API is not available...");
        return null;
    }//from  ww  w .  j a  va 2s  .co m

    final long pid = process.getPid();
    JMXServiceURL serviceUrl;
    try {

        // get local host
        final MonitoredHost host = MonitoredHost.getMonitoredHost(new HostIdentifier((String) null));
        // get monitored VM
        final MonitoredVm vm = attachToMonitoredVm(host, pid);
        if (vm == null) {
            return null;
        }

        // get the service url, only if the service supports attach-on-demand
        if (!MonitoredVmUtil.isAttachable(vm)) {
            LOG.warn("JVM with PID[" + pid + "] does not support attach-on-demand");
            return null;
        }

        // can the PID be converted to int, throw an exception on platforms where this can't be done!
        if (pid < Integer.MIN_VALUE || pid > Integer.MAX_VALUE) {
            throw new Exception("Java process PID [" + pid
                    + "] cannot be converted to integer to extract JMX url using ConnectorAddressLink.importFrom(int)");
        }

        // get the connector address from vm
        serviceUrl = new JMXServiceURL(ConnectorAddressLink.importFrom((int) pid));
        try {
            vm.detach();
        } catch (Exception e) {
            // We already succeeded in obtaining the connector address,
            // so just log this, rather than throwing an exception.
            LOG.error("Failed to detach from JVM [" + vm.getVmIdentifier() + "].", e);
        }

    } catch (Exception e) {
        throw new RuntimeException("Failed to extract JMX service URL for process with PID [" + pid + "].", e);
    }

    LOG.debug("JMX service URL for java process with PID[" + pid + "]: " + serviceUrl);
    return serviceUrl;
}

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 {//  w w  w.j ava2 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.zenoss.jmxnl.NotificationListener.java

public NotificationListener(String url, String scope, String username, String password, String zenossDevice,
        String[] attributeFilters, String connectionRetryInterval)
        throws MalformedURLException, MalformedObjectNameException, NullPointerException {
    this.url = new JMXServiceURL(url);

    if (scope != null) {
        this.scope = new ObjectName(scope);
    } else {/*from ww w  . j  a  v a2s. com*/
        this.scope = new ObjectName("*:*");
    }

    environment = new HashMap<String, String[]>();
    if (username != null && password != null) {
        String[] credentials = new String[] { username, password };
        environment.put("jmx.remote.credentials", credentials);
    }

    this.zenossDevice = zenossDevice;

    if (attributeFilters == null) {
        log.debug(url + ": No attribute filters configured");
        attributeFilter = null;
    } else {
        attributeFilter = new AttributeChangeNotificationFilter();
        for (int i = 0; i < attributeFilters.length; i++) {
            log.info(url + ": Registering attribute filter for " + attributeFilters[i]);
            attributeFilter.enableAttribute(attributeFilters[i]);
        }
    }

    this.connectionRetryInterval = connectionRetryInterval;

    connectionEvent = new HashMap<String, String>();
    connectionEvent.put("device", zenossDevice);
    connectionEvent.put("component", "zenjmxnl");
    connectionEvent.put("eventKey", this.url.toString());
    connectionEvent.put("eventClass", "/Status/JMX/Conn");
}

From source file:org.ff4j.jmx.FF4JMBeanTest.java

private void openJmxConnection() throws Exception {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

    // Make a connector server...
    JMXServiceURL jmxUrl = new JMXServiceURL("service:jmx:rmi://");
    jmxConnectionServer = JMXConnectorServerFactory.newJMXConnectorServer(jmxUrl, null, mbs);
    jmxConnectionServer.start();//w  ww.  j a  v  a2  s  . c o  m
    JMXServiceURL jmxAddress = jmxConnectionServer.getAddress();

    // Now make a connector client using the server's address
    jmxConnectionFactory = JMXConnectorFactory.connect(jmxAddress);
    mbServConn = jmxConnectionFactory.getMBeanServerConnection();
}

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  .ja  v a 2s  . com*/
 */
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());
    }
}