Example usage for javax.management MBeanServer getMBeanInfo

List of usage examples for javax.management MBeanServer getMBeanInfo

Introduction

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

Prototype

public MBeanInfo getMBeanInfo(ObjectName name)
            throws InstanceNotFoundException, IntrospectionException, ReflectionException;

Source Link

Usage

From source file:com.betfair.cougar.core.impl.jmx.HtmlAdaptorParser.java

private void appendMBean(MBeanServer server, ObjectName on, String attrName, String separator,
        StringBuilder buf) {//from  www  . j  av a2 s .  c om
    StringBuilder local = new StringBuilder();
    try {

        MBeanInfo info = server.getMBeanInfo(on);
        local.append(on.toString());
        MBeanAttributeInfo[] attr = info.getAttributes();
        for (int i = 0; i < attr.length; i++) {
            if ((attrName == null || attrName.equals(attr[i].getName())) && attr[i].isReadable()) {
                local.append(separator);
                local.append(attr[i].getName());
                local.append(separator);
                local.append(server.getAttribute(on, attr[i].getName()));
            }
        }
    } catch (Exception e) {
        LOGGER.debug("Unable to retrieve Bean information for bean " + on, e);
        return;
    }
    buf.append(local);
}

From source file:org.apache.streams.jackson.StreamsTaskCounterDeserializer.java

@Override
public StreamsTaskCounterBroadcast deserialize(JsonParser jsonParser,
        DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    try {/*  w  w w  .  j a  va 2s.  c o m*/
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();

        StreamsTaskCounterBroadcast streamsTaskCounterBroadcast = new StreamsTaskCounterBroadcast();
        JsonNode attributes = jsonParser.getCodec().readTree(jsonParser);

        ObjectName name = new ObjectName(attributes.get("canonicalName").asText());
        MBeanInfo info = server.getMBeanInfo(name);
        streamsTaskCounterBroadcast.setName(name.toString());

        for (MBeanAttributeInfo attribute : Arrays.asList(info.getAttributes())) {
            try {
                switch (attribute.getName()) {
                case "ErrorRate":
                    streamsTaskCounterBroadcast
                            .setErrorRate((double) server.getAttribute(name, attribute.getName()));
                    break;
                case "NumEmitted":
                    streamsTaskCounterBroadcast
                            .setNumEmitted((long) server.getAttribute(name, attribute.getName()));
                    break;
                case "NumReceived":
                    streamsTaskCounterBroadcast
                            .setNumReceived((long) server.getAttribute(name, attribute.getName()));
                    break;
                case "NumUnhandledErrors":
                    streamsTaskCounterBroadcast
                            .setNumUnhandledErrors((long) server.getAttribute(name, attribute.getName()));
                    break;
                case "AvgTime":
                    streamsTaskCounterBroadcast
                            .setAvgTime((double) server.getAttribute(name, attribute.getName()));
                    break;
                case "MaxTime":
                    streamsTaskCounterBroadcast
                            .setMaxTime((long) server.getAttribute(name, attribute.getName()));
                    break;
                }
            } catch (Exception e) {
                LOGGER.error("Exception while trying to deserialize StreamsTaskCounterBroadcast object: {}", e);
            }
        }

        return streamsTaskCounterBroadcast;
    } catch (Exception e) {
        LOGGER.error("Exception while trying to deserialize StreamsTaskCounterBroadcast object: {}", e);
        return null;
    }
}

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());

    ///*from w w w. j a  va 2 s . 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:com.streamsets.datacollector.bundles.content.SdcInfoContentGenerator.java

