Example usage for javax.management MBeanServerConnection getAttribute

List of usage examples for javax.management MBeanServerConnection getAttribute

Introduction

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

Prototype

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

Source Link

Document

Gets the value of a specific attribute of a named MBean.

Usage

From source file:org.opennms.features.jmxconfiggenerator.jmxconfig.JmxDatacollectionConfiggenerator.java

private CompAttrib createCompAttrib(MBeanServerConnection jmxServerConnection, ObjectInstance jmxObjectInstance,
        MBeanAttributeInfo jmxMBeanAttributeInfo) {
    Boolean contentAdded = false;

    CompAttrib xmlCompAttrib = xmlObjectFactory.createCompAttrib();
    xmlCompAttrib.setName(jmxMBeanAttributeInfo.getName());
    xmlCompAttrib.setType("Composite");
    xmlCompAttrib.setAlias(jmxMBeanAttributeInfo.getName());

    CompositeData compositeData;/*from   w  w w  . j a v a2s .c  o  m*/
    try {
        logger.debug("Try to get composite data");
        compositeData = (CompositeData) jmxServerConnection.getAttribute(jmxObjectInstance.getObjectName(),
                jmxMBeanAttributeInfo.getName());
        if (compositeData == null) {
            logger.warn(
                    "compositeData is null. jmxObjectInstance.getObjectName: '{}', jmxMBeanAttributeInfo.getName: '{}'");
        }
        if (compositeData != null) {
            logger.debug("compositeData.getCompositeType: '{}'", compositeData.getCompositeType());
            Set<String> keys = compositeData.getCompositeType().keySet();
            for (String key : keys) {
                Object compositeEntry = compositeData.get(key);
                if (numbers.contains(compositeEntry.getClass().getName())) {
                    contentAdded = true;
                    CompMember xmlCompMember = xmlObjectFactory.createCompMember();
                    xmlCompMember.setName(key);

                    logger.debug("composite member pure alias: '{}'",
                            jmxMBeanAttributeInfo.getName() + StringUtils.capitalize(key));
                    String alias = nameCutter
                            .trimByDictionary(jmxMBeanAttributeInfo.getName() + StringUtils.capitalize(key));
                    alias = createAndRegisterUniqueAlias(alias);
                    xmlCompMember.setAlias(alias);
                    logger.debug("composite member trimmed alias: '{}'", alias);

                    xmlCompMember.setType("gauge");
                    xmlCompAttrib.getCompMember().add(xmlCompMember);

                } else {
                    logger.debug("composite member key '{}' object's class '{}' was not a number.", key,
                            compositeEntry.getClass().getName());
                }
            }
        }
    } catch (Exception e) {
        logger.error("killed in action: '{}'", e.getMessage());
    }

    if (contentAdded) {
        logger.debug("xmlCompAttrib returned by createCompAttrib it's '{}'", xmlCompAttrib);
        return xmlCompAttrib;
    }
    return null;
}

From source file:net.sf.ehcache.management.ManagementServiceTest.java

private void traverseMBeanAttributes(MBeanServerConnection connection, String type)
        throws JMException, IOException {
    Set objectNames = connection.queryNames(new ObjectName("net.sf.ehcache:type=" + type + ",*"), null);
    for (Iterator iterator = objectNames.iterator(); iterator.hasNext();) {
        ObjectName objectName = (ObjectName) iterator.next();
        MBeanInfo mBeanInfo = connection.getMBeanInfo(objectName);
        MBeanAttributeInfo[] attributes = mBeanInfo.getAttributes();
        for (int i = 0; i < attributes.length; i++) {
            MBeanAttributeInfo attribute = attributes[i];
            LOG.info(attribute.getName() + " " + connection.getAttribute(objectName, attribute.getName()));
        }/*from   w w  w. ja  va  2s  . co m*/
    }
}

From source file:org.springframework.integration.jmx.DefaultMBeanObjectConverter.java

@Override
public Object convert(MBeanServerConnection connection, ObjectInstance instance) {
    Map<String, Object> attributeMap = new HashMap<String, Object>();

    try {/*from  ww w  .j av  a2  s .  com*/
        ObjectName objName = instance.getObjectName();
        if (!connection.isRegistered(objName)) {
            return attributeMap;
        }

        MBeanInfo info = connection.getMBeanInfo(objName);
        MBeanAttributeInfo[] attributeInfos = info.getAttributes();

        for (MBeanAttributeInfo attrInfo : attributeInfos) {
            // we don't need to repeat name of this as an attribute
            if ("ObjectName".equals(attrInfo.getName()) || !this.filter.accept(objName, attrInfo.getName())) {
                continue;
            }

            Object value;
            try {
                value = connection.getAttribute(objName, attrInfo.getName());
            } catch (RuntimeMBeanException e) {
                // N.B. standard MemoryUsage MBeans will throw an exception when some
                // measurement is unsupported. Logging at trace rather than debug to
                // avoid confusion.
                if (log.isTraceEnabled()) {
                    log.trace("Error getting attribute '" + attrInfo.getName() + "' on '" + objName + "'", e);
                }

                // try to unwrap the exception somewhat; not sure this is ideal
                Throwable t = e;
                while (t.getCause() != null) {
                    t = t.getCause();
                }
                value = String.format("%s[%s]", t.getClass().getName(), t.getMessage());
            }

            attributeMap.put(attrInfo.getName(), checkAndConvert(value));
        }

    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }

    return attributeMap;
}

