Example usage for javax.management MBeanServer getAttributes

List of usage examples for javax.management MBeanServer getAttributes

Introduction

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

Prototype

public AttributeList getAttributes(ObjectName name, String[] attributes)
        throws InstanceNotFoundException, ReflectionException;

Source Link

Usage

From source file:utilities.srvRutinas.java

public static double getProcessCpuLoad() throws Exception {

    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem");
    AttributeList list = mbs.getAttributes(name, new String[] { "ProcessCpuLoad" });

    if (list.isEmpty())
        return Double.NaN;

    Attribute att = (Attribute) list.get(0);
    Double value = (Double) att.getValue();

    // usually takes a couple of seconds before we get real values
    if (value == -1.0)
        return Double.NaN;
    // returns a percentage value with 1 decimal point precision
    return ((int) (value * 1000) / 10.0);
}

From source file:org.apache.jackrabbit.oak.run.osgi.OakOSGiRepositoryFactory.java

/**
 * Registers the Platform MBeanServer as OSGi service. This would enable
 * Aries JMX Whitboard support to then register the JMX MBean which are registered as OSGi service
 * to be registered against the MBean server
 *///  ww w  .j  av a2  s . c o m
private static void registerMBeanServer(PojoServiceRegistry registry) {
    MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
    Hashtable<String, Object> mbeanProps = new Hashtable<String, Object>();
    try {
        ObjectName beanName = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate");
        AttributeList attrs = platformMBeanServer.getAttributes(beanName,
                new String[] { "MBeanServerId", "SpecificationName", "SpecificationVersion",
                        "SpecificationVendor", "ImplementationName", "ImplementationVersion",
                        "ImplementationVendor" });
        for (Object object : attrs) {
            Attribute attr = (Attribute) object;
            if (attr.getValue() != null) {
                mbeanProps.put(attr.getName(), attr.getValue().toString());
            }
        }
    } catch (Exception je) {
        log.info("Cannot set service properties of Platform MBeanServer service, registering without", je);
    }
    registry.registerService(MBeanServer.class.getName(), platformMBeanServer, mbeanProps);
}

From source file:com.amazonaws.client.metrics.support.JmxInfoProviderSupport.java

@Override
public long[] getFileDecriptorInfo() {
    MBeanServer mbsc = MBeans.getMBeanServer();
    AttributeList attributes;/*  w  ww . j  a  v  a2  s  . c  o  m*/
    try {
        attributes = mbsc.getAttributes(new ObjectName("java.lang:type=OperatingSystem"),
                new String[] { "OpenFileDescriptorCount", "MaxFileDescriptorCount" });
        List<Attribute> attrList = attributes.asList();
        long openFdCount = (Long) attrList.get(0).getValue();
        long maxFdCount = (Long) attrList.get(1).getValue();
        long[] fdCounts = { openFdCount, maxFdCount };
        return fdCounts;
    } catch (Exception e) {
        LogFactory.getLog(SdkMBeanRegistrySupport.class).debug("Failed to retrieve file descriptor info", e);
    }
    return null;
}

From source file:io.soabase.core.SoaBundle.java

private void addMetrics(Environment environment) {
    Metric metric = new Gauge<Double>() {
        private double lastValue = 0.0;

        @Override/*from   w  w  w .j a va2 s  .c  o  m*/
        public Double getValue() {
            try {
                MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
                ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem");
                AttributeList list = mbs.getAttributes(name, new String[] { "SystemCpuLoad" });
                if ((list != null) && (list.size() > 0)) {
                    // unfortunately, this bean reports bad values occasionally. Filter them out.
                    Object value = list.asList().get(0).getValue();
                    double d = (value instanceof Number) ? ((Number) value).doubleValue() : 0.0;
                    d = ((d > 0.0) && (d < 1.0)) ? d : lastValue;
                    lastValue = d;
                    return d;
                }
            } catch (Exception ignore) {
                // ignore
            }
            return lastValue;
        }
    };
    environment.metrics().register("system.cpu.load", metric);
}

From source file:org.hyperic.hq.plugin.weblogic.jmx.AttributeGetter.java