private void writeJmx(BundleWriter writer) throws IOException {
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();

    try (JsonGenerator generator = writer.createGenerator("runtime/jmx.json")) {
        generator.useDefaultPrettyPrinter();
        generator.writeStartObject();// ww  w. jav a2s .  c  o m
        generator.writeArrayFieldStart("beans");

        for (ObjectName objectName : mBeanServer.queryNames(null, null)) {
            MBeanInfo info;
            try {
                info = mBeanServer.getMBeanInfo(objectName);
            } catch (InstanceNotFoundException | IntrospectionException | ReflectionException ex) {
                LOG.warn("Exception accessing MBeanInfo ", ex);
                continue;
            }

            generator.writeStartObject();
            generator.writeStringField("name", objectName.toString());
            generator.writeObjectFieldStart("attributes");

            for (MBeanAttributeInfo attr : info.getAttributes()) {
                try {
                    writeAttribute(generator, attr.getName(),
                            mBeanServer.getAttribute(objectName, attr.getName()));
                } catch (MBeanException | AttributeNotFoundException | InstanceNotFoundException
                        | ReflectionException | RuntimeMBeanException ex) {
                    generator.writeStringField(attr.getName(), "Exception: " + ex.toString());
                }
            }

            generator.writeEndObject();
            generator.writeEndObject();
            writer.writeLn("");
        }

        generator.writeEndArray();
        generator.writeEndObject();
    } finally {
        writer.markEndOfFile();
    }
}

From source file:net.sbbi.upnp.jmx.upnp.UPNPConnectorServer.java

public void handleNotification(Notification notification, Object handBack) {

    if (notification.getType().equals(MBeanServerNotification.REGISTRATION_NOTIFICATION)) {
        MBeanServerNotification regNot = (MBeanServerNotification) notification;
        MBeanServer srv = getMBeanServer();
        ObjectName name = regNot.getMBeanName();
        try {/*from w  w w .j  a va2  s  .  c o m*/
            ObjectInstance objIn = srv.getObjectInstance(name);
            String className = objIn.getClassName();
            // do not expose as UPN, UPNP devices exposed as MBeans ( class UPNPServiceMBean purpose )
            if (className.equals(UPNPServiceMBean.class.getName()))
                return;
            if (builder.select(name, className)) {
                MBeanInfo info = srv.getMBeanInfo(name);
                UPNPMBeanDevice dv = builder.buildUPNPMBean(getMBeanServer(), objIn, info);
                if (dv != null) {
                    dv.setBindAddress(sktAddress);
                    dv.start();
                    registeredMBeans.put(name.toString(), dv);
                }
            }
        } catch (Exception ex) {
            log.error("Error during UPNP Mbean device " + name.toString() + " creation", ex);
        }
    } else if (notification.getType().equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)) {
        MBeanServerNotification regNot = (MBeanServerNotification) notification;
        String beanName = regNot.getMBeanName().toString();
        synchronized (STOP_PROCESS) {
            UPNPMBeanDevice dv = (UPNPMBeanDevice) registeredMBeans.get(beanName);
            if (dv != null) {
                try {
                    dv.stop();
                } catch (Exception ex) {
                    log.error("Error during UPNPMBean device stop", ex);
                }
                registeredMBeans.remove(beanName);
            }
        }
    }
}

From source file:com.jkoolcloud.tnt4j.streams.custom.kafka.interceptors.reporters.metrics.MetricsReporter.java

/**
 * Collects JMX attributes of MBeans defined by <tt>objNameStr</tt>.
 *
 * @param objNameStr//from   w w w . j av a 2 s.c  om
 *            MBeans object name pattern to query
 * @param mBeanServer
 *            MBean server instance to use
 * @param activity
 *            activity instance to put JMX metrics snapshots
 * @throws Exception
 *             if JMX attributes collecting fails
 */
