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.rhq.cassandra.ClusterInitService.java

public boolean isNativeTransportRunning(String storageNode, int jmxPort) throws Exception {
    Boolean nativeTransportRunning = false;
    String url = getJMXConnectionURL(storageNode, jmxPort);
    JMXServiceURL serviceURL = new JMXServiceURL(url);
    Map<String, String> env = new HashMap<String, String>();
    JMXConnector connector = null;

    try {/*from  w ww . j a v  a 2s.com*/
        connector = JMXConnectorFactory.connect(serviceURL, env);
        MBeanServerConnection serverConnection = connector.getMBeanServerConnection();
        ObjectName storageService = new ObjectName("org.apache.cassandra.db:type=StorageService");
        String attribute = "NativeTransportRunning";
        try {
            nativeTransportRunning = (Boolean) serverConnection.getAttribute(storageService, attribute);
        } catch (Exception e) {
            // It is ok to just catch and log exceptions here particularly in an integration
            // test environment where we could potentially try to do the JMX query before
            // Cassandra is fully initialized. We can query StorageService before the native
            // transport server is initialized which will result in Cassandra throwing a NPE.
            // We do not want propagate that exception because it is just a matter of waiting
            // for Cassandra to finish initializing.
            if (log.isDebugEnabled()) {
                log.debug("Failed to read attribute [" + attribute + "] from " + storageService, e);
            } else {
                log.info("Faied to read attribute [" + attribute + "] from " + storageService + ": "
                        + e.getMessage());
            }
        }
    } finally {
        if (connector != null) {
            connector.close();
        }
    }
    return nativeTransportRunning;
}

From source file:com.springsource.hq.plugin.tcserver.plugin.TomcatMeasurementPlugin.java

