Example usage for javax.management.remote JMXConnector getMBeanServerConnection

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

Introduction

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

Prototype

public MBeanServerConnection getMBeanServerConnection() throws IOException;

Source Link

Document

Returns an MBeanServerConnection object representing a remote MBean server.

Usage

From source file:gr.cslab.Metric_test.java

static void reportMetric(Metric ms, String host) {
    try {//from  w  w w. j a va2s  .  c  o  m
        //construct the service URL
        JMXConnector jmxc = hostConnections.get(host);
        if (jmxc == null) {
            System.out.println("Host " + host + " unavailable, attempting to connect");
            if (!connectHost(host))
                return;
        }
        MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
        Object rv = mbsc.getAttribute(ms.mbeanName, ms.attribute);
        if (verbose)
            System.out.println(host + ": " + ms.label + "=" + rv + " " + ms.units);
    } catch (IOException ex) {
        System.err.println("ERROR: problem in connection with" + host);
    } catch (MBeanException | ReflectionException ex) {
    } catch (AttributeNotFoundException ex) {
        System.err.println("ERROR: could not find attribute: " + ms.attribute + "in host: " + host);
    } catch (InstanceNotFoundException ex) {
        System.err.println("ERROR: instance was not found");
    }
}

From source file:com.neophob.sematrix.cli.PixConClientJmx.java

/**
 * /*w  w w  .  ja  v a 2  s.  c  om*/
 * @param hostname
 * @param port
 */
public static void queryJmxServer(String hostname, int port) {
    System.setSecurityManager(new java.rmi.RMISecurityManager());

    JMXServiceURL url;
    JMXConnector jmxc;
    hostname = hostname + ":" + port;
    System.out.println("Create an RMI connector client and connect it to the RMI connector server " + hostname);
    try {
        url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + hostname + "/jmxrmi");
        jmxc = JMXConnectorFactory.connect(url, null);

        System.out.println("Get an MBeanServerConnection...");
        MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
        printJmxStatus(mbsc);

        System.out.println("\nClose the connection to the server");
        jmxc.close();

    } catch (Exception e) {
        System.out.println("Error: JMX Error!");
        e.printStackTrace();
    }
}

From source file:com.cisco.oss.foundation.message.HornetQMessagingFactory.java

private static void printHQVersion(final String host, final String port) {
    LOGGER.info("HornetQ version: {}", VersionLoader.getVersion().getVersionName());

    Runnable getVersionFromServer = new Runnable() {
        @Override/*  w ww.  j  a va  2 s. c  o  m*/
        public void run() {
            try {

                // Step 9. Retrieve the ObjectName of the queue. This is used to identify the server resources to manage
                ObjectName on = ObjectNameBuilder.DEFAULT.getHornetQServerObjectName();

                // Step 10. Create JMX Connector to connect to the server's MBeanServer
                String url = MessageFormat.format("service:jmx:rmi://{0}/jndi/rmi://{0}:{1}/jmxrmi", host,
                        port == null ? "3900" : port);
                LOGGER.debug("HornetQ Server jmx url: {}", url);
                JMXConnector connector = JMXConnectorFactory.connect(new JMXServiceURL(url), new HashMap());

                // Step 11. Retrieve the MBeanServerConnection
                MBeanServerConnection mbsc = connector.getMBeanServerConnection();

                // Step 12. Create a JMSQueueControl proxy to manage the queue on the server
                JMSServerControl serverControl = MBeanServerInvocationHandler.newProxyInstance(mbsc, on,
                        JMSServerControl.class, false);

                String serverControlVersion = serverControl.getVersion();
                LOGGER.info("HornetQ Server version: {}", serverControlVersion);

            } catch (Exception e) {
                LOGGER.info("can't log server version. error is: {}", e.toString());
            }
        }
    };

    try {

        new Thread(getVersionFromServer).start();

    } catch (Exception e) {
        LOGGER.info("can't log server version. error is: {}", e.toString());
    }
}

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  w ww.jav  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:dk.netarkivet.common.utils.JMXUtils.java

