Example usage for javax.management MBeanServer queryMBeans

List of usage examples for javax.management MBeanServer queryMBeans

Introduction

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

Prototype

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

Source Link

Usage

From source file:com.googlecode.psiprobe.controllers.threads.ThreadStackController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    long threadID = ServletRequestUtils.getLongParameter(request, "id", -1);
    String threadName = ServletRequestUtils.getStringParameter(request, "name", null);

    List stack = null;/*  w  w  w  .j  a v  a  2s.  c  o m*/
    MBeanServer mBeanServer = new Registry().getMBeanServer();
    ObjectName threadingOName = new ObjectName("java.lang:type=Threading");

    if (threadID == -1 && threadName != null) {
        // find thread by name
        long[] allIds = (long[]) mBeanServer.getAttribute(threadingOName, "AllThreadIds");
        for (int i = 0; i < allIds.length; i++) {
            CompositeData cd = (CompositeData) mBeanServer.invoke(threadingOName, "getThreadInfo",
                    new Object[] { new Long(allIds[i]) }, new String[] { "long" });
            String name = JmxTools.getStringAttr(cd, "threadName");
            if (threadName.equals(name)) {
                threadID = allIds[i];
                break;
            }
        }
    }

    if (mBeanServer.queryMBeans(threadingOName, null) != null && threadID != -1) {

        CompositeData cd = (CompositeData) mBeanServer.invoke(threadingOName, "getThreadInfo",
                new Object[] { new Long(threadID), new Integer(stackElementCount) },
                new String[] { "long", "int" });
        if (cd != null) {
            CompositeData[] elements = (CompositeData[]) cd.get("stackTrace");
            threadName = JmxTools.getStringAttr(cd, "threadName");

            stack = new ArrayList(elements.length);

            for (int i = 0; i < elements.length; i++) {
                CompositeData cd2 = elements[i];
                ThreadStackElement tse = new ThreadStackElement();
                tse.setClassName(JmxTools.getStringAttr(cd2, "className"));
                tse.setFileName(JmxTools.getStringAttr(cd2, "fileName"));
                tse.setMethodName(JmxTools.getStringAttr(cd2, "methodName"));
                tse.setLineNumber(JmxTools.getIntAttr(cd2, "lineNumber", -1));
                tse.setNativeMethod(JmxTools.getBooleanAttr(cd2, "nativeMethod"));
                stack.add(tse);
            }
        }
    }

    return new ModelAndView(getViewName(), "stack", stack).addObject("threadName", threadName);
}

From source file:org.acmsl.commons.utils.jmx.MBeanRegistrator.java

/**
 * Obtains a reference to the MBean server. If at least one
 * MBean server already exists, then a reference to that MBean
 * server is returned. Otherwise a new instance is created.
 * @param cachedInstance the cached instance, if any.
 * @return such server.//  ww w  .  ja  v a  2  s  .  c o m
 */
@Nullable
protected MBeanServer getMBeanServer(@Nullable final MBeanServer cachedInstance) {
    MBeanServer result = cachedInstance;

    if (result == null) {
        @NotNull
        final List<MBeanServer> mbeanServers = MBeanServerFactory.findMBeanServer(null);

        @NotNull
        final Iterator<MBeanServer> serverIterator = mbeanServers.iterator();

        while (serverIterator.hasNext()) {
            @NotNull
            final MBeanServer mbeanServer = serverIterator.next();

            mbeanServer.queryMBeans(null, null);
        }

        result = (mbeanServers.size() > 0) ? mbeanServers.get(0) : MBeanServerFactory.createMBeanServer();

        setMBeanServer(result);
    }

    return result;
}

From source file:org.apache.synapse.commons.snmp.SNMPAgent.java

@Override
protected void registerManagedObjects() {
    log.info("Initializing Synapse SNMP MIB");
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    Set<ObjectInstance> instances = mbs.queryMBeans(null, null);

    try {//from  w w w .  j ava 2s .co m
        for (ObjectInstance instance : instances) {
            ObjectName objectName = instance.getObjectName();
            if (objectName.getDomain().equals("org.apache.synapse")) {
                String oidString = SynapseMIBUtils.getOID(objectName);
                if (oidString == null) {
                    continue;
                }

                MBeanInfo info = mbs.getMBeanInfo(objectName);
                MBeanAttributeInfo[] attributes = info.getAttributes();
                List<String> attributeNames = new ArrayList<String>();
                List<String> mapAttributes = new ArrayList<String>();
                for (MBeanAttributeInfo attributeInfo : attributes) {
                    attributeNames.add(attributeInfo.getName());
                    if (Map.class.getName().equals(attributeInfo.getType())) {
                        mapAttributes.add(attributeInfo.getName());
                    }
                }
                Collections.sort(attributeNames);

                doRegister(attributeNames, mapAttributes, oidString, objectName);
            }
        }
    } catch (Exception e) {
        log.error("Error while initializing the SNMP MIB", e);
    }
}

