Example usage for javax.management MBeanServer getAttribute

List of usage examples for javax.management MBeanServer getAttribute

Introduction

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

Prototype

public Object getAttribute(ObjectName name, String attribute)
        throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException;

Source Link

Usage

From source file:org.apache.openejb.server.cli.command.LocalJMXCommand.java

private void get(final String cmd) {
    int space = cmd.indexOf(" ");
    if (space < 0) {
        streamManager.writeErr("you need to specify an attribute and an objectname");
        return;// www . j av a 2  s . c o m
    }

    final String attr = cmd.substring(0, space);
    final String on = cmd.substring(space, cmd.length()).trim();

    final MBeanServer mBeanServer = LocalMBeanServer.get();
    try {
        final ObjectName oname = new ObjectName(on);
        final Object value = mBeanServer.getAttribute(oname, attr);
        streamManager.writeOut("Attribute [" + on + " -> " + attr + "] = " + stringify(value));
    } catch (Exception ex) {
        streamManager.writeErr(ex);
    }
}

From source file:org.apache.hadoop.hbase.util.JSONBean.java

/**
 * @param mBeanServer/*from   ww  w  .ja v  a2s.co m*/
 * @param qry
 * @param attribute
 * @param description
 * @return Return non-zero if failed to find bean. 0
 * @throws IOException
 */
private static int write(final JsonGenerator jg, final MBeanServer mBeanServer, ObjectName qry,
        String attribute, final boolean description) throws IOException {
    LOG.trace("Listing beans for " + qry);
    Set<ObjectName> names = null;
    names = mBeanServer.queryNames(qry, null);
    jg.writeArrayFieldStart("beans");
    Iterator<ObjectName> it = names.iterator();
    while (it.hasNext()) {
        ObjectName oname = it.next();
        MBeanInfo minfo;
        String code = "";
        String descriptionStr = null;
        Object attributeinfo = null;
        try {
            minfo = mBeanServer.getMBeanInfo(oname);
            code = minfo.getClassName();
            if (description)
                descriptionStr = minfo.getDescription();
            String prs = "";
            try {
                if ("org.apache.commons.modeler.BaseModelMBean".equals(code)) {
                    prs = "modelerType";
                    code = (String) mBeanServer.getAttribute(oname, prs);
                }
                if (attribute != null) {
                    prs = attribute;
                    attributeinfo = mBeanServer.getAttribute(oname, prs);
                }
            } catch (RuntimeMBeanException e) {
                // UnsupportedOperationExceptions happen in the normal course of business,
                // so no need to log them as errors all the time.
                if (e.getCause() instanceof UnsupportedOperationException) {
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Getting attribute " + prs + " of " + oname + " threw " + e);
                    }
                } else {
                    LOG.error("Getting attribute " + prs + " of " + oname + " threw an exception", e);
                }
                return 0;
            } catch (AttributeNotFoundException e) {
                // If the modelerType attribute was not found, the class name is used
                // instead.
                LOG.error("getting attribute " + prs + " of " + oname + " threw an exception", e);
            } catch (MBeanException e) {
                // The code inside the attribute getter threw an exception so log it,
                // and fall back on the class name
                LOG.error("getting attribute " + prs + " of " + oname + " threw an exception", e);
            } catch (RuntimeException e) {
                // For some reason even with an MBeanException available to them
                // Runtime exceptionscan still find their way through, so treat them
                // the same as MBeanException
                LOG.error("getting attribute " + prs + " of " + oname + " threw an exception", e);
            } catch (ReflectionException e) {
                // This happens when the code inside the JMX bean (setter?? from the
                // java docs) threw an exception, so log it and fall back on the
                // class name
                LOG.error("getting attribute " + prs + " of " + oname + " threw an exception", e);
            }
        } catch (InstanceNotFoundException e) {
            //Ignored for some reason the bean was not found so don't output it
            continue;
        } catch (IntrospectionException e) {
            // This is an internal error, something odd happened with reflection so
            // log it and don't output the bean.
            LOG.error("Problem while trying to process JMX query: " + qry + " with MBean " + oname, e);
            continue;
        } catch (ReflectionException e) {
            // This happens when the code inside the JMX bean threw an exception, so
            // log it and don't output the bean.
            LOG.error("Problem while trying to process JMX query: " + qry + " with MBean " + oname, e);
            continue;
        }

        jg.writeStartObject();
        jg.writeStringField("name", oname.toString());
        if (description && descriptionStr != null && descriptionStr.length() > 0) {
            jg.writeStringField("description", descriptionStr);
        }
        jg.writeStringField("modelerType", code);
        if (attribute != null && attributeinfo == null) {
            jg.writeStringField("result", "ERROR");
            jg.writeStringField("message", "No attribute with name " + attribute + " was found.");
            jg.writeEndObject();
            jg.writeEndArray();
            jg.close();
            return -1;
        }

        if (attribute != null) {
            writeAttribute(jg, attribute, descriptionStr, attributeinfo);
        } else {
            MBeanAttributeInfo[] attrs = minfo.getAttributes();
            for (int i = 0; i < attrs.length; i++) {
                writeAttribute(jg, mBeanServer, oname, description, attrs[i]);
            }
        }
        jg.writeEndObject();
    }
    jg.writeEndArray();
    return 0;
}

