Example usage for javax.management MBeanServerConnection queryMBeans

List of usage examples for javax.management MBeanServerConnection queryMBeans

Introduction

In this page you can find the example usage for javax.management MBeanServerConnection queryMBeans.

Prototype

public Set<ObjectInstance> queryMBeans(ObjectName name, QueryExp query) throws IOException;

Source Link

Document

Gets MBeans controlled by the MBean server.

Usage

From source file:com.appdynamics.monitors.muleesb.JMXUtil.java

public static Set<ObjectInstance> queryMbeans(MBeanServerConnection connection, String mbeanMatcher)
        throws IOException, MalformedObjectNameException {
    Set<ObjectInstance> mBeans = connection.queryMBeans(new ObjectName(mbeanMatcher), null);
    return mBeans;
}

From source file:com.linkedin.d2.balancer.util.LoadBalancerClientCli.java

public static void resetTogglingStores(String host, boolean enabled) throws Exception {

    MonitoredHost _host = MonitoredHost.getMonitoredHost(new HostIdentifier(host));

    for (Object pidObj : _host.activeVms()) {
        int pid = (Integer) pidObj;

        System.out.println("checking pid: " + pid);

        JMXServiceURL jmxUrl = null;
        com.sun.tools.attach.VirtualMachine vm = com.sun.tools.attach.VirtualMachine.attach(pid + "");

        try {/*from w  w  w . j  av  a 2  s . c o  m*/
            // get the connector address
            String connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
            // establish connection to connector server
            if (connectorAddress != null) {
                jmxUrl = new JMXServiceURL(connectorAddress);
            }
        } finally {
            vm.detach();
        }

        if (jmxUrl != null) {
            System.out.println("got jmx url: " + jmxUrl);

            // connect to jmx
            JMXConnector connector = JMXConnectorFactory.connect(jmxUrl);

            connector.connect();

            MBeanServerConnection mbeanServer = connector.getMBeanServerConnection();

            // look for all beans in the d2 name space
            Set<ObjectInstance> objectInstances = mbeanServer.queryMBeans(new ObjectName("com.linkedin.d2:*"),
                    null);

            for (ObjectInstance objectInstance : objectInstances) {
                System.err.println("checking object: " + objectInstance.getObjectName());

                // if we've found a toggling store, then toggle it
                if (objectInstance.getObjectName().toString().endsWith("TogglingStore")) {
                    System.out.println("found toggling zk store, so toggling to: " + enabled);

                    mbeanServer.invoke(objectInstance.getObjectName(), "setEnabled", new Object[] { enabled },
                            new String[] { "boolean" });
                }
            }
        } else {
            System.out.println("pid is not a jmx process: " + pid);
        }
    }
}

From source file:com.lmig.cf.metrics.opsmetrics.OpsMetrics.java

private List<JmxMetric> searchForMetrics(MBeanServerConnection connection, ObjectName objectName)
        throws Exception {
    List<JmxMetric> metrics = new ArrayList<JmxMetric>();
    Set<ObjectInstance> matchingObjects = connection.queryMBeans(objectName, null);
    for (ObjectInstance object : matchingObjects) {
        List<String> attributes = getAttributeNames(connection, object);
        attributes.stream().filter(attr -> !blacklisted(attr))
                .filter(attr -> metricValueIsNumber(connection, object, attr))
                .map(attr -> new JmxMetric(object, attr, getAttributeValue(connection, object, attr)))
                .forEach(metrics::add);//ww  w.ja  va2s . c  om
    }
    return metrics;
}