From source file:org.jboss.web.tomcat.tc5.Tomcat5.java

public void stopService() throws Exception {

    String objectNameS = catalinaDomain + ":type=server";
    ObjectName objectName = new ObjectName(objectNameS);

    server.invoke(objectName, "stop", new Object[] {}, new String[] {});

    server.invoke(objectName, "destroy", new Object[] {}, new String[] {});

    server.unregisterMBean(objectName);//from ww w  .  j ava2 s  .  c  om

    MBeanServer server2 = server;

    // deregister with MainDeployer
    mainDeployer.removeDeployer(thisProxy);

    // Unregister any remaining jboss.web or Catalina MBeans
    ObjectName queryObjectName = new ObjectName(catalinaDomain + ":*");
    Iterator iterator = server2.queryMBeans(queryObjectName, null).iterator();
    while (iterator.hasNext()) {
        ObjectInstance oi = (ObjectInstance) iterator.next();
        ObjectName toRemove = oi.getObjectName();
        // Exception: Don't unregister the service right now
        if (!"WebServer".equals(toRemove.getKeyProperty("service"))) {
            if (server2.isRegistered(toRemove)) {
                server2.unregisterMBean(toRemove);
            }
        }
    }
    queryObjectName = new ObjectName("Catalina:*");
    iterator = server2.queryMBeans(queryObjectName, null).iterator();
    while (iterator.hasNext()) {
        ObjectInstance oi = (ObjectInstance) iterator.next();
        ObjectName name = oi.getObjectName();
        server2.unregisterMBean(name);
    }

}

From source file:org.nuxeo.ecm.webapp.seam.NuxeoSeamFlusher.java

protected void invalidateWebSessions() throws IOException {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    ObjectName name;/*from  ww w.java2  s  . co m*/
    try {
        name = new ObjectName("Catalina:type=Manager,context=/nuxeo,host=*");
    } catch (MalformedObjectNameException e) {
        throw new IOException(e);
    }
    for (ObjectInstance oi : mbs.queryMBeans(name, null)) {
        WebSessionFlusher flusher = JMX.newMBeanProxy(mbs, oi.getObjectName(), WebSessionFlusher.class);
        StringTokenizer tokenizer = new StringTokenizer(flusher.listSessionIds(), " ");
        while (tokenizer.hasMoreTokens()) {
            String id = tokenizer.nextToken();
            flusher.expireSession(id);
        }
    }
}

From source file:org.nuxeo.ecm.webapp.seam.NuxeoSeamWebGate.java

protected Set<WebConnector> fetchConnectors() {
    Set<WebConnector> connectors = new HashSet<WebConnector>();
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    ObjectName names;/*from w w  w  . ja va2s.  c  om*/
    try {
        names = new ObjectName("Catalina:type=Connector,port=*,address=*");
    } catch (MalformedObjectNameException e) {
        log.error("Cannot query for tomcat connectors", e);
        return connectors;
    }
    Set<ObjectInstance> ois = mbs.queryMBeans(names, null);
    for (ObjectInstance oi : ois) {
        WebConnector connector = JMX.newMBeanProxy(mbs, oi.getObjectName(), WebConnector.class);
        connectors.add(connector);
    }
    return connectors;
}

From source file:org.openehealth.coala.lifecycle.FacesAppListener.java

