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.meltmedia.cadmium.deployer.JBossUtil.java

public static boolean isWarDeployed(String warName, Logger log) throws Exception {
    MBeanServer server = MBeanServerLocator.locateJBoss();
    Set<ObjectInstance> foundInstances = server
            .queryMBeans(new ObjectName("jboss.deployment:type=Deployment,id=\"*" + warName + "*\""), null);
    boolean found = false;
    if (foundInstances != null && foundInstances.size() > 0) {
        log.debug("MBean query returned: {} results.", foundInstances.size());
        for (ObjectInstance instance : foundInstances) {
            String simpleName = "" + server.getAttribute(instance.getObjectName(), "SimpleName");
            log.debug("Checking {} is {}", simpleName, warName);
            if (simpleName.equals(warName)) {
                found = true;//from ww  w .  j  a va2s . c  o m
                String state = server.getAttribute(instance.getObjectName(), "State") + "";
                log.debug("Deployment state {}", state);
                if (state.equals("ERROR")) {
                    Object error = server.getAttribute(instance.getObjectName(), "Problem");
                    log.debug("Found problem: {}", error);
                    if (error instanceof Throwable) {
                        throw new Exception((Throwable) error);
                    } else {
                        throw new Exception(error.toString());
                    }
                } else if (state.equals("DEPLOYED")) {
                    return true;
                } else if (state.equals("UNDEPLOYED")) {
                    found = false;
                }
            }
        }
    }
    if (!found) {
        throw new NoDeploymentFoundException();
    }
    return false;
}

From source file:com.googlecode.psiprobe.Utils.java

public static boolean isThreadingEnabled() {
    try {/*from  w ww  .  j  a v  a  2s  . c o m*/
        MBeanServer mBeanServer = new Registry().getMBeanServer();
        ObjectName threadingOName = new ObjectName("java.lang:type=Threading");
        Set s = mBeanServer.queryMBeans(threadingOName, null);
        return s != null && s.size() > 0;
    } catch (MalformedObjectNameException e) {
        return false;
    }
}

From source file:com.googlecode.psiprobe.beans.JvmMemoryInfoAccessorBean.java

public List getPools() throws Exception {

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

    //// www  . j a v  a 2s. com
    // totals
    //
    long totalInit = 0;
    long totalMax = 0;
    long totalUsed = 0;
    long totalCommitted = 0;

    for (Iterator it = memoryOPools.iterator(); it.hasNext();) {
        ObjectInstance oi = (ObjectInstance) it.next();
        ObjectName oName = oi.getObjectName();
        MemoryPool memoryPool = new MemoryPool();
        memoryPool.setName(JmxTools.getStringAttr(mBeanServer, oName, "Name"));
        memoryPool.setType(JmxTools.getStringAttr(mBeanServer, oName, "Type"));

        CompositeDataSupport cd = (CompositeDataSupport) mBeanServer.getAttribute(oName, "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? " + oName.toString() + " \"Usage\" attribute is NULL!");
        }

        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:de.thorstenberger.examServer.pdf.PDFExporter.java

/**
 * use jmx, query catalina mbean to find non ssl connectors (-Dcom.sun.management.jmxremote) FIXME tomcat specific
 * code//w ww.  j av a2 s  .  c om
 *
 * @param request
 * @return
 */
private String getServerUrl() {

    final MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        for (final Object mbean : beanServer.queryMBeans(new ObjectName("*:type=Connector,*"), null)) {
            final ObjectInstance oi = (ObjectInstance) mbean;
            final Boolean isSecure = (Boolean) beanServer.getAttribute(oi.getObjectName(), "secure");
            final String protocol = (String) beanServer.getAttribute(oi.getObjectName(), "protocol");
            final int port = (Integer) beanServer.getAttribute(oi.getObjectName(), "port");
            if (!isSecure && protocol.startsWith("HTTP")) {
                log.debug(String.format("Using unsecured tomcat connector at port %d", port));
                return "http://localhost:" + port;
            }
        }
    } catch (final MalformedObjectNameException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final NullPointerException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final AttributeNotFoundException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final InstanceNotFoundException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final MBeanException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final ReflectionException e) {
        log.warn("Could not access JMX mbeans.", e);
    }
    log.warn(
            "No mbeans of type '*:type=Connector,*' configured, using default url (assuming non-ssl http connector on port 8080).");
    return "http://localhost:8080";
}