From source file:com.paxxis.cornerstone.messaging.service.shell.ServiceShell.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void doShutdown(String[] vals) throws Exception {
    StringBuilder buf = new StringBuilder("service:jmx:rmi://localhost/jndi/rmi://localhost:");
    String serviceName = vals[0];

    buf.append(vals[1]).append("/").append(serviceName);
    String serviceUrl = buf.toString();

    JMXServiceURL url = new JMXServiceURL(serviceUrl);
    JMXConnector jmxc = null;/*from   w  w w. j a  v a2s .c  o  m*/
    try {
        jmxc = JMXConnectorFactory.connect(url, null);

    } catch (Exception e) {
        throw new Exception("Unable to establish JMX connection at " + serviceUrl);
    }

    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

    Set<ObjectInstance> mBeansSet = mbsc.queryMBeans(new ObjectName(serviceName + ":*"), null);
    List<IServiceController> serviceProxies = new ArrayList<IServiceController>();
    Class serviceBusInterface = Class.forName(IServiceBusManager.class.getName());
    Class serviceControllerInterface = Class.forName(IServiceController.class.getName());

    for (ObjectInstance mBeanObject : mBeansSet) {
        ObjectName mbeanName = mBeanObject.getObjectName();
        Class mbeanClass = Class.forName(mBeanObject.getClassName());
        if (serviceBusInterface.isAssignableFrom(mbeanClass)) {
            IServiceBusManager requestConnector = JMX.newMBeanProxy(mbsc, mbeanName, IServiceBusManager.class,
                    true);
            System.out.print(mbeanName + " terminating....");
            requestConnector.disconnect();
            while (true) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ie) {

                }

                if (!requestConnector.isConnected()) {
                    break;
                }
            }
            System.out.println(" Done");
        } else if (serviceControllerInterface.isAssignableFrom(mbeanClass)) {
            // save off the service proxies to make sure we disconnect
            // all connectors before shutting down the service itself
            IServiceController mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName, IServiceController.class, true);
            serviceProxies.add(mbeanProxy);
        }
    }

    for (IServiceController mbeanProxy : serviceProxies) {
        try {
            mbeanProxy.shutdown();
        } catch (UndeclaredThrowableException ex) {
        }
    }

    System.out.println("Service terminated");
}

From source file:com.stumbleupon.hbaseadmin.JMXQuery.java

public String execute(String hostport) throws Exception {
    Iterator i;/*w w  w . j a v  a 2 s  .c o  m*/
    String result = "";
    final JMXServiceURL rmiurl = new JMXServiceURL(
            "service:jmx:rmi://" + hostport + "/jndi/rmi://" + hostport + "/jmxrmi");
    final JMXConnector jmxc = JMXConnectorFactory.connect(rmiurl, getCredentials(password_file));
    try {
        final MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

        final ObjectName objName = new ObjectName(beanName);
        final Set beans = mbsc.queryMBeans(objName, null);

        if (beans.size() == 0) {
            logger.warn(objName.getCanonicalName() + " is not a registered bean");
        } else if (beans.size() == 1) {
            final ObjectInstance instance = (ObjectInstance) beans.iterator().next();
            result = doBean(mbsc, instance, command);
        } else {

            for (i = beans.iterator(); i.hasNext();) {
                final Object obj = i.next();

                if (obj instanceof ObjectName)
                    System.out.println(((ObjectName) obj).getCanonicalName());
                else if (obj instanceof ObjectInstance) {
                    System.out.println(((ObjectInstance) obj).getObjectName().getCanonicalName());
                } else
                    logger.error("Unexpected object type: " + obj);
            }
        }
    } finally {
        jmxc.close();
    }
    return result;
}

From source file:com.springsource.hq.plugin.tcserver.plugin.TomcatMeasurementPlugin.java

