Example usage for javax.management.remote JMXConnector close

List of usage examples for javax.management.remote JMXConnector close

Introduction

In this page you can find the example usage for javax.management.remote JMXConnector close.

Prototype

public void close() throws IOException;

Source Link

Document

Closes the client connection to its server.

Usage

From source file:org.apache.hadoop.hbase.TestStochasticBalancerJmxMetrics.java

/**
 * Read the attributes from Hadoop->HBase->Master->Balancer in JMX
 * @throws IOException /* w  ww.j a  v  a  2s .c  om*/
 */
private Set<String> readJmxMetrics() throws IOException {
    JMXConnector connector = null;
    ObjectName target = null;
    MBeanServerConnection mb = null;
    try {
        connector = JMXConnectorFactory.connect(JMXListener.buildJMXServiceURL(connectorPort, connectorPort));
        mb = connector.getMBeanServerConnection();

        Hashtable<String, String> pairs = new Hashtable<>();
        pairs.put("service", "HBase");
        pairs.put("name", "Master");
        pairs.put("sub", "Balancer");
        target = new ObjectName("Hadoop", pairs);
        MBeanInfo beanInfo = mb.getMBeanInfo(target);

        Set<String> existingAttrs = new HashSet<String>();
        for (MBeanAttributeInfo attrInfo : beanInfo.getAttributes()) {
            existingAttrs.add(attrInfo.getName());
        }
        return existingAttrs;
    } catch (Exception e) {
        LOG.warn("Failed to get bean!!! " + target, e);
        if (mb != null) {
            Set<ObjectInstance> instances = mb.queryMBeans(null, null);
            Iterator<ObjectInstance> iterator = instances.iterator();
            System.out.println("MBean Found:");
            while (iterator.hasNext()) {
                ObjectInstance instance = iterator.next();
                System.out.println("Class Name: " + instance.getClassName());
                System.out.println("Object Name: " + instance.getObjectName());
            }
        }
    } finally {
        if (connector != null) {
            try {
                connector.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

From source file:com.ibm.soatf.component.osb.ServiceManager.java

public static boolean changeServiceStatus(String servicetype, boolean status, String serviceURI, String host,
        int port, String username, String password) throws FrameworkExecutionException {

    SessionManagementMBean sm = null;//w  w  w  .jav  a2s  .co  m
    JMXConnector conn = null;
    boolean result = true;
    String statusMsg = "";
    try {
        conn = initConnection(host, port, username, password);
        MBeanServerConnection mbconn = conn.getMBeanServerConnection();
        DomainRuntimeServiceMBean clusterService = (DomainRuntimeServiceMBean) MBeanServerInvocationHandler
                .newProxyInstance(mbconn, new ObjectName(DomainRuntimeServiceMBean.OBJECT_NAME));
        sm = (SessionManagementMBean) clusterService.findService(SessionManagementMBean.NAME,
                SessionManagementMBean.TYPE, null);
        sm.createSession(SESSION_NAME);
        ALSBConfigurationMBean alsbSession = (ALSBConfigurationMBean) clusterService.findService(
                ALSBConfigurationMBean.NAME + "." + SESSION_NAME, ALSBConfigurationMBean.TYPE, null);

        if (servicetype.equals("ProxyService")) {
            Ref ref = constructRef("ProxyService", serviceURI);
            ProxyServiceConfigurationMBean proxyConfigMBean = (ProxyServiceConfigurationMBean) clusterService
                    .findService(ProxyServiceConfigurationMBean.NAME + "." + SESSION_NAME,
                            ProxyServiceConfigurationMBean.TYPE, null);
            if (status) {
                proxyConfigMBean.enableService(ref);
                statusMsg = "Enable the ProxyService : " + serviceURI;
                logger.info(statusMsg);
            } else {
                proxyConfigMBean.disableService(ref);
                statusMsg = "Disable the ProxyService : " + serviceURI;
                logger.info(statusMsg);
            }
        } else if (servicetype.equals("BusinessService")) {
            try {
                Ref ref = constructRef("BusinessService", serviceURI);
                BusinessServiceConfigurationMBean businessConfigMBean = (BusinessServiceConfigurationMBean) clusterService
                        .findService(BusinessServiceConfigurationMBean.NAME + "." + SESSION_NAME,
                                BusinessServiceConfigurationMBean.TYPE, null);
                if (status) {
                    businessConfigMBean.enableService(ref);
                    statusMsg = "Enable the BusinessService : " + serviceURI;
                    logger.info(statusMsg);
                } else {
                    businessConfigMBean.disableService(ref);
                    statusMsg = "Disable the BusinessService : " + serviceURI;
                    logger.info(statusMsg);
                }
            } catch (IllegalArgumentException ex) {
                logger.fatal(ExceptionUtils.getStackTrace(ex));
            }
        }
        sm.activateSession(SESSION_NAME, statusMsg);
        conn.close();
    } catch (Exception ex) {
        if (null != sm) {
            try {
                sm.discardSession(SESSION_NAME);
            } catch (Exception e) {
                logger.debug("Not able to discard the session. " + e.getLocalizedMessage());
                throw new FrameworkExecutionException(e);
            }
        }
        result = false;
        logger.error("Error in MBean Server connection. " + ex.getLocalizedMessage());
        ex.printStackTrace();
    } finally {
        if (null != conn) {
            try {
                conn.close();
            } catch (Exception e) {
                logger.debug("Not able to close the JMX connection. " + e.getLocalizedMessage());
                throw new FrameworkExecutionException(e);

            }
        }
    }

    return result;
}

From source file:org.kuali.test.ui.components.dialogs.JmxDlg.java

public void loadJMXData() {
    JMXConnector conn = null;

    try {//  w w  w . j  a va  2 s .  co  m
        Set<String> hs = new HashSet<String>();

        if (jmx.getPerformanceMonitoringAttributes() != null) {
            for (PerformanceMonitoringAttribute pma : jmx.getPerformanceMonitoringAttributes()
                    .getPerformanceMonitoringAttributeArray()) {
                hs.add(pma.getType() + "." + pma.getName());
            }
        }

        conn = Utils.getJMXConnector(getConfiguration(), jmx);

        if (conn != null) {
            MBeanServerConnection mbeanConn = conn.getMBeanServerConnection();
            if (mbeanConn != null) {
                for (int i = 0; i < tabInfo.length; ++i) {
                    MBeanInfo mbeanInfo = mbeanConn.getMBeanInfo(new ObjectName(tabInfo[i].getJmxBeanName()));

                    if (mbeanInfo != null) {
                        for (MBeanAttributeInfo att : mbeanInfo.getAttributes()) {
                            AttributeWrapper aw = new AttributeWrapper(att);

                            if (isValidAttributeType(aw.getType())) {
                                tabInfo[i].getAttributeInfo().add(aw);

                                if (hs.contains(tabInfo[i].getJmxBeanName() + "." + aw.getName())) {
                                    aw.setSelected(true);
                                }
                            }
                        }

                        getTablePanel(i).getTable().setTableData(tabInfo[i].getAttributeInfo());
                    }
                }
            }
        }
    }

    catch (Exception ex) {
        LOG.error(ex.toString(), ex);
        UIUtils.showError(this, "JMX Error", "Error occurred during JMX connection - " + ex.toString());
    }

    finally {
        if (conn != null) {
            try {
                conn.close();
            }

            catch (Exception ex) {
            }
            ;
        }
    }
}

From source file:de.unisb.cs.st.javalanche.mutation.runtime.jmx.MutationMxClient.java

public static boolean connect(int i) {
    JMXConnector jmxc = null;
    JMXServiceURL url = null;/*from  ww  w . ja v a  2s. co  m*/

    try {
        url = new JMXServiceURL(MXBeanRegisterer.ADDRESS + i);
        jmxc = JMXConnectorFactory.connect(url, null);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        return false;
        // System.out.println("Could not connect to address: " + url);
        // e.printStackTrace();
    }
    if (jmxc != null) {
        try {
            MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
            ObjectName objectName = new ObjectName(MXBeanRegisterer.OBJECT_NAME);
            Object numberOfMutations = mbsc.getAttribute(objectName, "NumberOfMutations");
            Object currentTest = mbsc.getAttribute(objectName, "CurrentTest");
            Object currentMutation = mbsc.getAttribute(objectName, "CurrentMutation");
            Object allMutations = mbsc.getAttribute(objectName, "Mutations");
            Object mutationsDuration = mbsc.getAttribute(objectName, "MutationDuration");
            Object testDuration = mbsc.getAttribute(objectName, "TestDuration");
            //            Object mutationSummary = mbsc.getAttribute(objectName,
            //                  "MutationSummary");

            final RuntimeMXBean remoteRuntime = ManagementFactory.newPlatformMXBeanProxy(mbsc,
                    ManagementFactory.RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);

            final MemoryMXBean remoteMemory = ManagementFactory.newPlatformMXBeanProxy(mbsc,
                    ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class);
            System.out.print("Connection: " + i + "  ");
            System.out.println("Target VM: " + remoteRuntime.getName() + " - " + remoteRuntime.getVmVendor()
                    + " - " + remoteRuntime.getSpecVersion() + " - " + remoteRuntime.getVmVersion());
            System.out.println(
                    "Running for: " + DurationFormatUtils.formatDurationHMS(remoteRuntime.getUptime()));
            System.out
                    .println("Memory usage: Heap - " + formatMemory(remoteMemory.getHeapMemoryUsage().getUsed())
                            + "  Non Heap - " + formatMemory(remoteMemory.getNonHeapMemoryUsage().getUsed()));

            String mutationDurationFormatted = DurationFormatUtils
                    .formatDurationHMS(Long.parseLong(mutationsDuration.toString()));
            String testDurationFormatted = DurationFormatUtils
                    .formatDurationHMS(Long.parseLong(testDuration.toString()));
            if (DEBUG_ADD) {
                System.out.println("Classpath: " + remoteRuntime.getClassPath());
                System.out.println("Args: " + remoteRuntime.getInputArguments());
                System.out.println("All Mutations: " + allMutations);
            }
            //            System.out.println(mutationSummary);
            System.out.println(
                    "Current mutation (Running for: " + mutationDurationFormatted + "): " + currentMutation);
            System.out.println("Mutations tested: " + numberOfMutations);
            System.out.println("Current test:   (Running for: " + testDurationFormatted + "): " + currentTest);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MalformedObjectNameException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (AttributeNotFoundException e) {
            e.printStackTrace();
        } catch (InstanceNotFoundException e) {
            e.printStackTrace();
        } catch (MBeanException e) {
            e.printStackTrace();
        } catch (ReflectionException e) {
            e.printStackTrace();
        } finally {
            try {
                jmxc.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return true;
}

From source file:org.wso2.carbon.analytics.common.jmx.agent.JmxAgentWebInterface.java

/**
 * @param mBean    : The name of the MBean
 * @param url      : The URL for the JMX server
 * @param userName : The User name for the JMX server
 * @param password : The password for the JMX server
 * @return : The set of attributes in a MBean
 * @throws MalformedObjectNameException// ww w  .  jav  a 2  s.c  o m
 * @throws IntrospectionException
 * @throws InstanceNotFoundException
 * @throws IOException
 * @throws ReflectionException
 */
public String[][] getMBeanAttributeInfo(String mBean, String url, String userName, String password)
        throws MalformedObjectNameException, IntrospectionException, InstanceNotFoundException, IOException,
        ReflectionException {

    JMXConnector jmxc = getJmxConnector(url, userName, password);

    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
    ObjectName mBeanName = new ObjectName(mBean);

    MBeanAttributeInfo[] attrs = mbsc.getMBeanInfo(mBeanName).getAttributes();

    ArrayList<String[]> strAttrs = new ArrayList<String[]>();

    for (MBeanAttributeInfo info : attrs) {

        //check the suitability of the attribute
        try {
            Object result = mbsc.getAttribute(mBeanName, info.getName());

            //if this is an instance of a primary data type supported by cassandra
            if (result instanceof String || result instanceof Integer || result instanceof Double
                    || result instanceof Long || result instanceof Boolean || result instanceof Float) {
                strAttrs.add(new String[] { info.getName() });
            }

            //if this is a composite data type
            if (result instanceof CompositeData) {
                CompositeData cd = (CompositeData) result;
                ArrayList<String> keys = new ArrayList<String>();
                //add the attribute name
                keys.add(info.getName());
                for (String key : cd.getCompositeType().keySet()) {
                    //check whether the key returns a primary data type
                    Object attrValue = cd.get(key);
                    if (attrValue instanceof String || attrValue instanceof Integer
                            || attrValue instanceof Double || attrValue instanceof Long
                            || attrValue instanceof Boolean || attrValue instanceof Float) {
                        keys.add(key);
                    }
                }
                //if this composite data object has keys which returns attributes with
                // primary data types
                if (keys.size() > 1) {
                    strAttrs.add(keys.toArray(new String[keys.size()]));
                }
            }
        } catch (MBeanException e) {
            log.error("Removed the attribute " + info.getName() + " of " + mBean + " from the UI list due to: "
                    + e.getMessage());
        } catch (AttributeNotFoundException e) {
            log.error("Removed the attribute " + info.getName() + " of " + mBean + " from the UI list due to: "
                    + e.getMessage());
        } catch (UnmarshalException e) {
            log.error("Removed the attribute " + info.getName() + " of " + mBean + " from the UI list due to: "
                    + e.getMessage());
        } catch (RuntimeOperationsException e) {
            log.error("Removed the attribute " + info.getName() + " of " + mBean + " from the UI list due to: "
                    + e.getMessage());

        } catch (RuntimeMBeanException e) {
            log.error("Removed the attribute " + info.getName() + " of " + mBean + " from the UI list due to: "
                    + e.getMessage());
        } catch (ReflectionException e) {
            log.error("Removed the attribute " + info.getName() + " of " + mBean + " from the UI list due to: "
                    + e.getMessage());
        } catch (Exception e) {
            log.error("Removed the attribute " + info.getName() + " of " + mBean + " from the UI list due to: "
                    + e.getMessage());
        }
    }

    //close the connection
    jmxc.close();

    return strAttrs.toArray(new String[strAttrs.size()][]);
}

From source file:org.kuali.test.runner.execution.TestExecutionContext.java

private void writePerformanceData(TestOperation op, long operationElaspedTime) {
    if (isPerformanceDataRequired()) {

        if (performanceData == null) {
            performanceData = new ArrayList<String[]>();
        }//from   w  ww.ja v a 2s .c  om

        String submitElementName = getLastHttpSubmitElementName();
        ;

        if (op.getOperationType().equals(TestOperationType.HTTP_REQUEST)) {
            String[] rec = getInitializedPerformanceDataRecord();
            rec[8] = Constants.PERFORMANCE_ATTRIBUTE_TYPE_CLIENT;
            rec[9] = Constants.CLIENT_PERFORMANCE_ATTRIBUTE_HTTP_RESPONSE_TIME;
            rec[10] = Constants.PRIMITIVE_LONG_TYPE;
            rec[11] = "" + operationElaspedTime;
            rec[12] = submitElementName;
            rec[13] = (op.getOperation().getHtmlRequestOperation().getMethod() + ": "
                    + op.getOperation().getHtmlRequestOperation().getUrl());
            performanceData.add(rec);
        }

        JmxConnection jmxconn = Utils.findJmxConnection(configuration, platform.getJmxConnectionName());

        if ((jmxconn != null) && (jmxconn.getPerformanceMonitoringAttributes() != null)) {
            JMXConnector conn = null;
            try {
                conn = Utils.getJMXConnector(configuration, jmxconn);
                if (conn != null) {
                    MBeanServerConnection mbeanconn = conn.getMBeanServerConnection();
                    for (PerformanceMonitoringAttribute att : jmxconn.getPerformanceMonitoringAttributes()
                            .getPerformanceMonitoringAttributeArray()) {

                        Object value = "";
                        if (ManagementFactory.MEMORY_MXBEAN_NAME.equals(att.getType())) {
                            MemoryMXBean mbean = ManagementFactory.newPlatformMXBeanProxy(mbeanconn,
                                    ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class);
                            value = getValueFromMXBeanObject(att.getName(), mbean);
                        } else if (ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME.equals(att.getType())) {
                            OperatingSystemMXBean mbean = ManagementFactory.newPlatformMXBeanProxy(mbeanconn,
                                    att.getType(), OperatingSystemMXBean.class);
                            value = getValueFromMXBeanObject(att.getName(), mbean);
                        } else if (ManagementFactory.THREAD_MXBEAN_NAME.equals(att.getType())) {
                            ThreadMXBean mbean = ManagementFactory.newPlatformMXBeanProxy(mbeanconn,
                                    att.getType(), ThreadMXBean.class);
                            value = getValueFromMXBeanObject(att.getName(), mbean);
                        }

                        if ((value != null) && StringUtils.isNotBlank(value.toString())) {
                            String[] rec = getInitializedPerformanceDataRecord();

                            int pos = att.getType().indexOf(Constants.SEPARATOR_EQUALS);

                            if (pos > -1) {
                                rec[8] = att.getType().substring(pos + 1);
                            } else {
                                rec[8] = att.getType();
                            }
                            rec[9] = att.getName();
                            rec[10] = att.getType();
                            rec[11] = value.toString();
                            rec[12] = submitElementName;
                            rec[13] = att.getDescription();

                            performanceData.add(rec);
                        }
                    }
                }
            }

            catch (Exception ex) {
                LOG.error(ex.toString(), ex);
            }

            finally {
                if (conn != null) {
                    try {
                        conn.close();
                    }

                    catch (Exception ex) {
                    }
                    ;
                }
            }
        }
    }
}

From source file:com.clustercontrol.jmx.factory.RunMonitorJmx.java

/**
 * JMX ??/*from   w  w w  .  j a v  a 2  s. co m*/
 * 
 * @param facilityId ID
 * @return ???????true
 */
@Override
public boolean collect(String facilityId) {
    boolean result = false;

    if (m_now != null) {
        m_nodeDate = m_now.getTime();
    }
    m_value = 0;
    exception = null;

    NodeInfo node = null;
    if (!m_isMonitorJob) {
        node = nodeInfo.get(facilityId);
    } else {
        try {
            // ??
            node = new RepositoryControllerBean().getNode(facilityId);
        } catch (Exception e) {
            m_message = MessageConstant.MESSAGE_COULD_NOT_GET_NODE_ATTRIBUTES.getMessage();
            return false;
        }
    }

    JMXServiceURL url = null;
    try {
        String rmiFormat = HinemosPropertyUtil.getHinemosPropertyStr("monitor.jmx.rmi.format",
                "service:jmx:rmi:///jndi/rmi://%s:%d/jmxrmi");
        String urlStr = String.format(rmiFormat, node.getAvailableIpAddress(), jmx.getPort());
        m_log.debug("facilityId=" + facilityId + ", url=" + urlStr);
        url = new JMXServiceURL(urlStr);
    } catch (Exception e) {
        m_log.warn("fail to initialize JMXServiceURL : " + e.getMessage() + " (" + e.getClass().getName() + ")",
                e);
        exception = e;
        return result;
    }

    JMXConnector jmxc = null;
    try {
        Map<String, Object> env = new HashMap<>();

        if (jmx.getAuthUser() != null)
            env.put(JMXConnector.CREDENTIALS, new String[] { jmx.getAuthUser(), jmx.getAuthPassword() });

        System.setProperty("sun.rmi.transport.tcp.responseTimeout", Integer.toString(HinemosPropertyUtil
                .getHinemosPropertyNum("system.sun.rmi.transport.tcp.responseTimeout", Long.valueOf(10 * 1000))
                .intValue()));
        jmxc = JMXConnectorFactory.connect(url, env);
        MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

        JmxMasterInfo jmxMasterInfo = QueryUtil.getJmxMasterInfoPK(jmx.getMasterId());
        Object value = mbsc.getAttribute(new ObjectName(jmxMasterInfo.getObjectName()),
                jmxMasterInfo.getAttributeName());
        m_value = Double.parseDouble(
                searchTargetValue(value, Arrays.asList(KeyParser.parseKeys(jmxMasterInfo.getKeys())))
                        .toString());

        // ??
        if (m_convertFlg == ConvertValueConstant.TYPE_DELTA) {

            // ??
            MonitorJmxValue valueEntity = null;
            Double prevValue = 0d;
            Long prevDate = 0l;

            if (!m_isMonitorJob) {
                // ??
                // cache??
                valueEntity = MonitorJmxCache.getMonitorJmxValue(m_monitorId, facilityId);

                // ???
                prevValue = valueEntity.getValue();
                if (valueEntity.getGetDate() != null) {
                    prevDate = valueEntity.getGetDate();
                }
            } else {
                // ??
                valueEntity = new MonitorJmxValue(new MonitorJmxValuePK(m_monitorId, facilityId));
                if (m_prvData instanceof MonitorJmxValue) {
                    // ????
                    prevValue = ((MonitorJmxValue) m_prvData).getValue();
                    prevDate = ((MonitorJmxValue) m_prvData).getGetDate();
                }
            }

            // JMX????
            valueEntity.setValue(Double.valueOf(m_value));
            valueEntity.setGetDate(m_nodeDate);

            if (!m_isMonitorJob) {
                // ???ID?????
                if (m_monitor.getMonitorFlg())
                    MonitorJmxCache.update(m_monitorId, facilityId, valueEntity);

                int m_validSecond = HinemosPropertyUtil
                        .getHinemosPropertyNum("monitor.jmx.valid.second", Long.valueOf(15)).intValue();
                // ???????????
                int tolerance = (m_runInterval + m_validSecond) * 1000;

                if (prevDate > m_nodeDate - tolerance) {

                    // ??null???
                    if (prevValue == null) {
                        m_log.debug("collect() : prevValue is null");
                        m_prevNullchk = true;
                        return false;
                    }

                    m_value = m_value - prevValue;
                } else {
                    if (prevDate != 0l) {
                        DateFormat df = DateFormat.getDateTimeInstance();
                        df.setTimeZone(HinemosTime.getTimeZone());
                        String[] args = { df.format(new Date(prevDate)) };
                        m_message = MessageConstant.MESSAGE_TOO_OLD_TO_CALCULATE.getMessage(args);
                        return false;
                    } else {
                        // ???0??
                        m_nodeDate = 0l;
                    }
                }
            } else {
                m_value = m_value - prevValue;
                m_curData = valueEntity;
            }
        }

        m_log.debug(jmxMasterInfo.getName() + " : " + m_value + " " + jmxMasterInfo.getMeasure());

        result = true;
    } catch (NumberFormatException e) {
        m_log.info("collect() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
        String[] args = { Double.toString(m_value) };
        m_message = MessageConstant.MESSAGE_COULD_NOT_GET_NUMERIC_VALUE.getMessage(args);
        return false;
    } catch (Exception e) {
        String message = e.getMessage();
        if (message != null) {
            message = message.replaceAll("\n", "");
        }
        m_log.warn("fail to access JMXService : " + message + " (" + e.getClass().getName() + ")");
        exception = e;
    } finally {
        try {
            if (jmxc != null) {
                jmxc.close();
            }
        } catch (IOException e) {
            m_log.info("fail to close JMXService : " + e.getMessage() + " (" + e.getClass().getName() + ")");
            exception = e;
        }
    }

    return result;
}

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 ww w.j a  va2s  . 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;
}