/** Get the value of an attribute, closing the connector afterwards.  If you
 * wish to hold on to the connector, call
 * JMXUtils#executeCommand(MBeanServerConnection, String, String, String[])
 *
 * @param connector A one-shot connector object.
 * @param beanName The name of the bean to get an attribute from.
 * @param attribute The attribute to get.
 * @return Whatever the command returned.
 *///from  w w w  . j a v  a2s .  c o  m
public static Object getAttribute(JMXConnector connector, String beanName, String attribute) {
    ArgumentNotValid.checkNotNull(connector, "JMXConnector connector");
    ArgumentNotValid.checkNotNullOrEmpty(beanName, "String beanName");
    ArgumentNotValid.checkNotNullOrEmpty(attribute, "String attribute");

    MBeanServerConnection connection;
    try {
        connection = connector.getMBeanServerConnection();
    } catch (IOException e) {
        throw new IOFailure("Failure getting JMX connection", e);
    }
    try {
        return getAttribute(beanName, attribute, connection);
    } finally {
        try {
            connector.close();
        } catch (IOException e) {
            log.warn("Couldn't close connection to " + beanName, e);
        }
    }
}

From source file:com.continuent.tungsten.common.jmx.JmxManager.java

public static MBeanServerConnection getServerConnection(JMXConnector jmxConnector) throws Exception {
    return jmxConnector.getMBeanServerConnection();
}

From source file:org.hyperic.hq.product.jmx.MxUtil.java

public static Object invoke(Properties config, String objectName, String method, Object[] args, String[] sig)
        throws MetricUnreachableException, MetricNotFoundException, PluginException {

    JMXConnector connector = null;

    try {//from   w ww  .  ja v  a  2s.c  o  m
        connector = getMBeanConnector(config);
        MBeanServerConnection mServer = connector.getMBeanServerConnection();
        ObjectName obj = new ObjectName(objectName);
        MBeanInfo info = mServer.getMBeanInfo(obj);

        if (sig.length == 0) {
            MBeanUtil.OperationParams params = MBeanUtil.getOperationParams(info, method, args);
            if (params.isAttribute) {
                if (method.startsWith("set")) {
                    return setAttribute(mServer, obj, method, params.arguments[0]);
                } else {
                    return getAttribute(mServer, obj, method);
                }
            }
            sig = params.signature;
            args = params.arguments;
        }

        return mServer.invoke(obj, method, args, sig);
    } catch (RemoteException e) {
        throw unreachable(config, e);
    } catch (MalformedObjectNameException e) {
        throw invalidObjectName(objectName, e);
    } catch (InstanceNotFoundException e) {
        throw objectNotFound(objectName, e);
    } catch (ReflectionException e) {
        throw error(objectName, e, method);
    } catch (IntrospectionException e) {
        throw error(objectName, e, method);
    } catch (MBeanException e) {
        throw error(objectName, e, method);
    } catch (IOException e) {
        throw error(objectName, e, method);
    } finally {
        close(connector, objectName, method);
    }
}

From source file:com.spotify.reaper.cassandra.JmxProxy.java

/**
 * Connect to JMX interface on the given host and port.
 *
 * @param handler  Implementation of {@link RepairStatusHandler} to process incoming
 *                 notifications/*from ww  w.j  ava 2  s  .  c  o  m*/
 *                 of repair events.
 * @param host     hostname or ip address of Cassandra node
 * @param port     port number to use for JMX connection
 * @param username username to use for JMX authentication
 * @param password password to use for JMX authentication
 */
