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:com.betfair.testing.utils.cougar.helpers.CougarHelpers.java

public boolean makeServerConnection(JMXConnector jmxConnector)
        throws IOException, MBeanException, AttributeNotFoundException, InstanceNotFoundException,
        ReflectionException, MalformedObjectNameException {

    MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection();
    Set<ObjectName> mbeans = mBeanServerConnection.queryNames(new ObjectName("CoUGAR:name=healthChecker,*"),
            null);/*from   w  ww . ja  va  2s  .co m*/
    if (!mbeans.isEmpty()) {
        mBeanServerConnection.getAttribute(mbeans.iterator().next(), "SystemInService");
        return true;
    }
    return false;
}

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

public Map<String, Object> getAttributesAsMap(String mbeanName, MBeanServerConnection mbsc, Set<String> keys)
        throws Exception {
    if (CollectionUtils.isBlankCollection(keys)) {
        return null;
    }/*from   w ww. j  a va2  s . c o  m*/

    ObjectName mbean = new ObjectName(mbeanName);
    MBeanInfo info = mbsc.getMBeanInfo(mbean);
    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>(keys.size());

        String name;
        for (int i = 0; i < size; i++) {
            name = attributes[i].getName();
            if (keys.contains(name)) {
                try {
                    beansMap.put(attributes[i].getName(), mbsc.getAttribute(mbean, attributes[i].getName()));
                } catch (Exception e) {
                    //ignore it
                }
            }
        }
        return beansMap;
    }
    return null;
}

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

