Example usage for javax.management MBeanInfo getDescription

List of usage examples for javax.management MBeanInfo getDescription

Introduction

In this page you can find the example usage for javax.management MBeanInfo getDescription.

Prototype

public String getDescription() 

Source Link

Document

Returns a human readable description of the MBean.

Usage

From source file:Utilities.java

/**
 * Prints info about a bean to a {@link VarOutputSink}.
 * //from w  w w.ja  v  a 2  s  .  c  om
 * @param sink The {@link VarOutputSink} to which info will be sent
 * @param mbs The {@link MBeanServer} with respect to which the
 *          {@code objectName} is accessed
 * @param objectName The {@link ObjectName} that identifies this bean
 */
public static void printMBeanInfo(VarOutputSink sink, MBeanServer mbs, ObjectName objectName) {
    MBeanInfo info = getMBeanInfoSafely(sink, mbs, objectName);
    if (info == null) {
        return;
    }

    sink.echo("\nCLASSNAME: \t" + info.getClassName());
    sink.echo("\nDESCRIPTION: \t" + info.getDescription());
    sink.echo("\nATTRIBUTES");
    MBeanAttributeInfo[] attrInfo = info.getAttributes();
    sink.printVariable("attrcount", Integer.toString(attrInfo.length));
    if (attrInfo.length > 0) {
        for (int i = 0; i < attrInfo.length; i++) {
            sink.echo(" ** NAME: \t" + attrInfo[i].getName());
            sink.echo("    DESCR: \t" + attrInfo[i].getDescription());
            sink.echo("    TYPE: \t" + attrInfo[i].getType() + "\tREAD: " + attrInfo[i].isReadable()
                    + "\tWRITE: " + attrInfo[i].isWritable());
        }
    } else
        sink.echo(" ** No attributes **");
    sink.echo("\nCONSTRUCTORS");
    MBeanConstructorInfo[] constrInfo = info.getConstructors();
    for (int i = 0; i < constrInfo.length; i++) {
        sink.echo(" ** NAME: \t" + constrInfo[i].getName());
        sink.echo("    DESCR: \t" + constrInfo[i].getDescription());
        sink.echo("    PARAM: \t" + constrInfo[i].getSignature().length + " parameter(s)");
    }
    sink.echo("\nOPERATIONS");
    MBeanOperationInfo[] opInfo = info.getOperations();
    if (opInfo.length > 0) {
        for (int i = 0; i < opInfo.length; i++) {
            sink.echo(" ** NAME: \t" + opInfo[i].getName());
            sink.echo("    DESCR: \t" + opInfo[i].getDescription());
            sink.echo("    PARAM: \t" + opInfo[i].getSignature().length + " parameter(s)");
        }
    } else
        sink.echo(" ** No operations ** ");
    sink.echo("\nNOTIFICATIONS");
    MBeanNotificationInfo[] notifInfo = info.getNotifications();
    if (notifInfo.length > 0) {
        for (int i = 0; i < notifInfo.length; i++) {
            sink.echo(" ** NAME: \t" + notifInfo[i].getName());
            sink.echo("    DESCR: \t" + notifInfo[i].getDescription());
            String notifTypes[] = notifInfo[i].getNotifTypes();
            for (int j = 0; j < notifTypes.length; j++) {
                sink.echo("    TYPE: \t" + notifTypes[j]);
            }
        }
    } else
        sink.echo(" ** No notifications **");
}

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

/**
 * @param mBeanServer//from w  w  w  . ja v  a 2s .  c o 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:org.jolokia.handler.list.DescriptionDataUpdater.java

/** 
 * The update method is overridden here directly since the usual extraction method
 * is not needed/* www .j ava 2  s . c o  m*/
 *
 * {@inheritDoc}
 * */
@Override
void update(JSONObject pJSONObject, MBeanInfo pMBeanInfo, Stack<String> pPathStack) {
    verifyThatPathIsEmpty(pPathStack);
    pJSONObject.put(getKey(), pMBeanInfo.getDescription());
}

From source file:net.zcarioca.jmx.domain.MBeanDescriptor.java

/**
 * Constructor for an {@link MBeanDescriptor}.
 * //from ww w  .  j a  v a  2s  .  co m
 * @param objectInstance The {@link ObjectInstance} as provided by an {@link MBeanServer}.
 */
public MBeanDescriptor(ObjectName objectName, MBeanInfo mbeanInfo) {
    this.className = mbeanInfo.getClassName();
    this.objectName = objectName;
    this.description = mbeanInfo.getDescription();
}

