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:de.unisb.cs.st.javalanche.mutation.runtime.jmx.MutationMxClient.java

public static boolean connect(int i) {
    JMXConnector jmxc = null;//from  w  w w . j a v a2s. c  o m
    JMXServiceURL url = null;

    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:com.all.services.ServiceConsole.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    try {//from   w  w  w  . j av  a 2s  .c  om
        LOG.info("Connecting to JMX service...");
        if (args.length < 2) {
            LOG.error("Incorrect usage of Ultrapeer console.\n\n Args should be 'command password [host]'");
            throw new IllegalArgumentException("Not enough agrugments to run.");
        }
        HashMap env = new HashMap();
        env.put("jmx.remote.credentials", new String[] { "controlRole", args[1] });
        String hostname = args.length > 2 ? args[2] : "";
        JMXConnector jmxc = JMXConnectorFactory
                .connect(new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + hostname + ":9999/jmxrmi"), env);
        ServiceMonitorMBean mbeanProxy = JMX.newMBeanProxy(jmxc.getMBeanServerConnection(),
                new ObjectName("com.all.services:type=ServiceMonitor"), ServiceMonitorMBean.class, true);
        handleCommand(mbeanProxy, args[0]);
        jmxc.close();
        LOG.info("Done.");
    } catch (Exception e) {
        LOG.error(e, e);
    }
}

From source file:gr.cslab.Metric_test.java

static boolean connectHost(String hostName) {
    try {/*  ww  w  .  j  av a  2  s .  co  m*/
        String url = "service:jmx:rmi:///jndi/rmi://" + hostName + ":" + port + "/jmxrmi";
        System.out.println("Using host: " + hostName + " (" + url + ")");
        JMXServiceURL serviceUrl = new JMXServiceURL(url);
        JMXConnector jmxc = JMXConnectorFactory.connect(serviceUrl, null);
        hostConnections.put(hostName, jmxc);
    } catch (MalformedURLException ex) {
        System.err.println("ERROR: malformed url");
        return false;
    } catch (IOException ex) {
        System.err.println("ERROR: could not connect to: " + hostName);
        hostConnections.remove(hostName);
        return false;
    }
    return true;
}

From source file:com.fusesource.forge.jmstest.probe.jmx.JMXConnectionFactory.java

public JMXConnector getConnector() {

    JMXConnector connector = null;

    try {//from   w  w  w.  ja  v  a 2s .  c  o m
        if (connector == null) {
            if (username != null && password != null) {
                Map<String, String[]> m = new HashMap<String, String[]>();
                m.put(JMXConnector.CREDENTIALS, new String[] { username, password });
                connector = JMXConnectorFactory.connect(new JMXServiceURL(url), m);
            } else {
                connector = JMXConnectorFactory.connect(new JMXServiceURL(url));
            }
        }
    } catch (IOException ioe) {
        // TODO: do this right
        log().error("Error connecting to JMX server ", ioe);
    }
    return connector;
}

From source file:com.riotgames.mondev.JMXDiscovery.java

protected String discoverMBeans(String key) throws Exception {
    try {/*  ww w.j  a v  a2 s. co m*/
        HashMap<String, String[]> env = null;
        if (null != username && null != password) {
            env = new HashMap<String, String[]>();
            env.put(JMXConnector.CREDENTIALS, new String[] { username, password });
        }

        jmxc = JMXConnectorFactory.connect(jmxServerUrl, env);
        mbsc = jmxc.getMBeanServerConnection();

        ObjectName filter = new ObjectName(key);
        JSONArray beanList = new JSONArray();
        JSONObject mapping = new JSONObject();

        Set beans = mbsc.queryMBeans(filter, null);
        for (Object obj : beans) {
            JSONObject bean = new JSONObject();
            ObjectName beanName;

            // Return the ObjectName instance correctly for both Objects and Instances
            if (obj instanceof ObjectName)
                beanName = (ObjectName) obj;
            else if (obj instanceof ObjectInstance)
                beanName = ((ObjectInstance) obj).getObjectName();
            else
                throw new RuntimeException("Unexpected object type: " + obj);

            // Build the standing info, description and object path
            MBeanInfo mbi = mbsc.getMBeanInfo(beanName);
            bean.put("{#JMXDESC}", mbi.getDescription());
            bean.put("{#JMXOBJ}", beanName.getCanonicalName());

            // Build a list of all the MBean properties as {#PROP<NAME>}
            Hashtable<String, String> pt = beanName.getKeyPropertyList();
            for (Map.Entry<String, String> prop : pt.entrySet())
                bean.put(String.format("{#PROP%s}", prop.getKey().toUpperCase()), prop.getValue());

            beanList.put(bean);
        }

        mapping.put("data", beanList);
        return mapping.toString();
    } catch (Exception e) {
        JSONArray data = new JSONArray();
        JSONObject out = new JSONObject();
        out.put("data", data);

        return out.toString();
    } finally {
        try {
            if (null != jmxc)
                jmxc.close();
        } catch (java.io.IOException exception) {
        }

        jmxc = null;
        mbsc = null;
    }
}