From source file:de.thorstenberger.taskmodel.view.webapp.filter.ExportPDFFilter.java

/**
 * Try to find a nonssl connector to retrieve shared resources like stylesheets, images etc. Fallback: Use request
 * url.//from  w  ww  .j  a va  2s .  c om
 *
 * @param request
 * @return
 */
private String getLocalURL(final HttpServletRequest request) {

    final MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        for (final Object mbean : beanServer.queryMBeans(new ObjectName("*:type=Connector,*"), null)) {
            final ObjectInstance oi = (ObjectInstance) mbean;
            final Boolean isSecure = (Boolean) beanServer.getAttribute(oi.getObjectName(), "secure");
            final String protocol = (String) beanServer.getAttribute(oi.getObjectName(), "protocol");
            final int port = (Integer) beanServer.getAttribute(oi.getObjectName(), "port");
            if (!isSecure && protocol.startsWith("HTTP")) {
                log.debug(String.format("Using unsecured tomcat connector at port %d", port));
                return "http://localhost:" + port;
            }
        }
    } catch (final MalformedObjectNameException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final NullPointerException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final AttributeNotFoundException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final InstanceNotFoundException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final MBeanException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final ReflectionException e) {
        log.warn("Could not access JMX mbeans.", e);
    }
    String requestURL = request.getRequestURL().toString();
    log.warn("No mbeans of type '*:type=Connector,*' configured, using request url (assuming non-ssl): "
            + requestURL);
    return requestURL;
}

From source file:com.googlecode.psiprobe.beans.ContainerListenerBean.java

/**
 * Load ObjectNames for the relevant MBeans so they can be queried at a later stage without searching MBean server
 * over and over again./*  ww  w.  jav a  2 s .  c  o m*/
 *
 * @throws Exception - this method does not handle any of the exceptions that may be thrown when querying MBean server.
 */
private synchronized void initialize() throws Exception {

    MBeanServer server = getContainerWrapper().getResourceResolver().getMBeanServer();
    String serverName = getContainerWrapper().getTomcatContainer().getName();
    Set threadPools = server.queryMBeans(new ObjectName(serverName + ":type=ThreadPool,*"), null);
    poolNames = new ArrayList(threadPools.size());
    for (Iterator it = threadPools.iterator(); it.hasNext();) {

        ThreadPoolObjectName threadPoolObjectName = new ThreadPoolObjectName();
        ObjectName threadPoolName = ((ObjectInstance) it.next()).getObjectName();

        String name = threadPoolName.getKeyProperty("name");

        threadPoolObjectName.setThreadPoolName(threadPoolName);
        ObjectName grpName = server
                .getObjectInstance(new ObjectName(
                        threadPoolName.getDomain() + ":type=GlobalRequestProcessor,name=" + name))
                .getObjectName();
        threadPoolObjectName.setGlobalRequestProcessorName(grpName);

        //
        // unfortunately exact workers could not be found at the time of testing
        // so we filter out the relevant workers within the loop
        //
        Set workers = server
                .queryMBeans(new ObjectName(threadPoolName.getDomain() + ":type=RequestProcessor,*"), null);

        for (Iterator wrkIt = workers.iterator(); wrkIt.hasNext();) {
            ObjectName wrkName = ((ObjectInstance) wrkIt.next()).getObjectName();
            if (name.equals(wrkName.getKeyProperty("worker"))) {
                threadPoolObjectName.getRequestProcessorNames().add(wrkName);
            }
        }

        poolNames.add(threadPoolObjectName);
    }

    Set executors = server.queryMBeans(new ObjectName(serverName + ":type=Executor,*"), null);
    executorNames = new ArrayList(executors.size());
    for (Iterator it = executors.iterator(); it.hasNext();) {
        ObjectName executorName = ((ObjectInstance) it.next()).getObjectName();
        executorNames.add(executorName);
    }

    // Register with MBean server
    server.addNotificationListener(new ObjectName("JMImplementation:type=MBeanServerDelegate"), this, null,
            null);

}

From source file:architecture.ee.web.spring.controller.SecureMoSKitoController.java