@Override
public void processEvent(SystemEvent event) throws AbortProcessingException {

    /*/*  w  w  w .ja  va  2  s. c o  m*/
     * STARTUP PHASE - nothing yet
     */
    if (event instanceof PostConstructApplicationEvent) {
        LOG.info("PostConstructApplicationEvent is called");
    }

    /*
     * SHUTDOWN PHASE - cleaning up PDQ/XDS ipf routes (mwiesner)
     */

    if (event instanceof PreDestroyApplicationEvent) {
        LOG.info("PreDestroyApplicationEvent is called");
        MBeanServer mbserver = null;

        ArrayList<MBeanServer> mbservers = MBeanServerFactory.findMBeanServer(null);

        if (mbservers.size() > 0) {
            mbserver = (MBeanServer) mbservers.get(0);
        }

        if (mbserver != null) {
            LOG.info("Found our MBean server instance...");
        } else {
            mbserver = MBeanServerFactory.createMBeanServer();
        }

        try {
            Set<ObjectInstance> mbeans = mbserver.queryMBeans(null, null);
            for (ObjectInstance mb : mbeans) {
                if (mb.getObjectName().getCanonicalName().contains("camelContext-pdq")) {
                    LOG.info("Successfully removed MBean: " + mb.getObjectName().getCanonicalName());
                    mbserver.unregisterMBean(mb.getObjectName());
                } else if (mb.getObjectName().getCanonicalName().contains("camelContext-xds")) {
                    LOG.info("Successfully removed MBean: " + mb.getObjectName().getCanonicalName());
                    mbserver.unregisterMBean(mb.getObjectName());
                }
            }
        } catch (InstanceNotFoundException infe) {
            LOG.warn("Ignoring to unregister pdq/xds camelContext, as it was not found!?");
        } catch (Throwable e) {
            LOG.error(e.getLocalizedMessage(), e);
        }
    }
}

From source file:psiprobe.beans.ClusterWrapperBean.java

/**
 * Gets the cluster./*from ww w. j  a  v a2 s  .  com*/
 *
 * @param serverName the server name
 * @param hostName the host name
 * @param loadMembers the load members
 * @return the cluster
 * @throws Exception the exception
 */