From source file:com.riotgames.mondev.JMXDiscovery.java

protected String discoverMBeans(String key) throws Exception {
    try {// w  ww.j  a  va  2  s . c  o  m
        HashMap<String, String[]> env = null;
        if (null != username && null != password) {
            env = new HashMap<String, String[]>();
            env.put(JMXConnector.CREDENTIALS, new String[] { username, password });
        }

        jmxc = JMXConnectorFactory.connect(jmxServerUrl, env);
        mbsc = jmxc.getMBeanServerConnection();

        ObjectName filter = new ObjectName(key);
        JSONArray beanList = new JSONArray();
        JSONObject mapping = new JSONObject();

        Set beans = mbsc.queryMBeans(filter, null);
        for (Object obj : beans) {
            JSONObject bean = new JSONObject();
            ObjectName beanName;

            // Return the ObjectName instance correctly for both Objects and Instances
            if (obj instanceof ObjectName)
                beanName = (ObjectName) obj;
            else if (obj instanceof ObjectInstance)
                beanName = ((ObjectInstance) obj).getObjectName();
            else
                throw new RuntimeException("Unexpected object type: " + obj);

            // Build the standing info, description and object path
            MBeanInfo mbi = mbsc.getMBeanInfo(beanName);
            bean.put("{#JMXDESC}", mbi.getDescription());
            bean.put("{#JMXOBJ}", beanName.getCanonicalName());

            // Build a list of all the MBean properties as {#PROP<NAME>}
            Hashtable<String, String> pt = beanName.getKeyPropertyList();
            for (Map.Entry<String, String> prop : pt.entrySet())
                bean.put(String.format("{#PROP%s}", prop.getKey().toUpperCase()), prop.getValue());

            beanList.put(bean);
        }

        mapping.put("data", beanList);
        return mapping.toString();
    } catch (Exception e) {
        JSONArray data = new JSONArray();
        JSONObject out = new JSONObject();
        out.put("data", data);

        return out.toString();
    } finally {
        try {
            if (null != jmxc)
                jmxc.close();
        } catch (java.io.IOException exception) {
        }

        jmxc = null;
        mbsc = null;
    }
}

From source file:flens.query.JMXQuery.java

private Map<String, Object> getDetails(ObjectName objectName)
        throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException {
    Map<String, Object> out = new HashMap<>();
    MBeanInfo info = connection.getMBeanInfo(objectName);
    out.put("description", info.getDescription());
    out.put("attributes", getAttributes(info));
    out.put("operations", getOpperations(info));
    out.put("notifications", getNotifications(info));
    return out;//from ww  w .  j  av a2s  . c  o m

}

From source file:com.proofpoint.jmx.MBeanRepresentation.java

public MBeanRepresentation(MBeanServer mbeanServer, ObjectName objectName, ObjectMapper objectMapper)
        throws JMException {
    this.objectName = objectName;

    MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo(objectName);

    className = mbeanInfo.getClassName();
    description = mbeanInfo.getDescription();
    descriptor = toMap(mbeanInfo.getDescriptor());

    ////w  ww .j  ava  2s .  c om
    // Attributes
    //
    LinkedHashMap<String, MBeanAttributeInfo> attributeInfos = Maps.newLinkedHashMap();
    for (MBeanAttributeInfo attributeInfo : mbeanInfo.getAttributes()) {
        attributeInfos.put(attributeInfo.getName(), attributeInfo);
    }

    String[] attributeNames = attributeInfos.keySet().toArray(new String[attributeInfos.size()]);
    ImmutableList.Builder<AttributeRepresentation> attributes = ImmutableList.builder();
    for (Attribute attribute : mbeanServer.getAttributes(objectName, attributeNames).asList()) {
        String attributeName = attribute.getName();

        // use remove so we only include one value for each attribute
        MBeanAttributeInfo attributeInfo = attributeInfos.remove(attributeName);
        if (attributeInfo == null) {
            // unknown extra attribute, could have been added after MBeanInfo was fetched
            continue;
        }

        Object attributeValue = attribute.getValue();
        AttributeRepresentation attributeRepresentation = new AttributeRepresentation(attributeInfo,
                attributeValue, objectMapper);
        attributes.add(attributeRepresentation);
    }
    this.attributes = attributes.build();

    //
    // Operations
    //
    ImmutableList.Builder<OperationRepresentation> operations = ImmutableList.builder();
    for (MBeanOperationInfo operationInfo : mbeanInfo.getOperations()) {
        operations.add(new OperationRepresentation(operationInfo));
    }
    this.operations = operations.build();
}