From source file:net.testdriven.psiprobe.controllers.threads.ListSunThreadsController.java

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

    List<SunThread> threads = null;
    int executionStackDepth = 1;

    MBeanServer mBeanServer = new Registry().getMBeanServer();
    ObjectName threadingOName = new ObjectName("java.lang:type=Threading");

    long[] deadlockedIds = (long[]) mBeanServer.invoke(threadingOName, "findMonitorDeadlockedThreads", null,
            null);//from w  w w. ja  va 2  s . c  o  m
    long[] allIds = (long[]) mBeanServer.getAttribute(threadingOName, "AllThreadIds");

    if (allIds != null) {
        threads = new ArrayList<>(allIds.length);

        for (long allId : allIds) {
            CompositeData cd = (CompositeData) mBeanServer.invoke(threadingOName, "getThreadInfo",
                    new Object[] { allId, executionStackDepth }, new String[] { "long", "int" });

            if (cd != null) {
                SunThread st = new SunThread();
                st.setId(JmxTools.getLongAttr(cd, "threadId"));
                st.setName(JmxTools.getStringAttr(cd, "threadName"));
                st.setState(JmxTools.getStringAttr(cd, "threadState"));
                st.setSuspended(JmxTools.getBooleanAttr(cd, "suspended"));
                st.setInNative(JmxTools.getBooleanAttr(cd, "inNative"));
                st.setLockName(JmxTools.getStringAttr(cd, "lockName"));
                st.setLockOwnerName(JmxTools.getStringAttr(cd, "lockOwnerName"));
                st.setWaitedCount(JmxTools.getLongAttr(cd, "waitedCount"));
                st.setBlockedCount(JmxTools.getLongAttr(cd, "blockedCount"));
                st.setDeadlocked(contains(deadlockedIds, st.getId()));

                CompositeData[] stack = (CompositeData[]) cd.get("stackTrace");
                if (stack.length > 0) {
                    CompositeData cd2 = stack[0];
                    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"));
                    st.setExecutionPoint(tse);
                }

                threads.add(st);
            }
        }
    }
    return new ModelAndView(getViewName(), "threads", threads);
}

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

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

    List threads = null;//from w  w  w  .j a v  a  2 s .  c o  m
    int executionStackDepth = 1;

    MBeanServer mBeanServer = new Registry().getMBeanServer();
    ObjectName threadingOName = new ObjectName("java.lang:type=Threading");

    long[] deadlockedIds = (long[]) mBeanServer.invoke(threadingOName, "findMonitorDeadlockedThreads", null,
            null);
    long[] allIds = (long[]) mBeanServer.getAttribute(threadingOName, "AllThreadIds");

    if (allIds != null) {
        threads = new ArrayList(allIds.length);

        for (int i = 0; i < allIds.length; i++) {
            CompositeData cd = (CompositeData) mBeanServer.invoke(threadingOName, "getThreadInfo",
                    new Object[] { new Long(allIds[i]), new Integer(executionStackDepth) },
                    new String[] { "long", "int" });

            if (cd != null) {
                SunThread st = new SunThread();
                st.setId(JmxTools.getLongAttr(cd, "threadId"));
                st.setName(JmxTools.getStringAttr(cd, "threadName"));
                st.setState(JmxTools.getStringAttr(cd, "threadState"));
                st.setSuspended(JmxTools.getBooleanAttr(cd, "suspended"));
                st.setInNative(JmxTools.getBooleanAttr(cd, "inNative"));
                st.setLockName(JmxTools.getStringAttr(cd, "lockName"));
                st.setLockOwnerName(JmxTools.getStringAttr(cd, "lockOwnerName"));
                st.setWaitedCount(JmxTools.getLongAttr(cd, "waitedCount"));
                st.setBlockedCount(JmxTools.getLongAttr(cd, "blockedCount"));
                st.setDeadlocked(contains(deadlockedIds, st.getId()));

                CompositeData[] stack = (CompositeData[]) cd.get("stackTrace");
                if (stack.length > 0) {
                    CompositeData cd2 = stack[0];
                    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"));
                    st.setExecutionPoint(tse);
                }

                threads.add(st);
            }
        }
    }
    return new ModelAndView(getViewName(), "threads", threads);
}