From source file:io.fabric8.test.smoke.JolokiaEndpointTestBase.java

@Test
public void testMXBeanEndpoint() throws Exception {

    ContainerManager cntManager = ContainerManagerLocator.getContainerManager();
    Container cnt = cntManager.getCurrentContainer();

    ServiceEndpoint sep = cnt.getServiceEndpoint(URLServiceEndpoint.JMX_SERVICE_ENDPOINT_IDENTITY);
    JMXServiceEndpoint jmxEndpoint = sep.adapt(JMXServiceEndpoint.class);
    String serviceURL = jmxEndpoint.getServiceURL();
    Assert.assertNotNull("JMX URL not null", serviceURL);

    // Get the local MBeanServer
    MBeanServer server = ServiceLocator.getRequiredService(MBeanServer.class);
    server.registerMBean(new Simple(), SimpleMXBean.OBJECT_NAME);
    try {/*  w  w  w . j  a  v a 2s . c  om*/
        String[] userpass = RuntimeType.KARAF == RuntimeType.getRuntimeType() ? karafJmx : otherJmx;
        JMXConnector jmxConnector = jmxEndpoint.getJMXConnector(userpass[0], userpass[1], 200,
                TimeUnit.MILLISECONDS);
        MBeanServerConnection con = jmxConnector.getMBeanServerConnection();
        try {
            // Simple string echo
            Object[] params = new Object[] { "Kermit" };
            String[] signature = new String[] { String.class.getName() };
            Object result = con.invoke(SimpleMXBean.OBJECT_NAME, "echo", params, signature);
            Assert.assertEquals("Hello: Kermit", result);

            // Set Bean attribute using CompositeData
            Bean bean = new Bean("Hello", "Foo");
            CompositeData cdata = OpenTypeGenerator.toCompositeData(bean);
            con.setAttribute(SimpleMXBean.OBJECT_NAME, new Attribute("Bean", cdata));

            // Get Bean attribute using CompositeData
            cdata = (CompositeData) con.getAttribute(SimpleMXBean.OBJECT_NAME, "Bean");
            Assert.assertEquals(bean, OpenTypeGenerator.fromCompositeData(Bean.class, cdata));

            // Simple Bean echo using CompositeData
            params = new Object[] { cdata };
            signature = new String[] { CompositeData.class.getName() };
            cdata = (CompositeData) con.invoke(SimpleMXBean.OBJECT_NAME, "echoBean", params, signature);
            Assert.assertEquals(bean, OpenTypeGenerator.fromCompositeData(Bean.class, cdata));
        } finally {
            jmxConnector.close();
        }
    } finally {
        server.unregisterMBean(SimpleMXBean.OBJECT_NAME);
    }
}

From source file:com.betfair.testing.utils.cougar.helpers.CougarHelpers.java

private Object getJMXMBeanAttributeValue(String mBeanName, String attributeName) {

    try {/* w  w  w . ja v  a  2 s  .com*/
        MBeanServerConnection mBeanServerConnection = getJMXConnection();
        ObjectName mbeanName = new ObjectName(mBeanName);
        return mBeanServerConnection.getAttribute(mbeanName, attributeName);

    } catch (Exception e) {
        throw new RuntimeException(JMX_RETRIEVAL_ERROR + mBeanName + ": " + attributeName, e);
    }
}

From source file:org.xmatthew.spy2servers.component.spy.jmx.JmxSpySupportComponent.java

public Map<String, Object> getAttributesAsMap(String mbeanName, MBeanServerConnection mbsc) throws Exception {
    ObjectName mbean = new ObjectName(mbeanName);
    MBeanInfo info = null;/*  w w  w  . jav a 2  s . c  om*/
    try {
        info = mbsc.getMBeanInfo(mbean);
    } catch (Exception e) {
        //ignore the exception
    }

    if (info != null) {
        MBeanAttributeInfo[] attributes;
        attributes = info.getAttributes();
        if (attributes == null) {
            return null;
        }

        int size = attributes.length;
        if (size == 0) {
            return null;
        }

        Map<String, Object> beansMap = new HashMap<String, Object>(size);
        for (int i = 0; i < size; i++) {
            try {
                beansMap.put(attributes[i].getName(), mbsc.getAttribute(mbean, attributes[i].getName()));
            } catch (Exception e) {
                //ignore the exception
            }
        }
        return beansMap;
    }
    return null;
}

From source file:com.betfair.testing.utils.cougar.helpers.CougarHelpers.java