public void collectMetricsJMX(String objNameStr, MBeanServer mBeanServer, Activity activity) throws Exception {
    ObjectName oName = new ObjectName(objNameStr);
    Set<ObjectName> metricsBeans = mBeanServer.queryNames(oName, null);

    for (ObjectName mBeanName : metricsBeans) {
        try {
            PropertySnapshot snapshot = new PropertySnapshot(mBeanName.getCanonicalName());
            MBeanInfo metricsBean = mBeanServer.getMBeanInfo(mBeanName);
            MBeanAttributeInfo[] pMetricsAttrs = metricsBean.getAttributes();
            for (MBeanAttributeInfo pMetricsAttr : pMetricsAttrs) {
                try {
                    String attrName = pMetricsAttr.getName();
                    Object attrValue = mBeanServer.getAttribute(mBeanName, attrName);
                    processAttrValue(snapshot, new PropertyNameBuilder(pMetricsAttr.getName()), attrValue);
                } catch (Exception exc) {
                    Utils.logThrowable(LOGGER, OpLevel.WARNING,
                            StreamsResources.getBundle(KafkaStreamConstants.RESOURCE_BUNDLE_NAME),
                            "MetricsReporter.bean.attr.fail", mBeanName, pMetricsAttr.getName(), exc);
                }
            }

            if (getSnapshotPropIgnoreCase(snapshot, OBJ_NAME_ENTRY_KEY) == null) {
                snapshot.add(OBJ_NAME_ENTRY_KEY, mBeanName.getCanonicalName());
            }
            if (useObjectNameProperties) {
                snapshot.add("domain", mBeanName.getDomain()); // NON-NLS
                Map<String, String> objNameProps = mBeanName.getKeyPropertyList();
                for (Map.Entry<String, String> objNameProp : objNameProps.entrySet()) {
                    String propKey = objNameProp.getKey();
                    Object mv = snapshot.get(propKey);
                    snapshot.add(propKey + (mv == null ? "" : "_"), objNameProp.getValue()); // NON-NLS
                }
            }
            activity.addSnapshot(snapshot);
        } catch (Exception exc) {
            Utils.logThrowable(LOGGER, OpLevel.WARNING,
                    StreamsResources.getBundle(KafkaStreamConstants.RESOURCE_BUNDLE_NAME),
                    "MetricsReporter.bean.info.fail", mBeanName, exc);
        }
    }
}

From source file:org.apache.catalina.mbeans.MBeanDumper.java

/**
 * The following code to dump MBeans has been copied from JMXProxyServlet.
 *
 *//* w w w  .  j  av  a2s .  c om*/
public static String dumpBeans(MBeanServer mbeanServer, Set<ObjectName> names) {
    StringBuilder buf = new StringBuilder();
    Iterator<ObjectName> it = names.iterator();
    while (it.hasNext()) {
        ObjectName oname = it.next();
        buf.append("Name: ");
        buf.append(oname.toString());
        buf.append(CRLF);

        try {
            MBeanInfo minfo = mbeanServer.getMBeanInfo(oname);
            // can't be null - I think
            String code = minfo.getClassName();
            if ("org.apache.commons.modeler.BaseModelMBean".equals(code)) {
                code = (String) mbeanServer.getAttribute(oname, "modelerType");
            }
            buf.append("modelerType: ");
            buf.append(code);
            buf.append(CRLF);

            MBeanAttributeInfo attrs[] = minfo.getAttributes();
            Object value = null;

            for (int i = 0; i < attrs.length; i++) {
                if (!attrs[i].isReadable())
                    continue;
                String attName = attrs[i].getName();
                if ("modelerType".equals(attName))
                    continue;
                if (attName.indexOf("=") >= 0 || attName.indexOf(":") >= 0 || attName.indexOf(" ") >= 0) {
                    continue;
                }

                try {
                    value = mbeanServer.getAttribute(oname, attName);
                } catch (JMRuntimeException rme) {
                    Throwable cause = rme.getCause();
                    if (cause instanceof UnsupportedOperationException) {
                        if (log.isDebugEnabled()) {
                            log.debug("Error getting attribute " + oname + " " + attName, rme);
                        }
                    } else if (cause instanceof NullPointerException) {
                        if (log.isDebugEnabled()) {
                            log.debug("Error getting attribute " + oname + " " + attName, rme);
                        }
                    } else {
                        log.error("Error getting attribute " + oname + " " + attName, rme);
                    }
                    continue;
                } catch (Throwable t) {
                    ExceptionUtils.handleThrowable(t);
                    log.error("Error getting attribute " + oname + " " + attName, t);
                    continue;
                }
                if (value == null)
                    continue;
                String valueString;
                try {
                    Class<?> c = value.getClass();
                    if (c.isArray()) {
                        int len = Array.getLength(value);
                        StringBuilder sb = new StringBuilder(
                                "Array[" + c.getComponentType().getName() + "] of length " + len);
                        if (len > 0) {
                            sb.append(CRLF);
                        }
                        for (int j = 0; j < len; j++) {
                            sb.append("\t");
                            Object item = Array.get(value, j);
                            if (item == null) {
                                sb.append("NULL VALUE");
                            } else {
                                try {
                                    sb.append(escape(item.toString()));
                                } catch (Throwable t) {
                                    ExceptionUtils.handleThrowable(t);
                                    sb.append("NON-STRINGABLE VALUE");
                                }
                            }
                            if (j < len - 1) {
                                sb.append(CRLF);
                            }
                        }
                        valueString = sb.toString();
                    } else {
                        valueString = escape(value.toString());
                    }
                    buf.append(attName);
                    buf.append(": ");
                    buf.append(valueString);
                    buf.append(CRLF);
                } catch (Throwable t) {
                    ExceptionUtils.handleThrowable(t);
                }
            }
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
        }
        buf.append(CRLF);
    }
    return buf.toString();

}

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