private long getTotalGarbageCollectionTime(MBeanServerConnection connection)
        throws MetricUnreachableException, MetricNotFoundException, PluginException {

    long totalGcTimeMillis = 0;

    try {/*from w  ww  . j a  v  a  2s.  c  o m*/

        // Use of the MXBean replaced by plain old JMX query for TCS-71
        //
        // Set<ObjectName> garbageCollectors = connection.queryNames(
        // new ObjectName("java.lang:type=GarbageCollector,*"), null);
        // for (ObjectName garbageCollectorName : garbageCollectors) {
        // GarbageCollectorMXBean garbageCollector = getGarbageCollectorMXBean(
        // connection, garbageCollectorName);
        // long collectionTime = garbageCollector.getCollectionTime();

        ObjectName gcObjName = new ObjectName("java.lang:type=GarbageCollector,*");
        Set<ObjectInstance> garbageCollectors = connection.queryMBeans(gcObjName, null);

        for (ObjectInstance instance : garbageCollectors) {
            ObjectName instanceName = instance.getObjectName();
            Long l = (Long) connection.getAttribute(instance.getObjectName(), "CollectionTime");
            long collectionTime = l.longValue();
            LOGGER.debug(instanceName + "::CollectionTime=" + collectionTime);

            if (collectionTime > -1) {
                totalGcTimeMillis += collectionTime;
            }
        }
    } catch (MalformedObjectNameException e) {
        throw new MetricInvalidException("Error querying for GarbageCollector MBeans: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new MetricUnreachableException("Error querying for GarbageCollector MBeans:" + e.getMessage(), e);
    } catch (AttributeNotFoundException e) {
        throw new MetricNotFoundException("Error querying for GarbageCollector MBeans:" + e.getMessage(), e);
    } catch (InstanceNotFoundException e) {
        throw new MetricNotFoundException("Error querying for GarbageCollector MBeans:" + e.getMessage(), e);
    } catch (MBeanException e) {
        throw new PluginException("Error querying for GarbageCollector MBeans:" + e.getMessage(), e);
    } catch (ReflectionException e) {
        throw new PluginException("Error querying for GarbageCollector MBeans:" + e.getMessage(), e);
    } catch (NullPointerException e) {
        throw new PluginException("Error querying for GarbageCollector MBeans:" + e.getMessage(), e);
    }

    return totalGcTimeMillis;
}

From source file:org.helios.collector.jmx.connection.AbstractMBeanServerConnectionFactory.java

/**
 * Returns the value of an attribute//from   w w  w .j ava  2s  .co  m
 * @param objectName
 * @param attributeName
 * @return
 * @throws MBeanException
 * @throws AttributeNotFoundException
 * @throws InstanceNotFoundException
 * @throws ReflectionException
 * @throws IOException
 */
@Override
@ManagedOperation
public Object getAttribute(ObjectName objectName, String attributeName) throws MBeanException,
        AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException {
    validateConn();
    MBeanServerConnection conn = null;
    try {
        conn = getPooledConnection();
        return conn.getAttribute(objectName, attributeName);
    } catch (MBeanServerConnectionFactoryException e) {
        throw new RuntimeException("Failed to get pooled connection", e);
    } finally {
        try {
            this.returnPooledConnection(conn);
        } catch (Exception e) {
            log.debug(e.getMessage());
        }
    }
}

From source file:org.hyperic.hq.plugin.jboss.JBossUtil.java

static Object getRemoteMBeanValue(Metric metric)
        throws MetricNotFoundException, MetricInvalidException, MetricUnreachableException, PluginException {

    MBeanServerConnection mServer = null;
    boolean cached = true;
    String url = getServerURL(metric);

    synchronized (serverCache) {
        mServer = (MBeanServerConnection) serverCache.get(url);
    }//from  w w  w.  ja v a 2  s .c o m

    if (mServer == null) {
        cached = false;
        try {
            mServer = getMBeanServerConnection(metric); //jndi lookup
        } catch (NamingException e) {
            throw unreachable(metric, e);
        } catch (RemoteException e) {
            throw unreachable(metric, e);
        }

        determineJSR77Case(url, mServer);
        synchronized (serverCache) {
            serverCache.put(url, mServer);
        }
    }

    String attrName = metric.getAttributeName();
    boolean lc;

    Boolean jsr77Case;
    synchronized (lowerCaseURLMappings) {
        jsr77Case = (Boolean) lowerCaseURLMappings.get(url);
    }

    if (jsr77Case != null) {
        lc = jsr77Case.booleanValue();
    } else {
        lc = Character.isLowerCase(attrName.charAt(0));
    }

    String lcAttr;
    //another 3.2.8 hack
    if (lc && ((lcAttr = (String) jsr77LowerCase.get(attrName)) != null)) {
        attrName = lcAttr;
    }

    try {
        ObjectName objName = new ObjectName(metric.getObjectName());

        if (attrName.substring(1).startsWith(/*S*/"tatistic")) {
            return getJSR77Statistic(mServer, objName, metric, lc);
        } else if (attrName.equals("__INSTANCE__")) {
            //cheap hack for an avail metric for MBeans that dont
            //have anything better we can use, e.g. Hibernate.
            try {
                mServer.getObjectInstance(objName);
                return Boolean.TRUE;
            } catch (Exception e) {
                return Boolean.FALSE;
            }
        } else {
            return mServer.getAttribute(objName, attrName);
        }
    } catch (MalformedObjectNameException e) {
        throw invalid(metric, e);
    } catch (InstanceNotFoundException e) {
        throw notfound(metric, e);
    } catch (AttributeNotFoundException e) {
        //XXX not all MBeans have a reasonable attribute to
        //determine availability, so just assume if we get this far
        //the MBean exists and is alive.
        if (attrName.equals(Metric.ATTR_AVAIL)) {
            return new Double(Metric.AVAIL_UP);
        }
        throw notfound(metric, e);
    } catch (ReflectionException e) {
        throw error(metric, e);
    } catch (MBeanException e) {
        throw error(metric, e);
    } catch (RuntimeMBeanException e) {
        throw error(metric, e);
    } catch (Exception e) {
        //CommunicationException, NamingException, RemoteException, etc.
        if (cached) {
            //retry once, in the event the cached connection was stale
            synchronized (serverCache) {
                serverCache.remove(url);
            }
            log.debug("MBeanServerConnection cache cleared for " + url);
            return getRemoteMBeanValue(metric);
        } else {
            throw unreachable(metric, e);
        }
    }
}

From source file:org.hyperic.hq.plugin.tomcat.JBossUtil.java

static Object getRemoteMBeanValue(Metric metric)
        throws MetricNotFoundException, MetricInvalidException, MetricUnreachableException, PluginException {

    MBeanServerConnection mServer = null;
    boolean cached = true;
    String url = getServerURL(metric);

    synchronized (serverCache) {
        mServer = (MBeanServerConnection) serverCache.get(url);
    }/*from w w w  .  j  av  a 2  s.  c  o m*/

    if (mServer == null) {
        cached = false;
        try {
            mServer = getMBeanServerConnection(metric); //jndi lookup
        } catch (NamingException e) {
            throw unreachable(metric, e);
        } catch (RemoteException e) {
            throw unreachable(metric, e);
        }

        //            determineJSR77Case(url, mServer);
        synchronized (serverCache) {
            serverCache.put(url, mServer);
        }
    }

    String attrName = metric.getAttributeName();
    boolean lc;

    Boolean jsr77Case;
    synchronized (lowerCaseURLMappings) {
        jsr77Case = (Boolean) lowerCaseURLMappings.get(url);
    }

    if (jsr77Case != null) {
        lc = jsr77Case.booleanValue();
    } else {
        lc = Character.isLowerCase(attrName.charAt(0));
    }

    String lcAttr;
    //another 3.2.8 hack
    if (lc && ((lcAttr = (String) jsr77LowerCase.get(attrName)) != null)) {
        attrName = lcAttr;
    }

    try {
        ObjectName objName = new ObjectName(metric.getObjectName());

        if (attrName.substring(1).startsWith(/*S*/"tatistic")) {
            return getJSR77Statistic(mServer, objName, metric, lc);
        } else if (attrName.equals("__INSTANCE__")) {
            //cheap hack for an avail metric for MBeans that dont
            //have anything better we can use, e.g. Hibernate.
            try {
                mServer.getObjectInstance(objName);
                return Boolean.TRUE;
            } catch (Exception e) {
                return Boolean.FALSE;
            }
        } else {
            return mServer.getAttribute(objName, attrName);
        }
    } catch (MalformedObjectNameException e) {
        throw invalid(metric, e);
    } catch (InstanceNotFoundException e) {
        throw notfound(metric, e);
    } catch (AttributeNotFoundException e) {
        //XXX not all MBeans have a reasonable attribute to
        //determine availability, so just assume if we get this far
        //the MBean exists and is alive.
        if (attrName.equals(Metric.ATTR_AVAIL)) {
            return new Double(Metric.AVAIL_UP);
        }
        throw notfound(metric, e);
    } catch (ReflectionException e) {
        throw error(metric, e);
    } catch (MBeanException e) {
        throw error(metric, e);
    } catch (RuntimeMBeanException e) {
        throw error(metric, e);
    } catch (Exception e) {
        //CommunicationException, NamingException, RemoteException, etc.
        if (cached) {
            //retry once, in the event the cached connection was stale
            synchronized (serverCache) {
                serverCache.remove(url);
            }
            log.debug("MBeanServerConnection cache cleared for " + url);
            return getRemoteMBeanValue(metric);
        } else {
            throw unreachable(metric, e);
        }
    }
}

From source file:org.hyperic.hq.plugin.weblogic.WeblogicServiceControlPlugin.java

protected Object invoke(MBeanServerConnection mServer, String objectName, String method, Object[] args,
        String[] sig) throws MetricUnreachableException, MetricNotFoundException, PluginException {

    ObjectName obj;/*from   w  w w. j a v a2 s .c  o  m*/
    try {
        obj = new ObjectName(objectName);
    } catch (MalformedObjectNameException e1) {
        throw new PluginException("Unable to create an ObjectName from " + objectName);
    }

    MBeanInfo info;
    try {
        info = mServer.getMBeanInfo(obj);
    } catch (Exception e1) {
        throw new PluginException("Unable to obtain MBeanInfo from " + objectName);
    }

    if (sig.length == 0) {
        MBeanUtil.OperationParams params = MBeanUtil.getOperationParams(info, method, args);
        if (params.isAttribute) {
            if (method.startsWith("set")) {
                try {
                    mServer.setAttribute(obj, new Attribute(method.substring(3), params.arguments[0]));
                } catch (AttributeNotFoundException e) {
                    throw new MetricNotFoundException(e.getMessage(), e);
                } catch (Exception e) {
                    throw new PluginException(e);
                }
                return null;
            } else {
                try {
                    return mServer.getAttribute(obj, method.substring(3));
                } catch (AttributeNotFoundException e) {
                    throw new MetricNotFoundException(e.getMessage(), e);
                } catch (Exception e) {
                    throw new PluginException(e);
                }
            }
        }
        sig = params.signature;
        args = params.arguments;
    }

    try {
        return mServer.invoke(obj, method, args, sig);
    } catch (Exception e) {
        throw new PluginException(e);
    }
}

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

private Object queryMBeans(String pattern, Properties props) throws PluginException {

    MBeanServerConnection mServer;
    try {//w w w .  j av  a  2s .c  om
        mServer = MxUtil.getMBeanServer(props);
    } catch (Exception e) {
        throw new PluginException("getMBeanServer(" + props.getProperty(MxUtil.PROP_JMX_URL) + "): " + e, e);
    }
    ObjectName query;
    try {
        query = new ObjectName(pattern);
    } catch (Exception e) {
        throw new PluginException("Invalid query '" + pattern + "': " + e);
    }
    Map res = new HashMap();
    try {
        Iterator beans = mServer.queryNames(query, null).iterator();
        while (beans.hasNext()) {
            ObjectName obj = (ObjectName) beans.next();
            Map bean = new HashMap();
            Map attrs = new LinkedHashMap();
            bean.put(PROP_ATTRIBUTE + "s", attrs);
            res.put(obj.toString(), bean);

            MBeanInfo info = mServer.getMBeanInfo(obj);
            MBeanAttributeInfo[] attrInfo = info.getAttributes();
            for (int i = 0; i < attrInfo.length; i++) {
                MBeanAttributeInfo mia = attrInfo[i];
                String name = mia.getName();
                Map attr = new HashMap();
                Object val;
                try {
                    val = mServer.getAttribute(obj, name);
                } catch (Exception e) {
                    continue; //XXX
                }

                if (val == null) {
                    val = "-";
                }
                attr.put("Value", val);
                attr.put("Description", mia.getDescription());
                attr.put("isWritable", new Boolean(mia.isWritable()));
                attrs.put(name, attr);
            }

            bean.put(PROP_METHOD + "s", info.getOperations());
        }
    } catch (Exception e) {
        throw new PluginException("Error in query '" + pattern + "': " + e, e);
    }

    return res;
}

From source file:org.rhq.storage.installer.StorageInstaller.java

boolean verifyNodeIsUp(String address, int jmxPort, int retries, long timeout) throws Exception {
    String url = "service:jmx:rmi:///jndi/rmi://" + address + ":" + jmxPort + "/jmxrmi";
    JMXServiceURL serviceURL = new JMXServiceURL(url);
    JMXConnector connector = null;
    MBeanServerConnection serverConnection = null;

    // Sleep a few seconds to work around https://issues.apache.org/jira/browse/CASSANDRA-5467
    try {/*ww w.  ja  v  a 2  s  . c om*/
        Thread.sleep(3000);
    } catch (InterruptedException e) {
    }

    Map<String, String> env = new HashMap<String, String>();
    for (int i = 0; i < retries; ++i) {
        try {
            connector = JMXConnectorFactory.connect(serviceURL, env);
            serverConnection = connector.getMBeanServerConnection();
            ObjectName storageService = new ObjectName("org.apache.cassandra.db:type=StorageService");
            Boolean nativeTransportRunning = (Boolean) serverConnection.getAttribute(storageService,
                    "NativeTransportRunning");

            return nativeTransportRunning;
        } catch (Exception e) {
            if (i < retries) {
                if (log.isDebugEnabled()) {
                    log.debug("The storage node is not up.", e);
                } else {
                    Throwable rootCause = ThrowableUtil.getRootCause(e);
                    log.info("The storage node is not up: " + rootCause.getClass().getName() + ": "
                            + rootCause.getMessage());
                }
                log.info("Checking storage node status again in " + (timeout * (i + 1)) + " ms...");
            }
            Thread.sleep(timeout * (i + 1));
        }
    }
    return false;
}

From source file:edu.nwpu.gemfire.monitor.data.JMXDataUpdater.java

private void registerPulseUrlToManager(JMXConnector connection)
        throws IOException, AttributeNotFoundException, InstanceNotFoundException, MBeanException,
        ReflectionException, MalformedObjectNameException, InvalidAttributeValueException {
    if (LOGGER.infoEnabled()) {
        LOGGER.info(resourceBundle.getString("LOG_MSG_REGISTERING_APP_URL_TO_MANAGER"));
    }//from   w w  w .ja  va 2 s.c  o m

    // Reference to repository
    Repository repository = Repository.get();

    // Register Pulse URL if not already present in the JMX Manager
    if (connection != null) {
        MBeanServerConnection mbsc = connection.getMBeanServerConnection();

        Set<ObjectName> mbeans = mbsc.queryNames(this.MBEAN_OBJECT_NAME_MEMBER_MANAGER, null);

        for (ObjectName mbeanName : mbeans) {
            String presentUrl = (String) mbsc.getAttribute(mbeanName,
                    PulseConstants.MBEAN_MANAGER_ATTRIBUTE_PULSEURL);
            String pulseWebAppUrl = repository.getPulseWebAppUrl();
            if (pulseWebAppUrl != null && (presentUrl == null || !pulseWebAppUrl.equals(presentUrl))) {
                if (LOGGER.fineEnabled()) {
                    LOGGER.fine(resourceBundle.getString("LOG_MSG_SETTING_APP_URL_TO_MANAGER"));
                }
                Attribute pulseUrlAttr = new Attribute(PulseConstants.MBEAN_MANAGER_ATTRIBUTE_PULSEURL,
                        pulseWebAppUrl);
                mbsc.setAttribute(mbeanName, pulseUrlAttr);
            } else {
                if (LOGGER.fineEnabled()) {
                    LOGGER.fine(resourceBundle.getString("LOG_MSG_APP_URL_ALREADY_PRESENT_IN_MANAGER"));
                }
            }
        }
    }
}