From source file:org.mc4j.ems.impl.jmx.connection.bean.attribute.DAttribute.java

/**
 * Updates the local value of this mbean from the server
 * <p/>//w  w  w.j av a2  s .  c o m
 * TODO we should not update to null on failure, but retain the last known
 */
public synchronized Object refresh() {
    loaded = true;
    Object newValue = null;
    try {
        MBeanServer server = bean.getConnectionProvider().getMBeanServer();
        newValue = server.getAttribute(bean.getObjectName(), getName());

    } catch (ReflectionException e) {
        supportedType = false;
        registerFailure(e);
        throw new EmsException("Could not load attribute value " + e.toString(), e);
    } catch (InstanceNotFoundException e) {
        registerFailure(e);
        throw new EmsException(
                "Could not load attribute value, bean instance not found " + bean.getObjectName().toString(),
                e);
    } catch (MBeanException e) {
        registerFailure(e);
        Throwable t = e.getTargetException();
        if (t != null)
            throw new EmsException(
                    "Could not load attribute value, target bean threw exception " + t.getLocalizedMessage(),
                    t);
        else
            throw new EmsException("Could not load attribute value " + e.getLocalizedMessage(), e);
    } catch (AttributeNotFoundException e) {
        registerFailure(e);
        throw new EmsException("Could not load attribute value, attribute [" + getName() + "] not found", e);
    } catch (UndeclaredThrowableException e) {
        if (e.getUndeclaredThrowable() instanceof InvocationTargetException) {
            Throwable t = e.getCause();
            if (t.getCause() instanceof NotSerializableException) {
                supportedType = false;
                registerFailure(t.getCause());
                throw new EmsException("Could not load attribute value " + t.getLocalizedMessage(),
                        t.getCause());
            } else
                throw new EmsException("Could not load attribute value " + t.getLocalizedMessage(), t);
        }
        throw new EmsException("Could not load attribute value " + e.getLocalizedMessage(), e);
    } catch (RuntimeException re) {
        supportedType = false;

        // TODO GH: Figure this one out
        // Getting weblogic.management.NoAccessRuntimeException on wl9
        registerFailure(re);
        throw new EmsException("Could not load attribute value " + re.getLocalizedMessage(), re);
    } catch (NoClassDefFoundError ncdfe) {
        supportedType = false;
        registerFailure(ncdfe);
        throw new EmsException("Could not load attribute value " + ncdfe.getLocalizedMessage(), ncdfe);
    } catch (Throwable t) {
        throw new EmsException("Could not load attribute value " + t.getLocalizedMessage(), t);
    }
    alterValue(newValue);
    return newValue;
}