public Cluster getCluster(String serverName, String hostName, boolean loadMembers) throws Exception {

    Cluster cluster = null;

    MBeanServer mbeanServer = new Registry().getMBeanServer();
    ObjectName membershipOName = new ObjectName(serverName + ":type=ClusterMembership,host=" + hostName);
    ObjectName receiverOName = new ObjectName(serverName + ":type=ClusterReceiver,host=" + hostName);
    ObjectName senderOName = new ObjectName(serverName + ":type=ClusterSender,host=" + hostName);

    /*
     * should be just one set, this is just to find out if this instance is cluster-enabled and the
     * cluster supports JMX
     */
    Set<ObjectInstance> clusters = mbeanServer.queryMBeans(new ObjectName("*:type=Cluster,host=" + hostName),
            null);
    Set<ObjectInstance> membership = mbeanServer.queryMBeans(membershipOName, null);
    if (clusters != null && !clusters.isEmpty() && membership != null && membership.size() > 0) {
        ObjectName clusterOName = clusters.iterator().next().getObjectName();
        cluster = new Cluster();

        cluster.setName(JmxTools.getStringAttr(mbeanServer, clusterOName, "clusterName"));
        cluster.setInfo(JmxTools.getStringAttr(mbeanServer, clusterOName, "info"));
        cluster.setManagerClassName(JmxTools.getStringAttr(mbeanServer, clusterOName, "managerClassName"));

        cluster.setMcastAddress(JmxTools.getStringAttr(mbeanServer, membershipOName, "mcastAddr"));
        cluster.setMcastBindAddress(JmxTools.getStringAttr(mbeanServer, membershipOName, "mcastBindAddress"));
        cluster.setMcastClusterDomain(
                JmxTools.getStringAttr(mbeanServer, membershipOName, "mcastClusterDomain"));
        cluster.setMcastDropTime(JmxTools.getLongAttr(mbeanServer, membershipOName, "mcastDropTime"));
        cluster.setMcastFrequency(JmxTools.getLongAttr(mbeanServer, membershipOName, "mcastFrequency"));
        cluster.setMcastPort(JmxTools.getIntAttr(mbeanServer, membershipOName, "mcastPort"));
        cluster.setMcastSoTimeout(JmxTools.getIntAttr(mbeanServer, membershipOName, "mcastSoTimeout"));
        cluster.setMcastTtl(JmxTools.getIntAttr(mbeanServer, membershipOName, "mcastTTL"));

        cluster.setTcpListenAddress(JmxTools.getStringAttr(mbeanServer, receiverOName, "tcpListenAddress"));
        cluster.setTcpListenPort(JmxTools.getIntAttr(mbeanServer, receiverOName, "tcpListenPort"));
        cluster.setNrOfMsgsReceived(JmxTools.getLongAttr(mbeanServer, receiverOName, "nrOfMsgsReceived"));
        cluster.setTotalReceivedBytes(JmxTools.getLongAttr(mbeanServer, receiverOName, "totalReceivedBytes"));
        // cluster.setTcpSelectorTimeout(
        // JmxTools.getLongAttr(mBeanServer, receiverOName, "tcpSelectorTimeout"));
        // cluster.setTcpThreadCount(
        // JmxTools.getIntAttr(mBeanServer, receiverOName, "tcpThreadCount"));

        cluster.setSenderAckTimeout(JmxTools.getLongAttr(mbeanServer, senderOName, "ackTimeout"));
        cluster.setSenderAutoConnect((Boolean) mbeanServer.getAttribute(senderOName, "autoConnect"));
        cluster.setSenderFailureCounter(JmxTools.getLongAttr(mbeanServer, senderOName, "failureCounter"));
        cluster.setSenderNrOfRequests(JmxTools.getLongAttr(mbeanServer, senderOName, "nrOfRequests"));
        cluster.setSenderReplicationMode(JmxTools.getStringAttr(mbeanServer, senderOName, "replicationMode"));
        cluster.setSenderTotalBytes(JmxTools.getLongAttr(mbeanServer, senderOName, "totalBytes"));

        if (loadMembers) {
            ObjectName[] senders = (ObjectName[]) mbeanServer.getAttribute(senderOName, "senderObjectNames");
            for (ObjectName localSenderOName : senders) {
                ClusterSender sender;

                if ("pooled".equals(cluster.getSenderReplicationMode())) {
                    sender = new PooledClusterSender();
                } else if ("synchronous".equals(cluster.getSenderReplicationMode())) {
                    sender = new SyncClusterSender();
                } else if ("asynchronous".equals(cluster.getSenderReplicationMode())
                        || "fastasyncqueue".equals(cluster.getSenderReplicationMode())) {
                    sender = new AsyncClusterSender();
                } else {
                    sender = new ClusterSender();
                }

                sender.setAddress(JmxTools.getStringAttr(mbeanServer, localSenderOName, "address"));
                sender.setPort(JmxTools.getIntAttr(mbeanServer, localSenderOName, "port"));

                sender.setAvgMessageSize(
                        JmxTools.getLongAttr(mbeanServer, localSenderOName, "avgMessageSize", -1));
                sender.setAvgProcessingTime(
                        JmxTools.getLongAttr(mbeanServer, localSenderOName, "avgProcessingTime", -1));

                sender.setConnectCounter(JmxTools.getLongAttr(mbeanServer, localSenderOName, "connectCounter"));
                sender.setDisconnectCounter(
                        JmxTools.getLongAttr(mbeanServer, localSenderOName, "disconnectCounter"));
                sender.setConnected((Boolean) mbeanServer.getAttribute(localSenderOName, "connected"));
                sender.setKeepAliveTimeout(
                        JmxTools.getLongAttr(mbeanServer, localSenderOName, "keepAliveTimeout"));
                sender.setNrOfRequests(JmxTools.getLongAttr(mbeanServer, localSenderOName, "nrOfRequests"));
                sender.setTotalBytes(JmxTools.getLongAttr(mbeanServer, localSenderOName, "totalBytes"));
                sender.setResend((Boolean) mbeanServer.getAttribute(localSenderOName, "resend"));
                sender.setSuspect((Boolean) mbeanServer.getAttribute(localSenderOName, "suspect"));

                if (sender instanceof PooledClusterSender) {
                    ((PooledClusterSender) sender).setMaxPoolSocketLimit(
                            JmxTools.getIntAttr(mbeanServer, localSenderOName, "maxPoolSocketLimit"));
                }

                if (sender instanceof SyncClusterSender) {
                    SyncClusterSender syncSender = (SyncClusterSender) sender;
                    syncSender.setDataFailureCounter(
                            JmxTools.getLongAttr(mbeanServer, localSenderOName, "dataFailureCounter"));
                    syncSender.setDataResendCounter(
                            JmxTools.getLongAttr(mbeanServer, localSenderOName, "dataResendCounter"));
                    syncSender.setSocketOpenCounter(
                            JmxTools.getIntAttr(mbeanServer, localSenderOName, "socketOpenCounter"));
                    syncSender.setSocketCloseCounter(
                            JmxTools.getIntAttr(mbeanServer, localSenderOName, "socketCloseCounter"));
                    syncSender.setSocketOpenFailureCounter(
                            JmxTools.getIntAttr(mbeanServer, localSenderOName, "socketOpenFailureCounter"));
                }

                if (sender instanceof AsyncClusterSender) {
                    AsyncClusterSender asyncSender = (AsyncClusterSender) sender;
                    asyncSender.setInQueueCounter(
                            JmxTools.getLongAttr(mbeanServer, localSenderOName, "inQueueCounter"));
                    asyncSender.setOutQueueCounter(
                            JmxTools.getLongAttr(mbeanServer, localSenderOName, "outQueueCounter"));
                    asyncSender.setQueueSize(JmxTools.getIntAttr(mbeanServer, localSenderOName, "queueSize"));
                    asyncSender.setQueuedNrOfBytes(
                            JmxTools.getLongAttr(mbeanServer, localSenderOName, "queuedNrOfBytes"));
                }
                cluster.getMembers().add(sender);
            }
        }
    }
    return cluster;
}