private MetricValue getPercentAllocatedThreads(MBeanServerConnection connection, Metric metric)
        throws MetricUnreachableException, MetricNotFoundException, PluginException {
    int currentThreadCount = 0;
    int maxThreads = 0;

    try {//from  ww  w  .j  ava2  s  .c  o  m
        ObjectName threadPoolObjectName = new ObjectName(metric.getObjectName());
        currentThreadCount = ((Integer) connection.getAttribute(threadPoolObjectName, "currentThreadCount"))
                .intValue();
        maxThreads = ((Integer) connection.getAttribute(threadPoolObjectName, "maxThreads")).intValue();
    } catch (MalformedObjectNameException e) {
        throw new MetricInvalidException("Error querying for Thread Pool MBeans: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new MetricUnreachableException("Error querying for Thread Pool MBeans:" + e.getMessage(), e);
    } catch (AttributeNotFoundException e) {
        throw new MetricNotFoundException("Error querying for Thread Pool MBeans:" + e.getMessage(), e);
    } catch (InstanceNotFoundException e) {
        throw new MetricNotFoundException("Error querying for Thread Pool MBeans:" + e.getMessage(), e);
    } catch (MBeanException e) {
        throw new PluginException("Error querying for Thread Pool MBeans:" + e.getMessage(), e);
    } catch (ReflectionException e) {
        throw new PluginException("Error querying for Thread Pool MBeans:" + e.getMessage(), e);
    } catch (NullPointerException e) {
        throw new PluginException("Error querying for Thread Pool MBeans:" + e.getMessage(), e);
    }

    return new MetricValue(100d * (double) currentThreadCount / (double) maxThreads);
}

From source file:com.springsource.hq.plugin.tcserver.plugin.TomcatMeasurementPlugin.java

private MetricValue getPercentActiveThreads(MBeanServerConnection connection, Metric metric)
        throws MetricUnreachableException, MetricNotFoundException, PluginException {
    int currentThreadsBusy = 0;
    int maxThreads = 0;

    try {/*from  w  w  w .  ja va2s. c o m*/
        ObjectName threadPoolObjectName = new ObjectName(metric.getObjectName());
        currentThreadsBusy = ((Integer) connection.getAttribute(threadPoolObjectName, "currentThreadsBusy"))
                .intValue();
        maxThreads = ((Integer) connection.getAttribute(threadPoolObjectName, "maxThreads")).intValue();
    } catch (MalformedObjectNameException e) {
        throw new MetricInvalidException("Error querying for Thread Pool MBeans: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new MetricUnreachableException("Error querying for Thread Pool MBeans:" + e.getMessage(), e);
    } catch (AttributeNotFoundException e) {
        throw new MetricNotFoundException("Error querying for Thread Pool MBeans:" + e.getMessage(), e);
    } catch (InstanceNotFoundException e) {
        throw new MetricNotFoundException("Error querying for Thread Pool MBeans:" + e.getMessage(), e);
    } catch (MBeanException e) {
        throw new PluginException("Error querying for Thread Pool MBeans:" + e.getMessage(), e);
    } catch (ReflectionException e) {
        throw new PluginException("Error querying for Thread Pool MBeans:" + e.getMessage(), e);
    } catch (NullPointerException e) {
        throw new PluginException("Error querying for Thread Pool MBeans:" + e.getMessage(), e);
    }

    return new MetricValue(100d * (double) currentThreadsBusy / (double) maxThreads);
}

From source file:com.ngdata.sep.tools.monitoring.ReplicationStatusRetriever.java

public void addStatusFromJmx(ReplicationStatus replicationStatus) throws Exception {
    JmxConnections jmxConnections = new JmxConnections();

    for (String peerId : replicationStatus.getPeersAndRecoveredQueues()) {
        for (String server : replicationStatus.getServers(peerId)) {
            Status status = replicationStatus.getStatus(peerId, server);
            String hostName = ServerName.parseHostname(server);

            MBeanServerConnection connection = jmxConnections.getConnector(hostName, HBASE_JMX_PORT)
                    .getMBeanServerConnection();

            ObjectName replSourceBean = new ObjectName("hadoop:service=Replication,name=ReplicationSource for "
                    + URLEncoder.encode(peerId, "UTF8"));
            try {
                status.ageOfLastShippedOp = (Long) connection.getAttribute(replSourceBean,
                        "ageOfLastShippedOp");
            } catch (AttributeNotFoundException e) {
                // could be the case if the queue disappeared since we read info from ZK
            } catch (InstanceNotFoundException e) {
                // could be the case if the queue disappeared since we read info from ZK
            }/*w  w w  .j a  va  2  s  . co  m*/

            // The following mbean is only available when using NGDATA's ForkedReplicationSource
            ObjectName replSourceInfoBean = new ObjectName(
                    "hadoop:service=Replication,name=ReplicationSourceInfo for "
                            + URLEncoder.encode(peerId, "UTF8"));
            try {
                status.selectedPeerCount = (Integer) connection.getAttribute(replSourceInfoBean,
                        "SelectedPeerCount");
                status.timestampOfLastShippedOp = (Long) connection.getAttribute(replSourceInfoBean,
                        "TimestampLastShippedOp");
                status.sleepReason = (String) connection.getAttribute(replSourceInfoBean, "SleepReason");
                status.sleepMultiplier = (Integer) connection.getAttribute(replSourceInfoBean,
                        "SleepMultiplier");
                status.timestampLastSleep = (Long) connection.getAttribute(replSourceInfoBean,
                        "TimestampLastSleep");
            } catch (AttributeNotFoundException e) {
                // could be the case if the queue disappeared since we read info from ZK
            } catch (InstanceNotFoundException e) {
                // could be the case if the queue disappeared since we read info from ZK
                // or the ForkedReplicationSource isn't used
            }
        }
    }

    jmxConnections.close();
}

From source file:com.clustercontrol.jmx.factory.RunMonitorJmx.java

/**
 * JMX ??// w w w  .  jav  a2s  . c o m
 * 
 * @param facilityId ID
 * @return ???????true
 */
@Override
public boolean collect(String facilityId) {
    boolean result = false;

    if (m_now != null) {
        m_nodeDate = m_now.getTime();
    }
    m_value = 0;
    exception = null;

    NodeInfo node = null;
    if (!m_isMonitorJob) {
        node = nodeInfo.get(facilityId);
    } else {
        try {
            // ??
            node = new RepositoryControllerBean().getNode(facilityId);
        } catch (Exception e) {
            m_message = MessageConstant.MESSAGE_COULD_NOT_GET_NODE_ATTRIBUTES.getMessage();
            return false;
        }
    }

    JMXServiceURL url = null;
    try {
        String rmiFormat = HinemosPropertyUtil.getHinemosPropertyStr("monitor.jmx.rmi.format",
                "service:jmx:rmi:///jndi/rmi://%s:%d/jmxrmi");
        String urlStr = String.format(rmiFormat, node.getAvailableIpAddress(), jmx.getPort());
        m_log.debug("facilityId=" + facilityId + ", url=" + urlStr);
        url = new JMXServiceURL(urlStr);
    } catch (Exception e) {
        m_log.warn("fail to initialize JMXServiceURL : " + e.getMessage() + " (" + e.getClass().getName() + ")",
                e);
        exception = e;
        return result;
    }

    JMXConnector jmxc = null;
    try {
        Map<String, Object> env = new HashMap<>();

        if (jmx.getAuthUser() != null)
            env.put(JMXConnector.CREDENTIALS, new String[] { jmx.getAuthUser(), jmx.getAuthPassword() });

        System.setProperty("sun.rmi.transport.tcp.responseTimeout", Integer.toString(HinemosPropertyUtil
                .getHinemosPropertyNum("system.sun.rmi.transport.tcp.responseTimeout", Long.valueOf(10 * 1000))
                .intValue()));
        jmxc = JMXConnectorFactory.connect(url, env);
        MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

        JmxMasterInfo jmxMasterInfo = QueryUtil.getJmxMasterInfoPK(jmx.getMasterId());
        Object value = mbsc.getAttribute(new ObjectName(jmxMasterInfo.getObjectName()),
                jmxMasterInfo.getAttributeName());
        m_value = Double.parseDouble(
                searchTargetValue(value, Arrays.asList(KeyParser.parseKeys(jmxMasterInfo.getKeys())))
                        .toString());

        // ??
        if (m_convertFlg == ConvertValueConstant.TYPE_DELTA) {

            // ??
            MonitorJmxValue valueEntity = null;
            Double prevValue = 0d;
            Long prevDate = 0l;

            if (!m_isMonitorJob) {
                // ??
                // cache??
                valueEntity = MonitorJmxCache.getMonitorJmxValue(m_monitorId, facilityId);

                // ???
                prevValue = valueEntity.getValue();
                if (valueEntity.getGetDate() != null) {
                    prevDate = valueEntity.getGetDate();
                }
            } else {
                // ??
                valueEntity = new MonitorJmxValue(new MonitorJmxValuePK(m_monitorId, facilityId));
                if (m_prvData instanceof MonitorJmxValue) {
                    // ????
                    prevValue = ((MonitorJmxValue) m_prvData).getValue();
                    prevDate = ((MonitorJmxValue) m_prvData).getGetDate();
                }
            }

            // JMX????
            valueEntity.setValue(Double.valueOf(m_value));
            valueEntity.setGetDate(m_nodeDate);

            if (!m_isMonitorJob) {
                // ???ID?????
                if (m_monitor.getMonitorFlg())
                    MonitorJmxCache.update(m_monitorId, facilityId, valueEntity);

                int m_validSecond = HinemosPropertyUtil
                        .getHinemosPropertyNum("monitor.jmx.valid.second", Long.valueOf(15)).intValue();
                // ???????????
                int tolerance = (m_runInterval + m_validSecond) * 1000;

                if (prevDate > m_nodeDate - tolerance) {

                    // ??null???
                    if (prevValue == null) {
                        m_log.debug("collect() : prevValue is null");
                        m_prevNullchk = true;
                        return false;
                    }

                    m_value = m_value - prevValue;
                } else {
                    if (prevDate != 0l) {
                        DateFormat df = DateFormat.getDateTimeInstance();
                        df.setTimeZone(HinemosTime.getTimeZone());
                        String[] args = { df.format(new Date(prevDate)) };
                        m_message = MessageConstant.MESSAGE_TOO_OLD_TO_CALCULATE.getMessage(args);
                        return false;
                    } else {
                        // ???0??
                        m_nodeDate = 0l;
                    }
                }
            } else {
                m_value = m_value - prevValue;
                m_curData = valueEntity;
            }
        }

        m_log.debug(jmxMasterInfo.getName() + " : " + m_value + " " + jmxMasterInfo.getMeasure());

        result = true;
    } catch (NumberFormatException e) {
        m_log.info("collect() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
        String[] args = { Double.toString(m_value) };
        m_message = MessageConstant.MESSAGE_COULD_NOT_GET_NUMERIC_VALUE.getMessage(args);
        return false;
    } catch (Exception e) {
        String message = e.getMessage();
        if (message != null) {
            message = message.replaceAll("\n", "");
        }
        m_log.warn("fail to access JMXService : " + message + " (" + e.getClass().getName() + ")");
        exception = e;
    } finally {
        try {
            if (jmxc != null) {
                jmxc.close();
            }
        } catch (IOException e) {
            m_log.info("fail to close JMXService : " + e.getMessage() + " (" + e.getClass().getName() + ")");
            exception = e;
        }
    }

    return result;
}

From source file:com.springsource.hq.plugin.tcserver.plugin.TomcatMeasurementPlugin.java

private MetricValue getPercentActiveConnections(MBeanServerConnection connection, Metric metric)
        throws MetricUnreachableException, MetricNotFoundException, PluginException {
    int numActiveConnections = 0;
    int maxActiveConnections = 0;

    try {//from www  . ja va 2  s  .  c  o m
        ObjectName dataSourceObjectName = new ObjectName(metric.getObjectName());
        numActiveConnections = ((Integer) connection.getAttribute(dataSourceObjectName, "numActive"))
                .intValue();
        maxActiveConnections = ((Integer) connection.getAttribute(dataSourceObjectName, "maxActive"))
                .intValue();
    } catch (MalformedObjectNameException e) {
        throw new MetricInvalidException("Error querying for DataSource MBeans: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new MetricUnreachableException("Error querying for DataSource MBeans:" + e.getMessage(), e);
    } catch (AttributeNotFoundException e) {
        throw new MetricNotFoundException("Error querying for DataSource MBeans:" + e.getMessage(), e);
    } catch (InstanceNotFoundException e) {
        throw new MetricNotFoundException("Error querying for DataSource MBeans:" + e.getMessage(), e);
    } catch (MBeanException e) {
        throw new PluginException("Error querying for DataSource MBeans:" + e.getMessage(), e);
    } catch (ReflectionException e) {
        throw new PluginException("Error querying for DataSource MBeans:" + e.getMessage(), e);
    } catch (NullPointerException e) {
        throw new PluginException("Error querying for DataSource MBeans:" + e.getMessage(), e);
    }

    return new MetricValue(100d * (double) numActiveConnections / (double) maxActiveConnections);
}

From source file:org.rhq.plugins.cassandra.CassandraNodeComponent.java

private boolean isStorageServiceReachable() {
    JMXConnector connector = null;
    try {/*ww w  .j  a v  a  2s.com*/
        Configuration pluginConfig = getResourceContext().getPluginConfiguration();
        String url = pluginConfig.getSimpleValue("connectorAddress");
        JMXServiceURL serviceURL = new JMXServiceURL(url);
        connector = JMXConnectorFactory.connect(serviceURL, null);

        MBeanServerConnection serverConnection = connector.getMBeanServerConnection();
        ObjectName storageService = new ObjectName("org.apache.cassandra.db:type=StorageService");

        // query an attribute to make sure it is in fact available
        serverConnection.getAttribute(storageService, "NativeTransportRunning");

        return true;
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Failed to make JMX connection to StorageService", e);
        }
        return false;
    } finally {
        if (connector != null) {
            try {
                connector.close();
            } catch (IOException e) {
                if (log.isDebugEnabled()) {
                    log.debug("An error occurred closing the JMX connector", e);
                }
            }
        }
    }
}

From source file:org.wso2.carbon.analytics.common.jmx.agent.JmxAgentWebInterface.java

/**
 * @param mBean    : The name of the MBean
 * @param url      : The URL for the JMX server
 * @param userName : The User name for the JMX server
 * @param password : The password for the JMX server
 * @return : The set of attributes in a MBean
 * @throws MalformedObjectNameException//from   w  ww  . j  a  va  2 s  .  co  m
 * @throws IntrospectionException
 * @throws InstanceNotFoundException
 * @throws IOException
 * @throws ReflectionException
 */
public String[][] getMBeanAttributeInfo(String mBean, String url, String userName, String password)
        throws MalformedObjectNameException, IntrospectionException, InstanceNotFoundException, IOException,
        ReflectionException {

    JMXConnector jmxc = getJmxConnector(url, userName, password);

    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
    ObjectName mBeanName = new ObjectName(mBean);

    MBeanAttributeInfo[] attrs = mbsc.getMBeanInfo(mBeanName).getAttributes();

    ArrayList<String[]> strAttrs = new ArrayList<String[]>();

    for (MBeanAttributeInfo info : attrs) {

        //check the suitability of the attribute
        try {
            Object result = mbsc.getAttribute(mBeanName, info.getName());

            //if this is an instance of a primary data type supported by cassandra
            if (result instanceof String || result instanceof Integer || result instanceof Double
                    || result instanceof Long || result instanceof Boolean || result instanceof Float) {
                strAttrs.add(new String[] { info.getName() });
            }

            //if this is a composite data type
            if (result instanceof CompositeData) {
                CompositeData cd = (CompositeData) result;
                ArrayList<String> keys = new ArrayList<String>();
                //add the attribute name
                keys.add(info.getName());
                for (String key : cd.getCompositeType().keySet()) {
                    //check whether the key returns a primary data type
                    Object attrValue = cd.get(key);
                    if (attrValue instanceof String || attrValue instanceof Integer
                            || attrValue instanceof Double || attrValue instanceof Long
                            || attrValue instanceof Boolean || attrValue instanceof Float) {
                        keys.add(key);
                    }
                }
                //if this composite data object has keys which returns attributes with
                // primary data types
                if (keys.size() > 1) {
                    strAttrs.add(keys.toArray(new String[keys.size()]));
                }
            }
        } catch (MBeanException e) {
            log.error("Removed the attribute " + info.getName() + " of " + mBean + " from the UI list due to: "
                    + e.getMessage());
        } catch (AttributeNotFoundException e) {
            log.error("Removed the attribute " + info.getName() + " of " + mBean + " from the UI list due to: "
                    + e.getMessage());
        } catch (UnmarshalException e) {
            log.error("Removed the attribute " + info.getName() + " of " + mBean + " from the UI list due to: "
                    + e.getMessage());
        } catch (RuntimeOperationsException e) {
            log.error("Removed the attribute " + info.getName() + " of " + mBean + " from the UI list due to: "
                    + e.getMessage());

        } catch (RuntimeMBeanException e) {
            log.error("Removed the attribute " + info.getName() + " of " + mBean + " from the UI list due to: "
                    + e.getMessage());
        } catch (ReflectionException e) {
            log.error("Removed the attribute " + info.getName() + " of " + mBean + " from the UI list due to: "
                    + e.getMessage());
        } catch (Exception e) {
            log.error("Removed the attribute " + info.getName() + " of " + mBean + " from the UI list due to: "
                    + e.getMessage());
        }
    }

    //close the connection
    jmxc.close();

    return strAttrs.toArray(new String[strAttrs.size()][]);
}

From source file:org.opennms.tools.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 ww w  .  jav a2s  .c  om*/
    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 = NameTools
                            .trimByDictionary(jmxMBeanAttributeInfo.getName() + StringUtils.capitalize(key));
                    alias = createAndRegisterUniceAlias(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:org.apache.hadoop.test.system.AbstractDaemonClient.java

/**
 * Method implements all logic for receiving a bean's attribute.
 * If any initializations such as establishing bean server connections, etc.
 * are need it will do it.//from w ww. j ava 2s . c  om
 * @param serviceName name of the service where MBean is registered (NameNode)
 * @param type name of the MXBean class
 * @param attributeName name of the attribute to be retrieved
 * @return Object value of the attribute or <code>null</code> if not found
 * @throws IOException is thrown in case of any errors
 */
protected Object getJmxAttribute(String serviceName, String type, String attributeName) throws IOException {
    Object retAttribute = null;
    String domain = null;
    if (isJmxEnabled()) {
        try {
            MBeanServerConnection conn = establishJmxConnection(getHostName(), getJmxPortNumber());
            for (String d : conn.getDomains()) {
                if (d != null && d.startsWith(HADOOP_JMX_DOMAIN))
                    domain = d;
            }
            if (!jmxObjectNames.containsKey(type))
                jmxObjectNames.put(type, getJmxBeanName(domain, serviceName, type));
            retAttribute = conn.getAttribute(jmxObjectNames.get(type), attributeName);
        } catch (MBeanException e) {
            LOG.debug(e.getStackTrace());
            throw new IOException(e);
        } catch (AttributeNotFoundException e) {
            LOG.warn(e.getStackTrace());
            throw new IOException(e);
        } catch (InstanceNotFoundException e) {
            LOG.warn(e.getStackTrace());
            throw new IOException(e);
        } catch (ReflectionException e) {
            LOG.debug(e.getStackTrace());
            throw new IOException(e);
        }
    }
    return retAttribute;
}