From source file:psiprobe.controllers.threads.ListSunThreadsController.java

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

    List<SunThread> threads = null;
    int executionStackDepth = 1;

    MBeanServer mbeanServer = new Registry().getMBeanServer();
    ObjectName threadingOName = new ObjectName("java.lang:type=Threading");

    long[] deadlockedIds = (long[]) mbeanServer.invoke(threadingOName, "findMonitorDeadlockedThreads", null,
            null);//from  w w w  .  j  a va 2  s .  c  o  m
    long[] allIds = (long[]) mbeanServer.getAttribute(threadingOName, "AllThreadIds");

    if (allIds != null) {
        threads = new ArrayList<>(allIds.length);

        for (long id : allIds) {
            CompositeData cd = (CompositeData) mbeanServer.invoke(threadingOName, "getThreadInfo",
                    new Object[] { id, executionStackDepth }, new String[] { "long", "int" });

            if (cd != null) {
                SunThread st = new SunThread();
                st.setId(JmxTools.getLongAttr(cd, "threadId"));
                st.setName(JmxTools.getStringAttr(cd, "threadName"));
                st.setState(JmxTools.getStringAttr(cd, "threadState"));
                st.setSuspended(JmxTools.getBooleanAttr(cd, "suspended"));
                st.setInNative(JmxTools.getBooleanAttr(cd, "inNative"));
                st.setLockName(JmxTools.getStringAttr(cd, "lockName"));
                st.setLockOwnerName(JmxTools.getStringAttr(cd, "lockOwnerName"));
                st.setWaitedCount(JmxTools.getLongAttr(cd, "waitedCount"));
                st.setBlockedCount(JmxTools.getLongAttr(cd, "blockedCount"));
                st.setDeadlocked(contains(deadlockedIds, st.getId()));

                CompositeData[] stack = (CompositeData[]) cd.get("stackTrace");
                if (stack.length > 0) {
                    CompositeData cd2 = stack[0];
                    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"));
                    st.setExecutionPoint(tse);
                }

                threads.add(st);
            }
        }
    }
    return new ModelAndView(getViewName(), "threads", threads);
}

From source file:org.apache.hadoop.hdfs.server.datanode.TestDataNodeMXBean.java

@Test
public void testDataNodeMXBean() throws Exception {
    Configuration conf = new Configuration();
    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build();

    try {/*from  w ww.j a  va 2 s.c o m*/
        List<DataNode> datanodes = cluster.getDataNodes();
        Assert.assertEquals(datanodes.size(), 1);
        DataNode datanode = datanodes.get(0);

        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName mxbeanName = new ObjectName("Hadoop:service=DataNode,name=DataNodeInfo");
        // get attribute "ClusterId"
        String clusterId = (String) mbs.getAttribute(mxbeanName, "ClusterId");
        Assert.assertEquals(datanode.getClusterId(), clusterId);
        // get attribute "Version"
        String version = (String) mbs.getAttribute(mxbeanName, "Version");
        Assert.assertEquals(datanode.getVersion(), version);
        // get attribute "SotfwareVersion"
        String softwareVersion = (String) mbs.getAttribute(mxbeanName, "SoftwareVersion");
        Assert.assertEquals(datanode.getSoftwareVersion(), softwareVersion);
        Assert.assertEquals(version, softwareVersion + ", r" + datanode.getRevision());
        // get attribute "RpcPort"
        String rpcPort = (String) mbs.getAttribute(mxbeanName, "RpcPort");
        Assert.assertEquals(datanode.getRpcPort(), rpcPort);
        // get attribute "HttpPort"
        String httpPort = (String) mbs.getAttribute(mxbeanName, "HttpPort");
        Assert.assertEquals(datanode.getHttpPort(), httpPort);
        // get attribute "NamenodeAddresses"
        String namenodeAddresses = (String) mbs.getAttribute(mxbeanName, "NamenodeAddresses");
        Assert.assertEquals(datanode.getNamenodeAddresses(), namenodeAddresses);
        // get attribute "getVolumeInfo"
        String volumeInfo = (String) mbs.getAttribute(mxbeanName, "VolumeInfo");
        Assert.assertEquals(replaceDigits(datanode.getVolumeInfo()), replaceDigits(volumeInfo));
        // Ensure mxbean's XceiverCount is same as the DataNode's
        // live value.
        int xceiverCount = (Integer) mbs.getAttribute(mxbeanName, "XceiverCount");
        Assert.assertEquals(datanode.getXceiverCount(), xceiverCount);

        String bpActorInfo = (String) mbs.getAttribute(mxbeanName, "BPServiceActorInfo");
        Assert.assertEquals(datanode.getBPServiceActorInfo(), bpActorInfo);
    } finally {
        if (cluster != null) {
            cluster.shutdown();
        }
    }
}