/**
 * @param mBeanServer// ww w  .j a v a 2  s.  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:org.apache.hadoop.hdfs.server.common.MetricsLoggerTask.java

/**
 * Write metrics to the metrics appender when invoked.
 *//*from   w w w .j a  va2  s .  c  o  m*/
@Override
public void run() {
    // Skip querying metrics if there are no known appenders.
    if (!metricsLog.isInfoEnabled() || !hasAppenders(metricsLog) || objectName == null) {
        return;
    }

    metricsLog.info(" >> Begin " + nodeName + " metrics dump");
    final MBeanServer server = ManagementFactory.getPlatformMBeanServer();

    // Iterate over each MBean.
    for (final ObjectName mbeanName : server.queryNames(objectName, null)) {
        try {
            MBeanInfo mBeanInfo = server.getMBeanInfo(mbeanName);
            final String mBeanNameName = MBeans.getMbeanNameName(mbeanName);
            final Set<String> attributeNames = getFilteredAttributes(mBeanInfo);

            final AttributeList attributes = server.getAttributes(mbeanName,
                    attributeNames.toArray(new String[attributeNames.size()]));

            for (Object o : attributes) {
                final Attribute attribute = (Attribute) o;
                final Object value = attribute.getValue();
                final String valueStr = (value != null) ? value.toString() : "null";
                // Truncate the value if it is too long
                metricsLog.info(mBeanNameName + ":" + attribute.getName() + "=" + trimLine(valueStr));
            }
        } catch (Exception e) {
            metricsLog.error("Failed to get " + nodeName + " metrics for mbean " + mbeanName.toString(), e);
        }
    }
    metricsLog.info(" << End " + nodeName + " metrics dump");
}

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

private void invoke(final String value) {
    if (!value.contains("(") || !value.contains(")")) {
        streamManager.writeErr("method should follow the format: <methoName>(<arg1>,<arg2>,...)");
        return;// ww  w  .jav  a2s .  com
    }

    int open = value.indexOf("(");
    int close = value.lastIndexOf(")");

    final String name = value.substring(0, open).trim();
    final String rawArgs = value.substring(open + 1, close).trim();
    final ObjectName on;
    try {
        on = new ObjectName(value.substring(close + 1).trim());
    } catch (MalformedObjectNameException e) {
        streamManager.writeErr(e);
        return;
    }

    final MBeanServer server = LocalMBeanServer.get();
    final String[] args;
    if (rawArgs == null || rawArgs.isEmpty()) {
        args = new String[0];
    } else {
        args = rawArgs.split(",");
    }

    try {
        final MBeanInfo minfo = server.getMBeanInfo(on);
        final MBeanOperationInfo[] methods = minfo.getOperations();

        MBeanOperationInfo operation = null;
        for (int i = 0; i < methods.length; i++) {
            if (methods[i].getName().equals(name)) {
                operation = methods[i];
                break;
            }
        }

        if (operation == null) {
            streamManager.writeErr("can't find operation '" + name + "'");
            return;
        }

        final Object[] passedArgs = new Object[args.length];
        final String[] passedArgTypes = new String[args.length];
        for (int i = 0; i < passedArgs.length; i++) {
            final String expected = operation.getSignature()[i].getType();
            if (!String.class.getName().equals(expected)) {
                passedArgs[i] = PropertyEditors.getValue(expected, args[i],
                        Thread.currentThread().getContextClassLoader());
            } else {
                passedArgs[i] = args[i];
            }
            passedArgTypes[i] = expected;
        }

        streamManager.writeOut(stringify(server.invoke(on, name, passedArgs, passedArgTypes)));
    } catch (Exception e) {
        streamManager.writeErr(e);
        return;
    }
}