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.hyperic.hq.product.jmx.MxUtil.java

private static Object getAttribute(MBeanServerConnection mServer, ObjectName obj, String name)
        throws MetricUnreachableException, MetricNotFoundException, PluginException, ReflectionException,
        InstanceNotFoundException, MBeanException, IOException {

    if (name.startsWith("get")) {
        name = name.substring(3);/*from  w ww  . j  a v  a 2  s .  c om*/
    }

    try {
        return mServer.getAttribute(obj, name);
    } catch (AttributeNotFoundException e) {
        throw new MetricNotFoundException(e.getMessage(), e);
    }
}

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

static Double getJSR77Statistic(MBeanServerConnection mServer, ObjectName objName, String attribute)
        throws MalformedURLException, MalformedObjectNameException, IOException, MBeanException,
        AttributeNotFoundException, InstanceNotFoundException, ReflectionException, PluginException {

    Stats stats;//from w  ww  .  j  a  v a 2s .c o  m
    Boolean provider = (Boolean) mServer.getAttribute(objName, "statisticsProvider");
    if ((provider == null) || !provider.booleanValue()) {
        String msg = objName + " does not provide statistics";
        throw new PluginException(msg);
    }

    stats = (Stats) mServer.getAttribute(objName, "stats");

    if (stats == null) {
        throw new PluginException(objName + " has no stats");
    }

    String statName = attribute.substring(STATS_PREFIX.length());
    Statistic stat = stats.getStatistic(statName);
    if (stat == null) {
        String msg = "Statistic '" + statName + "' not found [" + objName + "]";
        throw new AttributeNotFoundException(msg);
    }

    long value;
    if (stat instanceof CountStatistic) {
        value = ((CountStatistic) stat).getCount();
    } else if (stat instanceof RangeStatistic) {
        value = ((RangeStatistic) stat).getCurrent();
    } else if (stat instanceof TimeStatistic) {
        // get the average time
        long count = ((TimeStatistic) stat).getCount();
        if (count == 0)
            value = 0;
        else
            value = ((TimeStatistic) stat).getTotalTime() / count;
    } else {
        String msg = "Unsupported statistic type [" + statName.getClass().getName() + " for [" + objName + ":"
                + attribute + "]";
        throw new MetricInvalidException(msg);
    }

    //XXX: handle bug with geronimo uptime metric
    if (statName.equals("UpTime")) {
        value = System.currentTimeMillis() - value;
    }

    return new Double(value);
}

From source file:com.mustardgrain.solr.SolrClient.java

private static Runnable getStatsRunner(final WeakReference<SolrClient> lbRef) {
    return new Runnable() {

        @Override/*from   ww w  .  j  ava  2s  .co m*/
        public void run() {
            SolrClient lb = lbRef.get();
            if (lb != null && lb.serverStats != null && LOG.isInfoEnabled()) {
                StringBuilder sb = new StringBuilder();
                sb.append("server responses over past ");
                sb.append(TimeUnit.MILLISECONDS.toMinutes(lb.statsInterval));
                sb.append(" mins (good/timeout/zero found) and cache hit ratio: ");
                boolean appendComma = false;

                for (Map.Entry<String, SolrStats> entry : lb.serverStats.entrySet()) {
                    if (appendComma)
                        sb.append(", ");

                    String server = entry.getKey();
                    SolrStats stats = entry.getValue();
                    String hitRatio = getHitRatio(server);

                    sb.append(server);
                    sb.append(": ");
                    sb.append(stats.getSuccesses());
                    sb.append("/");
                    sb.append(stats.getReadTimeouts());
                    sb.append("/");
                    sb.append(stats.getEmptyResults());
                    sb.append(" ");
                    sb.append(hitRatio);

                    appendComma = true;

                    stats.reset(); // Reset the counters once printed
                }

                LOG.info(sb);
            }
        }

        /**
         * Determines the hit ratio for the query result cache by calling
         * the SolrServer via JMX and reading its MBean containing that
         * information.
         * @param server Server from which to pull information
         * @return String form of hit ratio (either "n/a" or "xx%")
         */

        private String getHitRatio(String server) {
            String hitRatio = "n/a";
            JMXConnector jmxc = null;

            try {
                URL url = new URL(server);
                String domain = url.getPath();

                if (domain.startsWith("/"))
                    domain = domain.substring(1);

                ObjectName name = new ObjectName(
                        domain + ":id=org.apache.solr.search.LRUCache,type=queryResultCache");
                JMXServiceURL jmxUrl = new JMXServiceURL(
                        "service:jmx:rmi:///jndi/rmi://" + url.getHost() + ":7199/jmxrmi");
                jmxc = JMXConnectorFactory.connect(jmxUrl, null);
                MBeanServerConnection con = jmxc.getMBeanServerConnection();

                Object result = con.getAttribute(name, "hitratio");
                hitRatio = (int) (Float.parseFloat(String.valueOf(result)) * 100.0f) + "%";
            } catch (Exception e) {
                LOG.error(getNestedErrorMessages(e));
            } finally {
                if (jmxc != null) {
                    try {
                        jmxc.close();
                    } catch (Exception e) {
                        LOG.error(getNestedErrorMessages(e));
                    }
                }
            }

            return hitRatio;
        }

    };
}