private List<URL> getClassPathUrlsForTomcat(final String context, final String contextPropertyName) {
    List<MBeanServer> servers = MBeanServerFactory.findMBeanServer(null);
    for (MBeanServer s : servers) {
        Set<ObjectInstance> instances = s.queryMBeans(null, new QueryExp() {

            public boolean apply(ObjectName name) throws BadStringOperationException,
                    BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException {
                String type = name.getKeyProperty("type");
                log.debug(name.getDomain() + " : " + name.getKeyPropertyList());
                if (!type.equals("WebappClassLoader"))
                    return false;
                if (!name.getDomain().equals("Catalina"))
                    return false;
                if (!name.getKeyProperty(contextPropertyName).equals(context))
                    return false;
                return true;
            }// w  w w.j a  va 2  s. c o  m

            public void setMBeanServer(MBeanServer s) {
            }
        });
        if (instances.size() > 0) {
            try {
                URL[] urls = (URL[]) s.getAttribute(instances.iterator().next().getObjectName(), "URLs");
                return Arrays.asList(urls);
            } catch (Exception e) {
            }

        }
    }
    return null;
}

From source file:com.googlecode.psiprobe.beans.ClusterWrapperBean.java

public Cluster getCluster(String serverName, String hostName, boolean loadMembers) throws Exception {
    Cluster cluster = null;/*from w  w  w. j a v a  2  s. com*/

    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 clusters = mBeanServer.queryMBeans(new ObjectName("*:type=Cluster,host=" + hostName), null);
    Set membership = mBeanServer.queryMBeans(membershipOName, null);
    if (clusters != null && clusters.size() > 0 && membership != null && membership.size() > 0) {
        ObjectName clusterOName = ((ObjectInstance) 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(getLongAttr(mBeanServer, receiverOName, "tcpSelectorTimeout"));
        //            cluster.setTcpThreadCount(getIntAttr(mBeanServer, receiverOName, "tcpThreadCount"));

        cluster.setSenderAckTimeout(JmxTools.getLongAttr(mBeanServer, senderOName, "ackTimeout"));
        cluster.setSenderAutoConnect(
                ((Boolean) mBeanServer.getAttribute(senderOName, "autoConnect")).booleanValue());
        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 (int i = 0; i < senders.length; i++) {

                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();
                }
                ObjectName localSenderOName = senders[i];

                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")).booleanValue());
                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")).booleanValue());
                sender.setSuspect(
                        ((Boolean) mBeanServer.getAttribute(localSenderOName, "suspect")).booleanValue());

                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.controllers.threads.ThreadStackController.java

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

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

    List<ThreadStackElement> stack = null;
    MBeanServer mbeanServer = new Registry().getMBeanServer();
    ObjectName threadingOName = new ObjectName("java.lang:type=Threading");

    if (threadId == -1 && threadName != null) {
        // find thread by name
        for (long id : (long[]) mbeanServer.getAttribute(threadingOName, "AllThreadIds")) {
            CompositeData cd = (CompositeData) mbeanServer.invoke(threadingOName, "getThreadInfo",
                    new Object[] { id }, new String[] { "long" });
            String name = JmxTools.getStringAttr(cd, "threadName");
            if (threadName.equals(name)) {
                threadId = id;//w  ww.  j a v  a  2  s .com
                break;
            }
        }
    }

    if (mbeanServer.queryMBeans(threadingOName, null) != null && threadId != -1) {

        CompositeData cd = (CompositeData) mbeanServer.invoke(threadingOName, "getThreadInfo",
                new Object[] { threadId, 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 (CompositeData cd2 : elements) {
                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:net.testdriven.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<ThreadStackElement> stack = null;
    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 (long allId : allIds) {
            CompositeData cd = (CompositeData) mBeanServer.invoke(threadingOName, "getThreadInfo",
                    new Object[] { allId }, new String[] { "long" });
            String name = JmxTools.getStringAttr(cd, "threadName");
            if (threadName.equals(name)) {
                threadID = allId;//from w  w  w.j  a v  a2  s.c  om
                break;
            }
        }
    }

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

        CompositeData cd = (CompositeData) mBeanServer.invoke(threadingOName, "getThreadInfo",
                new Object[] { threadID, 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 (CompositeData cd2 : elements) {
                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);
}