From source file:org.fusesource.cloudmix.agent.jbi.AgentComponent.java

private ObjectName validateMbean(MBeanServer anMbeanServer, String anMbeanName) {
    try {/*from w w  w .j av  a2  s  .com*/
        ObjectName oname = new ObjectName(anMbeanName);
        MBeanInfo info = anMbeanServer.getMBeanInfo(oname);
        if (info != null) {
            LOGGER.info("Successfully accesses Deployment Service mbean");
            LOGGER.info("Description: " + info.getDescription());
            return oname;
        }
    } catch (Exception e) {
        LOGGER.debug("Exception getting DeploymentService mbean " + e);
    }
    LOGGER.error("Cannot resolve DeploymentService MBean using name " + anMbeanName);
    return null;
}

From source file:net.community.chest.gitcloud.facade.frontend.git.GitController.java

private void serveRequest(RequestMethod method, HttpServletRequest req, HttpServletResponse rsp)
        throws IOException, ServletException {
    if (logger.isDebugEnabled()) {
        logger.debug("serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "]");
    }/*from   w w  w  .jav  a 2 s.c  o  m*/

    if ((loopRetryTimeout > 0L) && (!loopDetected)) {
        long now = System.currentTimeMillis(), diff = now - initTimestamp;
        if ((diff > 0L) && (diff < loopRetryTimeout)) {
            try {
                MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo(new ObjectName(
                        "net.community.chest.gitcloud.facade.backend.git:name=BackendRepositoryResolver"));
                if (mbeanInfo != null) {
                    logger.info("serveRequest(" + method + ")[" + req.getRequestURI() + "]["
                            + req.getQueryString() + "]" + " detected loop: " + mbeanInfo.getClassName() + "["
                            + mbeanInfo.getDescription() + "]");
                    loopDetected = true;
                }
            } catch (JMException e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("serveRequest(" + method + ")[" + req.getRequestURI() + "]["
                            + req.getQueryString() + "]" + " failed " + e.getClass().getSimpleName()
                            + " to detect loop: " + e.getMessage());
                }
            }
        }
    }

    ResolvedRepositoryData repoData = resolveTargetRepository(method, req);
    if (repoData == null) {
        throw ExtendedLogUtils.thrownLogging(logger, Level.WARNING,
                "serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "]",
                new NoSuchElementException("Failed to resolve repository"));
    }

    String username = authenticate(req);
    // TODO check if the user is allowed to access the repository via the resolve operation (push/pull) if at all (e.g., private repo)
    logger.info("serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "] user="
            + username);

    /*
     * NOTE: this feature requires enabling cross-context forwarding.
     * In Tomcat, the 'crossContext' attribute in 'Context' element of
     * 'TOMCAT_HOME\conf\context.xml' must be set to true, to enable cross-context 
     */
    if (loopDetected) {
        // TODO see if can find a more efficient way than splitting and re-constructing
        URI uri = repoData.getRepoLocation();
        ServletContext curContext = req.getServletContext();
        String urlPath = uri.getPath(), urlQuery = uri.getQuery();
        String[] comps = StringUtils.split(urlPath, '/');
        String appName = comps[0];
        ServletContext loopContext = Validate.notNull(curContext.getContext("/" + appName),
                "No cross-context for %s", appName);
        // build the relative path in the re-directed context
        StringBuilder sb = new StringBuilder(
                urlPath.length() + 1 + (StringUtils.isEmpty(urlQuery) ? 0 : urlQuery.length()));
        for (int index = 1; index < comps.length; index++) {
            sb.append('/').append(comps[index]);
        }
        if (!StringUtils.isEmpty(urlQuery)) {
            sb.append('?').append(urlQuery);
        }

        String redirectPath = sb.toString();
        RequestDispatcher dispatcher = Validate.notNull(loopContext.getRequestDispatcher(redirectPath),
                "No dispatcher for %s", redirectPath);
        dispatcher.forward(req, rsp);
        if (logger.isDebugEnabled()) {
            logger.debug("serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString()
                    + "]" + " forwarded to " + loopContext.getContextPath() + "/" + redirectPath);
        }
    } else {
        executeRemoteRequest(method, repoData.getRepoLocation(), req, rsp);
    }
}