From source file:psiprobe.beans.JvmMemoryInfoAccessorBean.java

/**
 * Gets the pools.//from   w ww  .j a v  a2 s  .  co  m
 *
 * @return the pools
 * @throws Exception the exception
 */
public List<MemoryPool> getPools() throws Exception {

    List<MemoryPool> memoryPools = new LinkedList<>();
    MBeanServer mbeanServer = new Registry().getMBeanServer();
    Set<ObjectInstance> memoryOPools = mbeanServer.queryMBeans(new ObjectName("java.lang:type=MemoryPool,*"),
            null);

    // totals
    long totalInit = 0;
    long totalMax = 0;
    long totalUsed = 0;
    long totalCommitted = 0;

    for (ObjectInstance oi : memoryOPools) {
        ObjectName objName = oi.getObjectName();
        MemoryPool memoryPool = new MemoryPool();
        memoryPool.setName(JmxTools.getStringAttr(mbeanServer, objName, "Name"));
        memoryPool.setType(JmxTools.getStringAttr(mbeanServer, objName, "Type"));

        CompositeDataSupport cd = (CompositeDataSupport) mbeanServer.getAttribute(objName, "Usage");
        /*
         * It seems that "Usage" attribute of one of the pools may turn into null intermittently. We
         * better have a dip in the graph then an NPE though.
         */
        if (cd != null) {
            memoryPool.setMax(JmxTools.getLongAttr(cd, "max"));
            memoryPool.setUsed(JmxTools.getLongAttr(cd, "used"));
            memoryPool.setInit(JmxTools.getLongAttr(cd, "init"));
            memoryPool.setCommitted(JmxTools.getLongAttr(cd, "committed"));
        } else {
            logger.error("Oops, JVM problem? {} 'Usage' attribute is NULL!", objName);
        }

        totalInit += memoryPool.getInit();
        totalMax += memoryPool.getMax();
        totalUsed += memoryPool.getUsed();
        totalCommitted += memoryPool.getCommitted();

        memoryPools.add(memoryPool);
    }

    if (!memoryPools.isEmpty()) {
        MemoryPool pool = new MemoryPool();
        pool.setName("Total");
        pool.setType("TOTAL");
        pool.setInit(totalInit);
        pool.setUsed(totalUsed);
        pool.setMax(totalMax);
        pool.setCommitted(totalCommitted);
        memoryPools.add(pool);
    }

    return memoryPools;

}

From source file:psiprobe.Utils.java

/**
 * Checks if is threading enabled./*  w  ww  .j  a  v a 2  s.com*/
 *
 * @return true, if is threading enabled
 */
public static boolean isThreadingEnabled() {
    try {
        MBeanServer mbeanServer = new Registry().getMBeanServer();
        ObjectName threadingOName = new ObjectName("java.lang:type=Threading");
        Set<ObjectInstance> threading = mbeanServer.queryMBeans(threadingOName, null);
        return threading != null && !threading.isEmpty();
    } catch (MalformedObjectNameException e) {
        logger.trace("", e);
        return false;
    }
}