From source file:org.springframework.jmx.access.ConnectorDelegate.java

/**
 * Connects to the remote {@code MBeanServer} using the configured {@code JMXServiceURL}:
 * to the specified JMX service, or to a local MBeanServer if no service URL specified.
 * @param serviceUrl the JMX service URL to connect to (may be {@code null})
 * @param environment the JMX environment for the connector (may be {@code null})
 * @param agentId the local JMX MBeanServer's agent id (may be {@code null})
 *//*from w w  w.  j  a  v  a2  s .c o  m*/
public MBeanServerConnection connect(@Nullable JMXServiceURL serviceUrl, @Nullable Map<String, ?> environment,
        @Nullable String agentId) throws MBeanServerNotFoundException {

    if (serviceUrl != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Connecting to remote MBeanServer at URL [" + serviceUrl + "]");
        }
        try {
            this.connector = JMXConnectorFactory.connect(serviceUrl, environment);
            return this.connector.getMBeanServerConnection();
        } catch (IOException ex) {
            throw new MBeanServerNotFoundException(
                    "Could not connect to remote MBeanServer [" + serviceUrl + "]", ex);
        }
    } else {
        logger.debug("Attempting to locate local MBeanServer");
        return JmxUtils.locateMBeanServer(agentId);
    }
}

From source file:org.springside.modules.utils.jmx.JmxClientTemplate.java

/**
 * JMX Server.//w w  w.  j av  a2 s.  co  m
 */

private void initConnector(final String serviceUrl, final String userName, final String passwd)
        throws IOException {
    JMXServiceURL url = new JMXServiceURL(serviceUrl);

    boolean hasCredentlals = StringUtils.isNotBlank(userName);
    if (hasCredentlals) {
        Map environment = Collections.singletonMap(JMXConnector.CREDENTIALS, new String[] { userName, passwd });
        connector = JMXConnectorFactory.connect(url, environment);
    } else {
        connector = JMXConnectorFactory.connect(url);
    }

    connection = connector.getMBeanServerConnection();
    connected.set(true);
}

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

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

    try {/*from   www .ja va 2 s .c om*/
        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:com.rosy.bill.utils.jmx.JmxClientTemplate.java

/**
 * JMX Server.//from   www .  j ava2  s  .  c  o m
 */
@SuppressWarnings("unchecked")
private void initConnector(final String serviceUrl, final String userName, final String passwd)
        throws IOException {
    JMXServiceURL url = new JMXServiceURL(serviceUrl);

    boolean hasCredentlals = StringUtils.isNotBlank(userName);
    if (hasCredentlals) {
        Map environment = Collections.singletonMap(JMXConnector.CREDENTIALS, new String[] { userName, passwd });
        connector = JMXConnectorFactory.connect(url, environment);
    } else {
        connector = JMXConnectorFactory.connect(url);
    }

    connection = connector.getMBeanServerConnection();
    connected.set(true);
}

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

public static JMXConnector initConnection(String hostName, int port, String userName, String password)
        throws MalformedURLException, IOException {

    JMXServiceURL serviceUrl = new JMXServiceURL(DEFAULT_PROTO, hostName, port,
            JNDI_PREFIX + DomainRuntimeServiceMBean.MBEANSERVER_JNDI_NAME);
    HashMap<String, String> h = new HashMap<String, String>();
    h.put(Context.SECURITY_PRINCIPAL, userName);
    h.put(Context.SECURITY_CREDENTIALS, password);
    h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, DEFAULT_PROTO_PROVIDER_PACKAGES);
    return JMXConnectorFactory.connect(serviceUrl, h);

}