From source file:com.atolcd.alfresco.audit.web.scripts.LuceneIndexesInfoGet.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {

    try {//  w  w  w .j  ava2 s .com
        // Map that will be passed to the template
        Map<String, Object> model = new HashMap<String, Object>();

        ObjectName query = new ObjectName("Alfresco:Name=LuceneIndexes,*");
        MBeanServer mbs = getMBeanServerWithQuery(query);
        Set<ObjectName> luceneIndexesName = mbs.queryNames(query, null);
        List<LuceneIndex> luceneIndexes = new ArrayList<LuceneIndex>();

        for (ObjectName luceneIndexName : luceneIndexesName) {

            luceneIndexes.add(new LuceneIndex(luceneIndexName.getKeyProperty("Index"),
                    String.valueOf(mbs.getAttribute(luceneIndexName, "ActualSize")),
                    String.valueOf(mbs.getAttribute(luceneIndexName, "NumberOfDocuments")),
                    String.valueOf(mbs.getAttribute(luceneIndexName, "NumberOfFields")),
                    String.valueOf(mbs.getAttribute(luceneIndexName, "NumberOfIndexedFields")),
                    String.valueOf(mbs.getAttribute(luceneIndexName, "UsedSize"))));
        }

        model.put("luceneIndexes", luceneIndexes);

        return model;
    } catch (Exception e) {
        throw new WebScriptException(
                "[LuceneIndexesInfosGet] Error in executeImpl function : \n" + e.getMessage());
    }
}

From source file:org.wso2.carbon.andes.cluster.mgt.internal.managementBeans.ClusterManagementBeans.java

/**
 * Gets the message store's health status
 *
 * @return true if healthy, else false.//from   w ww.  ja  va2  s  . co  m
 * @throws ClusterMgtException
 */
public boolean getStoreHealth() throws ClusterMgtException {
    boolean storeHealth = false;
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        ObjectName objectName = new ObjectName(
                "org.wso2.andes:type=ClusterManagementInformation," + "name=ClusterManagementInformation");
        Object result = mBeanServer.getAttribute(objectName, ClusterMgtConstants.STORE_HEALTH);
        if (result != null) {
            storeHealth = (Boolean) result;
        }
        return storeHealth;

    } catch (MalformedObjectNameException e) {
        throw new ClusterMgtException("Cannot get message store health.", e);
    } catch (ReflectionException e) {
        throw new ClusterMgtException("Cannot get message store health.", e);
    } catch (MBeanException e) {
        throw new ClusterMgtException("Cannot get message store health.", e);
    } catch (InstanceNotFoundException e) {
        throw new ClusterMgtException("Cannot get message store health.", e);
    } catch (AttributeNotFoundException e) {
        throw new ClusterMgtException("Cannot get message store health.", e);
    }
}

From source file:org.wso2.carbon.andes.cluster.mgt.internal.managementBeans.ClusterManagementBeans.java

/**
 * Checks whether clustering is enabled//from w ww .j ava2  s .com
 *
 * @return a boolean whether clustering is enabled
 * @throws ClusterMgtException
 */
public boolean isClusteringEnabled() throws ClusterMgtException {
    boolean isClustered = false;
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        ObjectName objectName = new ObjectName(
                "org.wso2.andes:type=ClusterManagementInformation," + "name=ClusterManagementInformation");
        Object result = mBeanServer.getAttribute(objectName, ClusterMgtConstants.IS_CLUSTERING_ENABLED);

        if (result != null) {
            isClustered = (Boolean) result;
        }

        return isClustered;
    } catch (MalformedObjectNameException e) {
        throw new ClusterMgtException("Cannot access cluster information", e);
    } catch (InstanceNotFoundException e) {
        throw new ClusterMgtException("Cannot access cluster information", e);
    } catch (ReflectionException e) {
        throw new ClusterMgtException("Cannot access cluster information", e);
    } catch (AttributeNotFoundException e) {
        throw new ClusterMgtException("Cannot access cluster information", e);
    } catch (MBeanException e) {
        throw new ClusterMgtException("Cannot access cluster information", e);
    }
}