private void setJMXMBeanAttribute(String mBeanName, String attributeName, Object newMbeanValue) {

    try {//from ww  w.  j av  a  2 s  .  com
        MBeanServerConnection mBeanServerConnection = getJMXConnection();
        ObjectName mbeanName = new ObjectName(mBeanName);
        Object currentAttributeValue = mBeanServerConnection.getAttribute(mbeanName, attributeName);
        Object reflectedValue = reflect.getRealProperty(currentAttributeValue.getClass(), newMbeanValue);
        Attribute attribute = new Attribute(attributeName, reflectedValue);
        mBeanServerConnection.setAttribute(mbeanName, attribute);
    } catch (Exception e) {
        throw new RuntimeException(JMX_SETTING_ERROR + mBeanName + ": " + attributeName, e);
    }
}

From source file:org.rhq.plugins.jslee.JainSleeServerComponent.java

public AvailabilityType getAvailability() {
    if (log.isTraceEnabled()) {
        log.trace("getAvailability() called.");
    }//w  ww.j  a  v a 2 s.c om

    if (this.mBeanServerUtils != null) {
        try {
            ObjectName sleemanagement = new ObjectName(SleeManagementMBean.OBJECT_NAME);
            MBeanServerConnection connection = this.mBeanServerUtils.getConnection();
            mBeanServerUtils.login();

            this.sleeState = (SleeState) connection.getAttribute(sleemanagement, "State");

            if (log.isDebugEnabled()) {
                log.debug("JAIN SLEE State = " + this.sleeState);
            }
            return AvailabilityType.UP;

        } catch (Exception e) {
            log.error("Failed to obtain JAIN SLEE Server state.", e);
            return AvailabilityType.DOWN;
        } finally {
            try {
                this.mBeanServerUtils.logout();
            } catch (LoginException e) {
                if (log.isDebugEnabled()) {
                    log.debug("Failed to logout from secured JMX", e);
                }
            }
        }
    } else {
        log.error("Returning availability as DOWN");
        return AvailabilityType.DOWN;
    }
}

From source file:org.hyperic.hq.product.jmx.MxQuery.java

public void getAttributes(MBeanServerConnection mServer) throws PluginException {

    String[] names = getAttributeNames();

    if (names.length == 0) {
        this.cprops = EMPTY_PROPERTIES;
        return;/*  w w  w  .  j  a v  a 2  s.  c o  m*/
    }

    for (int i = 0; i < names.length; i++) {
        String name = names[i];
        ObjectName objName;

        int ix = name.lastIndexOf(':');
        if (ix == -1) {
            //"serverVersion"
            objName = getObjectName();
        } else {
            //domain:Key=Val:serverVersion
            try {
                objName = new ObjectName(name.substring(0, ix));
            } catch (MalformedObjectNameException e) {
                throw new PluginException(name, e);
            }
            name = name.substring(ix + 1);
        }

        Object value;
        try {
            value = mServer.getAttribute(objName, name);
        } catch (Exception e) {
            log.debug("getAttribute(" + objName + ", " + name + ") failed", e);
            continue;
        }
        if (value != null) {
            String stringValue;
            if (value instanceof Object[]) {
                stringValue = Arrays.asList((Object[]) value).toString();
            } else {
                stringValue = value.toString();
            }
            setAttribute(names[i], stringValue);
        } else {
            // Show 'Attribute was null' in UI.
            log.debug("getAttribute(" + objName + ", " + name + ") returned null");
            setAttribute(names[i], "Attribute was null");
        }
    }

    this.cprops = new Properties();
    this.cprops.putAll(this.attrs);
}

From source file:org.cipango.console.printer.ApplicationPrinter.java

public ApplicationPrinter(MBeanServerConnection connection) throws Exception {
    ObjectName[] sipContexts = PrinterUtil.getSipAppContexts(connection);

    Table contextsTable = new Table(connection, sipContexts, "appContexts");

    add(new SetPrinter(contextsTable));

    ObjectName[] otherContexts = PrinterUtil.getNonSipAppContexts(connection);
    if (otherContexts != null && otherContexts.length > 0) {
        Table otherContextsTable = new Table(connection, otherContexts, "otherContexts");
        for (Row row : otherContextsTable) {
            int index = 0;
            for (Header header : contextsTable.getHeaders()) {
                Value value = row.get(header);
                if (value == null)
                    row.getValues().add(index, new Value("N/A", header));
                index++;//from  w  w w.jav  a 2s  .  c  o m
            }
            contextsTable.add(row);
        }
    }

    for (Row row : contextsTable) {
        boolean running = (Boolean) connection.getAttribute(row.getObjectName(), "running");
        if (running)
            row.addOperation(new AppActionPrinter(STOP_APP, row.getObjectName()));
        else
            row.addOperation(new AppActionPrinter(START_APP, row.getObjectName()));

        row.addOperation(new AppActionPrinter(UNDEPLOY_APP, row.getObjectName()));
    }

    add(new ServletMappingPrinter(sipContexts, connection));
    add(DEPLOY_APP);
}