private long getTotalGarbageCollectionTime(MBeanServerConnection connection)
        throws MetricUnreachableException, MetricNotFoundException, PluginException {

    long totalGcTimeMillis = 0;

    try {/*from www.j a v  a2  s.  c  o m*/

        // Use of the MXBean replaced by plain old JMX query for TCS-71
        //
        // Set<ObjectName> garbageCollectors = connection.queryNames(
        // new ObjectName("java.lang:type=GarbageCollector,*"), null);
        // for (ObjectName garbageCollectorName : garbageCollectors) {
        // GarbageCollectorMXBean garbageCollector = getGarbageCollectorMXBean(
        // connection, garbageCollectorName);
        // long collectionTime = garbageCollector.getCollectionTime();

        ObjectName gcObjName = new ObjectName("java.lang:type=GarbageCollector,*");
        Set<ObjectInstance> garbageCollectors = connection.queryMBeans(gcObjName, null);

        for (ObjectInstance instance : garbageCollectors) {
            ObjectName instanceName = instance.getObjectName();
            Long l = (Long) connection.getAttribute(instance.getObjectName(), "CollectionTime");
            long collectionTime = l.longValue();
            LOGGER.debug(instanceName + "::CollectionTime=" + collectionTime);

            if (collectionTime > -1) {
                totalGcTimeMillis += collectionTime;
            }
        }
    } catch (MalformedObjectNameException e) {
        throw new MetricInvalidException("Error querying for GarbageCollector MBeans: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new MetricUnreachableException("Error querying for GarbageCollector MBeans:" + e.getMessage(), e);
    } catch (AttributeNotFoundException e) {
        throw new MetricNotFoundException("Error querying for GarbageCollector MBeans:" + e.getMessage(), e);
    } catch (InstanceNotFoundException e) {
        throw new MetricNotFoundException("Error querying for GarbageCollector MBeans:" + e.getMessage(), e);
    } catch (MBeanException e) {
        throw new PluginException("Error querying for GarbageCollector MBeans:" + e.getMessage(), e);
    } catch (ReflectionException e) {
        throw new PluginException("Error querying for GarbageCollector MBeans:" + e.getMessage(), e);
    } catch (NullPointerException e) {
        throw new PluginException("Error querying for GarbageCollector MBeans:" + e.getMessage(), e);
    }

    return totalGcTimeMillis;
}

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

/**
 * Read the attributes from Hadoop->HBase->Master->Balancer in JMX
 * @throws IOException //from ww  w  .  j  av a  2  s  . c o m
 */
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:org.helios.collector.jmx.connection.AbstractMBeanServerConnectionFactory.java

/**
 * Queries a set of MBean ObjectInstances from the passed ObjectName and Query expression
 * @param objectNaNames /*from  w  w  w .  ja  v  a  2  s . co  m*/
 * @param query
 * @return
 * @throws IOException
 */
@Override
@ManagedOperation
public Set<ObjectInstance> queryMBeans(ObjectName objectName, QueryExp query) throws IOException {
    validateConn();
    MBeanServerConnection conn = null;
    try {
        conn = getPooledConnection();
        return conn.queryMBeans(objectName, query);
    } catch (MBeanServerConnectionFactoryException e) {
        throw new RuntimeException("Failed to get pooled connection", e);
    } finally {
        try {
            this.returnPooledConnection(conn);
        } catch (Exception e) {
            log.debug(e.getMessage());
        }
    }
}

From source file:org.opennms.features.jmxconfiggenerator.jmxconfig.JmxDatacollectionConfiggenerator.java

public JmxDatacollectionConfig generateJmxConfigModel(MBeanServerConnection mBeanServerConnection,
        String serviceName, Boolean runStandardVmBeans, Boolean runWritableMBeans,
        Map<String, String> dictionary) {

    logger.debug("Startup values: \n serviceName: " + serviceName + "\n runStandardVmBeans: "
            + runStandardVmBeans + "\n runWritableMBeans: " + runWritableMBeans + "\n dictionary" + dictionary);
    nameCutter.setDictionary(dictionary);
    JmxDatacollectionConfig xmlJmxDatacollectionConfig = xmlObjectFactory.createJmxDatacollectionConfig();
    JmxCollection xmlJmxCollection = xmlObjectFactory.createJmxCollection();

    xmlJmxCollection.setName("JSR160-" + serviceName);
    xmlJmxCollection.setRrd(rrd);/*from  w  w w.  ja va2s  .  co m*/
    xmlJmxDatacollectionConfig.getJmxCollection().add(xmlJmxCollection);
    xmlJmxCollection.setMbeans(xmlObjectFactory.createMbeans());

    if (runStandardVmBeans) {
        ignores.clear();
    } else {
        ignores.addAll(standardVmBeans);
    }

    try {
        String[] domains = mBeanServerConnection.getDomains();
        logger.info("Found " + domains.length + " domains");
        logger.info("domains: " + Arrays.toString(domains));
        for (String domainName : domains) {

            // just domains that are relevant for the service
            if (!ignores.contains(domainName)) {
                logger.info("domain: " + domainName);

                // for all mBeans of the actual domain
                for (ObjectInstance jmxObjectInstance : mBeanServerConnection
                        .queryMBeans(new ObjectName(domainName + ":*"), null)) {
                    Mbean xmlMbean = xmlObjectFactory.createMbean();
                    xmlMbean.setObjectname(jmxObjectInstance.getObjectName().toString());
                    String typeAndOthers = StringUtils
                            .substringAfterLast(jmxObjectInstance.getObjectName().getCanonicalName(), "=");
                    xmlMbean.setName(domainName + "." + typeAndOthers);

                    logger.debug("\t" + jmxObjectInstance.getObjectName());

                    MBeanInfo jmxMbeanInfo;
                    try {
                        jmxMbeanInfo = mBeanServerConnection.getMBeanInfo(jmxObjectInstance.getObjectName());
                    } catch (InstanceNotFoundException e) {
                        logger.error("InstanceNotFoundException skipping MBean '{}' message: '{}'",
                                jmxObjectInstance.getObjectName(), e.getMessage());
                        continue;
                    } catch (IntrospectionException e) {
                        logger.error("IntrospectionException skipping MBean '{}' message: '{}'",
                                jmxObjectInstance.getObjectName(), e.getMessage());
                        continue;
                    } catch (ReflectionException e) {
                        logger.error("ReflectionException skipping MBean '{}' message: '{}'",
                                jmxObjectInstance.getObjectName(), e.getMessage());
                        continue;
                    } catch (Throwable e) {
                        logger.error(
                                "problem during remote call to get MBeanInfo for '{}' skipping this MBean. Message '{}'",
                                jmxObjectInstance.getObjectName(), e.getMessage());
                        continue;
                    }

                    logger.debug("--- Attributes for " + jmxObjectInstance.getObjectName());

                    for (MBeanAttributeInfo jmxBeanAttributeInfo : jmxMbeanInfo.getAttributes()) {

                        // process just readable mbeans
                        if (jmxBeanAttributeInfo.isReadable()) {
                            // precess writable mbeans if run writable
                            // mbeans is set
                            if (!jmxBeanAttributeInfo.isWritable() || runWritableMBeans) {

                                logger.debug("Check mBean: '{}', attribute: '{}'",
                                        jmxObjectInstance.getObjectName().toString(),
                                        jmxBeanAttributeInfo.getName());
                                logger.debug("isWritable: '{}', type: '{}'", jmxBeanAttributeInfo.isWritable(),
                                        jmxBeanAttributeInfo.getType());

                                // check for CompositeData
                                if ("javax.management.openmbean.CompositeData"
                                        .equals(jmxBeanAttributeInfo.getType())) {
                                    logger.error("actual mBean: '{}'", jmxObjectInstance.getObjectName());
                                    CompAttrib compAttrib = createCompAttrib(mBeanServerConnection,
                                            jmxObjectInstance, jmxBeanAttributeInfo);
                                    if (compAttrib != null) {
                                        logger.debug("xmlMbean got CompAttrib");
                                        xmlMbean.getCompAttrib().add(compAttrib);
                                    }
                                }

                                if (numbers.contains(jmxBeanAttributeInfo.getType())) {
                                    Attrib xmlJmxAttribute = createAttr(jmxBeanAttributeInfo);
                                    logger.debug("Added MBean: '{}' Added attribute: '{}'",
                                            xmlMbean.getObjectname(),
                                            xmlJmxAttribute.getName() + " as " + xmlJmxAttribute.getAlias());
                                    xmlMbean.getAttrib().add(xmlJmxAttribute);
                                }
                            }
                        }
                    }

                    if (xmlMbean.getAttrib().size() > 0 || xmlMbean.getCompAttrib().size() > 0) {
                        xmlJmxCollection.getMbeans().getMbean().add(xmlMbean);
                    } else {
                        logger.debug("mbean: " + xmlMbean.getName() + " has no relavant attributes.");
                    }
                }
            } else {
                logger.debug("ignored: " + domainName);
            }
        }

    } catch (MalformedObjectNameException e) {
        logger.error("MalformedObjectNameException '{}'", e.getMessage());
    } catch (IOException e) {
        logger.error("IOException '{}'", e.getMessage());
    }
    logger.debug("finish collection!");
    return xmlJmxDatacollectionConfig;
}

From source file:org.opennms.jmxconfiggenerator.jmxconfig.JmxDatacollectionConfiggenerator.java

public JmxDatacollectionConfig generateJmxConfigModel(MBeanServerConnection mBeanServerConnection,
        String serviceName, Boolean runStandardVmBeans, Boolean runWritableMBeans,
        Map<String, String> dictionary) {

    logger.debug("Startup values: \n serviceName: " + serviceName + "\n runStandardVmBeans: "
            + runStandardVmBeans + "\n runWritableMBeans: " + runWritableMBeans + "\n dictionary" + dictionary);
    nameCutter.setDictionary(dictionary);
    JmxDatacollectionConfig xmlJmxDatacollectionConfig = xmlObjectFactory.createJmxDatacollectionConfig();
    JmxCollection xmlJmxCollection = xmlObjectFactory.createJmxCollection();

    xmlJmxCollection.setName("JSR160-" + serviceName);
    xmlJmxCollection.setRrd(rrd);/* ww  w. ja  va2  s .  c om*/
    xmlJmxDatacollectionConfig.getJmxCollection().add(xmlJmxCollection);
    xmlJmxCollection.setMbeans(xmlObjectFactory.createMbeans());

    if (runStandardVmBeans) {
        ignores.clear();
    } else {
        ignores.addAll(standardVmBeans);
    }

    try {
        for (String domainName : mBeanServerConnection.getDomains()) {

            // just domains that are relevant for the service
            if (!ignores.contains(domainName)) {
                logger.debug("domain: " + domainName);

                // for all mBeans of the actual domain
                for (ObjectInstance jmxObjectInstance : mBeanServerConnection
                        .queryMBeans(new ObjectName(domainName + ":*"), null)) {
                    Mbean xmlMbean = xmlObjectFactory.createMbean();
                    xmlMbean.setObjectname(jmxObjectInstance.getObjectName().toString());
                    String typeAndOthers = StringUtils
                            .substringAfterLast(jmxObjectInstance.getObjectName().getCanonicalName(), "=");
                    xmlMbean.setName(domainName + "." + typeAndOthers);

                    logger.debug("\t" + jmxObjectInstance.getObjectName());

                    MBeanInfo jmxMbeanInfo;
                    try {
                        jmxMbeanInfo = mBeanServerConnection.getMBeanInfo(jmxObjectInstance.getObjectName());
                    } catch (InstanceNotFoundException e) {
                        logger.error("InstanceNotFoundException skipping MBean '{}' message: '{}'",
                                jmxObjectInstance.getObjectName(), e.getMessage());
                        continue;
                    } catch (IntrospectionException e) {
                        logger.error("IntrospectionException skipping MBean '{}' message: '{}'",
                                jmxObjectInstance.getObjectName(), e.getMessage());
                        continue;
                    } catch (ReflectionException e) {
                        logger.error("ReflectionException skipping MBean '{}' message: '{}'",
                                jmxObjectInstance.getObjectName(), e.getMessage());
                        continue;
                    } catch (Throwable e) {
                        logger.error(
                                "problem during remote call to get MBeanInfo for '{}' skipping this MBean. Message '{}'",
                                jmxObjectInstance.getObjectName(), e.getMessage());
                        continue;
                    }

                    logger.debug("--- Attributes for " + jmxObjectInstance.getObjectName());

                    for (MBeanAttributeInfo jmxBeanAttributeInfo : jmxMbeanInfo.getAttributes()) {

                        // process just readable mbeans
                        if (jmxBeanAttributeInfo.isReadable()) {
                            // precess writable mbeans if run writable mbeans is set
                            if (!jmxBeanAttributeInfo.isWritable() || runWritableMBeans) {

                                logger.debug("Check mBean: '{}', attribute: '{}'",
                                        jmxObjectInstance.getObjectName().toString(),
                                        jmxBeanAttributeInfo.getName());
                                logger.debug("isWritable: '{}', type: '{}'", jmxBeanAttributeInfo.isWritable(),
                                        jmxBeanAttributeInfo.getType());

                                // check for CompositeData
                                if ("javax.management.openmbean.CompositeData"
                                        .equals(jmxBeanAttributeInfo.getType())) {
                                    logger.error("actual mBean: '{}'", jmxObjectInstance.getObjectName());
                                    CompAttrib compAttrib = createCompAttrib(mBeanServerConnection,
                                            jmxObjectInstance, jmxBeanAttributeInfo);
                                    if (compAttrib != null) {
                                        logger.debug("xmlMbean got CompAttrib");
                                        xmlMbean.getCompAttrib().add(compAttrib);
                                    }
                                }

                                if (numbers.contains(jmxBeanAttributeInfo.getType())) {
                                    Attrib xmlJmxAttribute = createAttr(jmxBeanAttributeInfo);
                                    logger.debug("Added MBean: '{}' Added attribute: '{}'",
                                            xmlMbean.getObjectname(),
                                            xmlJmxAttribute.getName() + " as " + xmlJmxAttribute.getAlias());
                                    xmlMbean.getAttrib().add(xmlJmxAttribute);
                                }
                            }
                        }
                    }

                    if (xmlMbean.getAttrib().size() > 0 || xmlMbean.getCompAttrib().size() > 0) {
                        xmlJmxCollection.getMbeans().getMbean().add(xmlMbean);
                    } else {
                        logger.debug("mbean: " + xmlMbean.getName() + " has no relavant attributes.");
                    }
                }
            } else {
                logger.debug("ignored: " + domainName);
            }
        }

    } catch (MalformedObjectNameException e) {
        logger.error("MalformedObjectNameException '{}'", e.getMessage());
    } catch (IOException e) {
        logger.error("IOException '{}'", e.getMessage());
    }

    return xmlJmxDatacollectionConfig;
}