static JmxProxy connect(Optional<RepairStatusHandler> handler, String host, int port, String username,
        String password) throws ReaperException {
    ObjectName ssMbeanName;
    ObjectName cmMbeanName;
    JMXServiceURL jmxUrl;
    try {
        jmxUrl = new JMXServiceURL(String.format(JMX_URL, host, port));
        ssMbeanName = new ObjectName(SS_OBJECT_NAME);
        cmMbeanName = new ObjectName(CompactionManager.MBEAN_OBJECT_NAME);
    } catch (MalformedURLException | MalformedObjectNameException e) {
        LOG.error(String.format("Failed to prepare the JMX connection to %s:%s", host, port));
        throw new ReaperException("Failure during preparations for JMX connection", e);
    }
    try {
        Map<String, Object> env = new HashMap<String, Object>();
        if (username != null && password != null) {
            String[] creds = { username, password };
            env.put(JMXConnector.CREDENTIALS, creds);
        }
        JMXConnector jmxConn = JMXConnectorFactory.connect(jmxUrl, env);
        MBeanServerConnection mbeanServerConn = jmxConn.getMBeanServerConnection();
        Object ssProxy = JMX.newMBeanProxy(mbeanServerConn, ssMbeanName, StorageServiceMBean.class);
        String cassandraVersion = ((StorageServiceMBean) ssProxy).getReleaseVersion();
        if (cassandraVersion.startsWith("2.0") || cassandraVersion.startsWith("1.")) {
            ssProxy = JMX.newMBeanProxy(mbeanServerConn, ssMbeanName, StorageServiceMBean20.class);
        }

        CompactionManagerMBean cmProxy = JMX.newMBeanProxy(mbeanServerConn, cmMbeanName,
                CompactionManagerMBean.class);
        JmxProxy proxy = new JmxProxy(handler, host, jmxUrl, jmxConn, ssProxy, ssMbeanName, mbeanServerConn,
                cmProxy);
        // registering a listener throws bunch of exceptions, so we do it here rather than in the
        // constructor
        mbeanServerConn.addNotificationListener(ssMbeanName, proxy, null, null);
        LOG.debug("JMX connection to {} properly connected: {}", host, jmxUrl.toString());
        return proxy;
    } catch (IOException | InstanceNotFoundException e) {
        LOG.error("Failed to establish JMX connection to {}:{}", host, port);
        throw new ReaperException("Failure when establishing JMX connection", e);
    }
}

From source file:org.hyperic.hq.product.jmx.MxUtil.java

public static Object getValue(Properties config, String objectName, String attribute)
        throws MalformedURLException, MalformedObjectNameException, IOException, MBeanException,
        AttributeNotFoundException, InstanceNotFoundException, ReflectionException, PluginException {
    ObjectName objName = new ObjectName(objectName);
    JMXConnector connector = null;
    try {/* w w  w  .j  ava2s  . c  o  m*/
        connector = getCachedMBeanConnector(config);
        if (attribute.startsWith(STATS_PREFIX)) {
            return getJSR77Statistic(connector.getMBeanServerConnection(), objName, attribute);
        } else if (attribute.startsWith(COMPOSITE_PREFIX)) {
            return getCompositeMetric(connector.getMBeanServerConnection(), objName, attribute);
        } else {
            return connector.getMBeanServerConnection().getAttribute(objName, attribute);
        }
    } finally {
        close(connector);
    }
}

From source file:dk.netarkivet.common.utils.JMXUtils.java

/** Execute a single command, closing the connector afterwards.  If you
 * wish to hold on to the connector, call
 * JMXUtils#executeCommand(MBeanServerConnection, String, String, String[])
 *
 * @param connector A one-shot connector object.
 * @param beanName The name of the bean to execute a command on.
 * @param command The command to execute.
 * @param arguments The arguments to the command (all strings)
 * @return Whatever the command returned.
 *//*from ww  w .j ava 2  s .  com*/
public static Object executeCommand(JMXConnector connector, String beanName, String command,
        String... arguments) {
    ArgumentNotValid.checkNotNull(connector, "JMXConnector connector");
    ArgumentNotValid.checkNotNullOrEmpty(beanName, "String beanName");
    ArgumentNotValid.checkNotNullOrEmpty(command, "String command");
    ArgumentNotValid.checkNotNull(arguments, "String... arguments");

    MBeanServerConnection connection;
    try {
        connection = connector.getMBeanServerConnection();
    } catch (IOException e) {
        throw new IOFailure("Failure getting JMX connection", e);
    }
    try {
        return executeCommand(connection, beanName, command, arguments);
    } finally {
        try {
            connector.close();
        } catch (IOException e) {
            log.warn("Couldn't close connection to " + beanName, e);
        }
    }
}