From source file:dk.netarkivet.common.utils.JMXUtils.java

/** Get the value of an attribute from a bean.
 *
 * @param beanName Name of the bean to get an attribute for.
 * @param attribute Name of the attribute to get.
 * @param connection A connection to the JMX server for the bean.
 * @return Value of the attribute.//www. j a  v a  2 s. c o  m
 */
public static Object getAttribute(String beanName, String attribute, MBeanServerConnection connection) {
    ArgumentNotValid.checkNotNullOrEmpty(beanName, "String beanName");
    ArgumentNotValid.checkNotNullOrEmpty(attribute, "String attribute");
    ArgumentNotValid.checkNotNull(connection, "MBeanServerConnection connection");

    log.debug("Preparing to get attribute " + attribute + " on " + beanName);
    final int maxJmxRetries = getMaxTries();
    try {
        // The first time we attempt to connect to an mbean, we might have
        // to wait a bit for it to appear
        Throwable lastException;
        int tries = 0;
        do {
            tries++;
            try {
                Object ret = connection.getAttribute(getBeanName(beanName), attribute);
                log.debug("Getting attribute " + attribute + " returned " + ret);
                return ret;
            } catch (InstanceNotFoundException e) {
                log.trace("Error while getting attribute " + attribute + " on " + beanName, e);
                lastException = e;
                if (tries < maxJmxRetries) {
                    TimeUtils.exponentialBackoffSleep(tries);
                }
            } catch (IOException e) {
                log.trace("Error while getting attribute " + attribute + " on " + beanName, e);
                lastException = e;
                if (tries < maxJmxRetries) {
                    TimeUtils.exponentialBackoffSleep(tries);
                }
            }
        } while (tries < maxJmxRetries);
        throw new IOFailure("Failed to find MBean " + beanName + " for getting attribute " + attribute
                + " after " + tries + " attempts", lastException);
    } catch (AttributeNotFoundException e) {
        throw new IOFailure("MBean exception for " + beanName, e);
    } catch (MBeanException e) {
        throw new IOFailure("MBean exception for " + beanName, e);
    } catch (ReflectionException e) {
        throw new IOFailure("Reflection exception for " + beanName, e);
    }
}

From source file:com.athena.dolly.console.module.jmx.JmxClientManager.java

public static HashMap<String, Object> getObjectNameInfo(ObjectName objName, String nodeName) {
    JmxClient jmxClient = jmxClientMap.get(nodeName);

    try {/*from  w w  w.jav a 2 s. c  o  m*/
        MBeanServerConnection connection = jmxClient.getJmxConnector().getMBeanServerConnection();
        HashMap<String, Object> infoMap = new HashMap<String, Object>();
        Set<ObjectName> names = new TreeSet<ObjectName>(connection.queryNames(objName, null));

        for (ObjectName name : names) {
            logger.info("#######################");
            logger.info("\tObjectName = " + name);

            MBeanInfo info = connection.getMBeanInfo(name);
            MBeanAttributeInfo[] attributes = info.getAttributes();

            for (MBeanAttributeInfo attr : attributes) {
                logger.info("==========================");
                logger.info("attrName = " + attr.getName());
                logger.info("attrType = " + attr.getType());
                logger.info("connection.getAttribute = " + connection.getAttribute(name, attr.getName()));

                infoMap.put(attr.getName(), connection.getAttribute(name, attr.getName()));
            }
        }

        return infoMap;
    } catch (Exception e) {
        logger.error("unhandled exception has errored : ", e);
    }

    return null;
}

From source file:com.lmig.cf.metrics.opsmetrics.OpsMetrics.java

private boolean metricValueIsNumber(MBeanServerConnection connection, ObjectInstance object, String attribute) {
    try {/*from   w  w  w.  java 2 s  .c  om*/
        return connection.getAttribute(object.getObjectName(), attribute) instanceof Number;
    } catch (AttributeNotFoundException | InstanceNotFoundException | MBeanException | ReflectionException
            | IOException e) {
        return false;
    }
}

From source file:com.lmig.cf.metrics.opsmetrics.OpsMetrics.java

private Number getAttributeValue(MBeanServerConnection connection, ObjectInstance object, String attribute) {
    try {/*from ww  w  .  jav  a  2 s .c om*/
        return (Number) connection.getAttribute(object.getObjectName(), attribute);
    } catch (AttributeNotFoundException | InstanceNotFoundException | MBeanException | ReflectionException
            | IOException e) {
        return 0;
    }
}

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