public Object getAttribute(MBeanServer server, String attrName)
        throws InstanceNotFoundException, ReflectionException, AttributeNotFoundException {

    long timeNow = System.currentTimeMillis();

    if ((timeNow - this.timestamp) > this.expire) {
        AttributeList attrList;//from   w  ww  .j  a va  2  s  . c o  m

        if (log.isDebugEnabled()) {
            log.debug("server.getAttributes(" + this.name + ", " + Arrays.asList(this.attrs) + ")");
        }

        attrList = server.getAttributes(this.name, this.attrs);

        if (attrList == null) {
            throw new AttributeNotFoundException(this.name.toString());
        }

        for (Iterator it = attrList.iterator(); it.hasNext();) {

            Attribute attr = (Attribute) it.next();

            this.values.put(attr.getName(), attr.getValue());
        }

        this.timestamp = timeNow;
    }

    Object value = this.values.get(attrName);

    if (value == null) {
        throw new AttributeNotFoundException(attrName);
    }

    return value;
}

From source file:org.hyperic.hq.plugin.weblogic.jmx.WeblogicQuery.java

public boolean getAttributes(MBeanServer mServer, ObjectName name, String[] attrNames) {

    if (name == null) {
        return false;
    }/*from   w w  w .j a  va 2  s. c o m*/
    if (attrNames.length == 0) {
        setName(name.getKeyProperty("Name"));
        return true;
    }

    AttributeList list;

    try {
        list = mServer.getAttributes(name, attrNames);
    } catch (InstanceNotFoundException e) {
        //given that the ObjectName is from queryNames
        //returned by the server this should not happen.
        //however, it is possible when nodes are not properly
        //configured.
        logAttrFailure(name, attrNames, e);
        return false;
    } catch (ReflectionException e) {
        //this should not happen either
        logAttrFailure(name, attrNames, e);
        return false;
    }

    if (list == null) {
        //only 6.1 seems to behave this way,
        //modern weblogics throw exceptions.
        return false;
    }

    for (int i = 0; i < list.size(); i++) {
        Attribute attr = (Attribute) list.get(i);
        Object obj = attr.getValue();
        if (obj != null) {
            this.attrs.put(attr.getName(), obj.toString());
        }
    }

    return true;
}

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  v a 2  s  . com
@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.mc4j.ems.impl.jmx.connection.bean.DMBean.java

public List<EmsAttribute> refreshAttributes(List<String> attributeNames) {
    if (info == null)
        loadSynchronous();//w  w w  .  ja  v  a 2s  . c o  m

    MBeanServer server = getConnectionProvider().getMBeanServer();

    try {
        String[] names = attributeNames.toArray(new String[attributeNames.size()]);

        AttributeList attributeList = server.getAttributes(getObjectName(), names);

        List<EmsAttribute> attributeResults = new ArrayList<EmsAttribute>();

        Iterator iter = attributeList.iterator();
        while (iter.hasNext()) {
            Attribute attr = (Attribute) iter.next();
            EmsAttribute attribute = getAttribute(attr.getName());

            attribute.alterValue(attr.getValue());

            //                if (!values.containsKey(attribute.getName())) {
            //                    attribute.setSupportedType(false);
            //                }

            attributeResults.add(attribute);

        }
        return attributeResults;
    } catch (InstanceNotFoundException infe) {
        this.deleted = true;
        this.attributes = null;
        this.operations = null;
        this.notifications = null;

        throw new RuntimeException("Unable to load attributes, bean not found", infe);
    } catch (Exception e) {
        // TODO: determine which exceptions to register, which to throw and what to log
        //                e.printStackTrace();

        // Don't load them as a set anymore...
        this.hasUnsupportedType = true;
        //System.out.println(ExceptionUtility.printStackTracesToString(e));

        // If we still we're unable to load all the attributes at once
        // lets load as many as we can, one at a time.
        //            for (EmsAttribute attribute : getAttributes()) {
        //                attribute.refresh();
        //            }

        throw new RuntimeException(
                "Unable to load attributes on bean [" + getBeanName().toString() + "] " + e.getMessage(), e);
    }
    //        } else {
    //            // If the object has unsupported attribute types
    //            // lets load as many as we can, one at a time.
    //            System.out.println("Loading individually: " + getObjectName().getCanonicalName());
    //            for (EmsAttribute attribute : getAttributes()) {
    //                attribute.refresh();
    //            }
    //        }

}

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 av a  2 s. c  o  m
    // 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();
}