static Object getCompositeMetric(MBeanServerConnection mServer, ObjectName objName, String attribute)
        throws MalformedURLException, MalformedObjectNameException, IOException, MBeanException,
        AttributeNotFoundException, InstanceNotFoundException, ReflectionException, PluginException {

    String name = attribute.substring(COMPOSITE_PREFIX.length());

    int ix = name.indexOf('.');
    if (ix == -1) {
        throw new MetricInvalidException("Missing composite key");
    }//from w w  w .jav a2  s . co  m

    String attr = name.substring(0, ix);
    String key = name.substring(ix + 1);

    Object obj = mServer.getAttribute(objName, attr);
    if (obj instanceof CompositeData) {
        return MxCompositeData.getValue((CompositeData) obj, key);
    } else {
        throw new MetricInvalidException("Not CompositeData");
    }
}

From source file:org.jboss.as.test.integration.mgmt.access.AbstractJmxNonCoreMBeansSensitivityTestCase.java

private void getAttribute(String userName, JmxManagementInterface jmx) throws Exception {
    boolean successExpected = isReadAllowed(userName);

    MBeanServerConnection connection = jmx.getConnection();
    ObjectName domain = new ObjectName("java.lang:type=OperatingSystem");
    try {/*from  w  w w. j  av  a  2 s .com*/
        Object attribute = connection.getAttribute(domain, "Name");
        assertTrue("Failure was expected", successExpected);
        assertEquals(System.getProperty("os.name"), attribute.toString());
    } catch (JMRuntimeException e) {
        if (e.getMessage().contains("WFLYJMX0037")) {
            assertFalse("Success was expected but failure happened: " + e, successExpected);
        } else {
            throw e;
        }
    }
}

From source file:org.wso2.carbon.esb.mediator.test.property.PropertyIntegrationAxis2PropertiesTestCase.java

@Test(groups = { "wso2.esb" }, description = "Send messages using  ConcurrentConsumers "
        + "and MaxConcurrentConsumers Axis2 level properties")
public void maxConcurrentConsumersTest() throws Exception {

    String carbonHome = System.getProperty(ServerConstants.CARBON_HOME);
    String confDir = carbonHome + File.separator + "repository" + File.separator + "conf" + File.separator;

    //enabling jms transport with ActiveMQ
    File originalConfig = new File(
            TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts" + File.separator
                    + "AXIS2" + File.separator + "config" + File.separator + "property_axis2_server.xml");
    File destDir = new File(confDir + "axis2" + File.separator);
    FileUtils.copyFileToDirectory(originalConfig, destDir);

    serverManager.restartGracefully();/*  w  w w .  j  a va  2 s  .  c  o  m*/

    super.init(); // after restart the server instance initialization
    JMXServiceURL url = new JMXServiceURL(
            "service:jmx:rmi://" + context.getDefaultInstance().getHosts().get("default") + ":11311/jndi/rmi://"
                    + context.getDefaultInstance().getHosts().get("default") + ":10199/jmxrmi");

    HashMap<String, String[]> environment = new HashMap<String, String[]>();
    String[] credentials = new String[] { "admin", "admin" };
    environment.put(JMXConnector.CREDENTIALS, credentials);

    MBeanServerConnection mBeanServerConnection = JMXConnectorFactory.connect(url, environment)
            .getMBeanServerConnection();

    int beforeThreadCount = (Integer) mBeanServerConnection
            .getAttribute(new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME), "ThreadCount");

    String queueName = "SimpleStockQuoteService";

    for (int x = 0; x < 200; x++) {
        JMSQueueMessageProducer sender = new JMSQueueMessageProducer(
                JMSBrokerConfigurationProvider.getInstance().getBrokerConfiguration());

        try {
            sender.connect(queueName);
            for (int i = 0; i < 3; i++) {
                sender.pushMessage("<?xml version='1.0' encoding='UTF-8'?>"
                        + "<soapenv:Envelope xmlns:soapenv=\"http://schemas." + "xmlsoap.org/soap/envelope/\""
                        + " xmlns:ser=\"http://services.samples\" xmlns:xsd=\""
                        + "http://services.samples/xsd\">" + "   <soapenv:Header/>" + "   <soapenv:Body>"
                        + "      <ser:placeOrder>" + "         <ser:order>"
                        + "            <xsd:price>100</xsd:price>"
                        + "            <xsd:quantity>2000</xsd:quantity>"
                        + "            <xsd:symbol>JMSTransport</xsd:symbol>" + "         </ser:order>"
                        + "      </ser:placeOrder>" + "   </soapenv:Body>" + "</soapenv:Envelope>");
            }
        } finally {
            sender.disconnect();
        }
    }

    OMElement synapse = esbUtils
            .loadResource("/artifacts/ESB/mediatorconfig/property/" + "ConcurrentConsumers.xml");
    updateESBConfiguration(JMSEndpointManager.setConfigurations(synapse));

    int afterThreadCount = (Integer) mBeanServerConnection
            .getAttribute(new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME), "ThreadCount");

    assertTrue((afterThreadCount - beforeThreadCount) <= 150, "Expected thread count range" + " not met");
}