Example usage for javax.management ObjectName getCanonicalName

List of usage examples for javax.management ObjectName getCanonicalName

Introduction

In this page you can find the example usage for javax.management ObjectName getCanonicalName.

Prototype

public String getCanonicalName() 

Source Link

Document

Returns the canonical form of the name; that is, a string representation where the properties are sorted in lexical order.

More precisely, the canonical form of the name is a String consisting of the domain part, a colon (:), the canonical key property list, and a pattern indication.

The canonical key property list is the same string as described for #getCanonicalKeyPropertyListString() .

The pattern indication is:

  • empty for an ObjectName that is not a property list pattern;
  • an asterisk for an ObjectName that is a property list pattern with no keys; or
  • a comma and an asterisk (,*) for an ObjectName that is a property list pattern with at least one key.

    Usage

    From source file:flens.query.JMXQuery.java

    @SuppressWarnings("unchecked")
    private void call(Query q, String[] rest) throws MalformedObjectNameException, NullPointerException,
            IOException, InstanceNotFoundException, MBeanException, ReflectionException {
        String name = rest[0];// ww w. ja  v a  2s.co m
        String oppname = rest[1];
    
        Set<ObjectName> names = new TreeSet<ObjectName>(connection.queryNames(ObjectName.getInstance(name), null));
    
        Map<String, Object> out = new HashMap<>();
    
        for (ObjectName objectName : names) {
            List<Object> o = (List<Object>) q.getPayload().get("params");
            List<String> sig = (List<String>) q.getPayload().get("sig");
            out.put(objectName.getCanonicalName(),
                    connection.invoke(objectName, oppname, o.toArray(), sig.toArray(new String[sig.size()])));
        }
    
        q.respond(out);
    
    }
    

    From source file:org.opennms.systemreport.AbstractSystemReportPlugin.java

    protected <T> List<T> getBeans(final String mxBeanName, final Class<T> clazz) {
        initializeConnection();//from w ww.  j av a 2  s . c  om
        List<T> beans = new ArrayList<T>();
        if (m_connection == null)
            return beans;
        try {
            ObjectName o = new ObjectName(mxBeanName + ",*");
            for (final ObjectName name : (Set<ObjectName>) m_connection.queryNames(o, null)) {
                beans.add(getBean(name.getCanonicalName(), clazz));
            }
        } catch (final Exception e) {
            LOG.warn("Unable to get beans of type '{}'", mxBeanName, e);
        }
        return beans;
    }
    

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

    /**
     * @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 name array of the MBeans which the JMX server. The format of the array is
     *         [Domain name][MBean Canonical name]
     * @throws IOException//  w ww  . j  a v  a 2 s  .  c  o  m
     */
    public String[][] getMBeans(String url, String userName, String password) throws IOException {
    
        JMXConnector jmxc = null;
    
        try {
            jmxc = getJmxConnector(url, userName, password);
    
            MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
    
            int count = 0;
            Set<ObjectName> names = new TreeSet<ObjectName>(mbsc.queryNames(null, null));
            String[][] nameArr = new String[names.size()][2];
    
            for (ObjectName name : names) {
                nameArr[count][0] = name.getDomain();
                nameArr[count][1] = name.getCanonicalName();
                count++;
            }
    
            return nameArr;
    
        } catch (MalformedURLException e) {
            log.error(e);
            throw e;
        } catch (IOException e) {
            log.error(e);
            throw e;
        } finally {
            if (jmxc != null) {
                jmxc.close();
            }
        }
    }
    

    From source file:com.stumbleupon.hbaseadmin.JMXQuery.java

    public String execute(String hostport) throws Exception {
        Iterator i;/*from w w  w  .  ja  va  2  s  .  co m*/
        String result = "";
        final JMXServiceURL rmiurl = new JMXServiceURL(
                "service:jmx:rmi://" + hostport + "/jndi/rmi://" + hostport + "/jmxrmi");
        final JMXConnector jmxc = JMXConnectorFactory.connect(rmiurl, getCredentials(password_file));
        try {
            final MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
    
            final ObjectName objName = new ObjectName(beanName);
            final Set beans = mbsc.queryMBeans(objName, null);
    
            if (beans.size() == 0) {
                logger.warn(objName.getCanonicalName() + " is not a registered bean");
            } else if (beans.size() == 1) {
                final ObjectInstance instance = (ObjectInstance) beans.iterator().next();
                result = doBean(mbsc, instance, command);
            } else {
    
                for (i = beans.iterator(); i.hasNext();) {
                    final Object obj = i.next();
    
                    if (obj instanceof ObjectName)
                        System.out.println(((ObjectName) obj).getCanonicalName());
                    else if (obj instanceof ObjectInstance) {
                        System.out.println(((ObjectInstance) obj).getObjectName().getCanonicalName());
                    } else
                        logger.error("Unexpected object type: " + obj);
                }
            }
        } finally {
            jmxc.close();
        }
        return result;
    }
    

    From source file:azkaban.execapp.AzkabanExecutorServer.java

    public void close() {
        try {/*from www . ja  v  a  2s. co  m*/
            for (ObjectName name : registeredMBeans) {
                mbeanServer.unregisterMBean(name);
                logger.info("Jmx MBean " + name.getCanonicalName() + " unregistered.");
            }
        } catch (Exception e) {
            logger.error("Failed to cleanup MBeanServer", e);
        }
    }
    

    From source file:fr.openfarm.jmx.service.JMXQuery.java

    @Override
    public GetWildCardMultiDataResponse getWildCardJmxData(String name, String attributeName, String key)
            throws MalformedObjectNameException, NullPointerException, AttributeNotFoundException,
            InstanceNotFoundException, MBeanException, ReflectionException, IOException {
        ObjectName objectName = new ObjectName(name);
        Set<ObjectName> objectNameList = connection.queryNames(objectName, null);
        GetWildCardMultiDataResponse response = new GetWildCardMultiDataResponse();
        List<ObjectNameAndKey> objectAndkeyList = new ArrayList<ObjectNameAndKey>();
        for (ObjectName iterName : objectNameList) {
            objectName = iterName;// w  ww .  j a  v  a 2s .  c  o m
            ObjectNameAndKey objectAndKey = new ObjectNameAndKey();
            objectAndKey.setObjectName(objectName.getCanonicalName());
            Object attr = connection.getAttribute(objectName, attributeName);
            if (attr instanceof CompositeDataSupport) {
                CompositeDataSupport cds = (CompositeDataSupport) attr;
                if (key == null) {
                    ErrorJmx error = new ErrorJmx();
                    error.setMessage("Key is null for composed data " + name);
                    response.setError(error);
                    return response;
                }
                KeyResponse keyResponse = new KeyResponse();
                keyResponse.setKey(cds.get(key).toString());
                objectAndKey.setKeyResponse(keyResponse);
    
            } else {
                KeyResponse keyResponse = new KeyResponse();
                keyResponse.setKey(attr.toString());
                objectAndKey.setKeyResponse(keyResponse);
            }
            objectAndkeyList.add(objectAndKey);
        }
        response.setResponse(objectAndkeyList);
        return response;
    }
    

    From source file:com.spotify.reaper.cassandra.JmxProxy.java

    /**
     * New way of determining if a repair is running after C* 2.2
     * /*www .jav  a2 s  .c o  m*/
     * @return true if any repairs are running on the node.
     */
    public boolean isRepairRunningPost22() {
        try {
            // list all mbeans in search of one with the name Repair#?? 
            // This is the replacement for AntiEntropySessions since Cassandra 2.2
            Set beanSet = mbeanServer.queryNames(new ObjectName("org.apache.cassandra.internal:*"), null);
            for (Object bean : beanSet) {
                ObjectName objName = (ObjectName) bean;
                if (objName.getCanonicalName().contains("Repair#")) {
                    return true;
                }
            }
            return false;
        } catch (IOException ignored) {
            LOG.warn(FAILED_TO_CONNECT_TO_USING_JMX, host, ignored);
        } catch (MalformedObjectNameException ignored) {
            LOG.error("Internal error, malformed name", ignored);
        } catch (Exception e) {
            LOG.error(ERROR_GETTING_ATTR_JMX, e);
        }
        // If uncertain, assume it's running
        return true;
    }
    

    From source file:com.riotgames.mondev.JMXDiscovery.java

    protected String discoverMBeans(String key) throws Exception {
        try {//from www  .  j a  v  a  2 s.  co  m
            HashMap<String, String[]> env = null;
            if (null != username && null != password) {
                env = new HashMap<String, String[]>();
                env.put(JMXConnector.CREDENTIALS, new String[] { username, password });
            }
    
            jmxc = JMXConnectorFactory.connect(jmxServerUrl, env);
            mbsc = jmxc.getMBeanServerConnection();
    
            ObjectName filter = new ObjectName(key);
            JSONArray beanList = new JSONArray();
            JSONObject mapping = new JSONObject();
    
            Set beans = mbsc.queryMBeans(filter, null);
            for (Object obj : beans) {
                JSONObject bean = new JSONObject();
                ObjectName beanName;
    
                // Return the ObjectName instance correctly for both Objects and Instances
                if (obj instanceof ObjectName)
                    beanName = (ObjectName) obj;
                else if (obj instanceof ObjectInstance)
                    beanName = ((ObjectInstance) obj).getObjectName();
                else
                    throw new RuntimeException("Unexpected object type: " + obj);
    
                // Build the standing info, description and object path
                MBeanInfo mbi = mbsc.getMBeanInfo(beanName);
                bean.put("{#JMXDESC}", mbi.getDescription());
                bean.put("{#JMXOBJ}", beanName.getCanonicalName());
    
                // Build a list of all the MBean properties as {#PROP<NAME>}
                Hashtable<String, String> pt = beanName.getKeyPropertyList();
                for (Map.Entry<String, String> prop : pt.entrySet())
                    bean.put(String.format("{#PROP%s}", prop.getKey().toUpperCase()), prop.getValue());
    
                beanList.put(bean);
            }
    
            mapping.put("data", beanList);
            return mapping.toString();
        } catch (Exception e) {
            JSONArray data = new JSONArray();
            JSONObject out = new JSONObject();
            out.put("data", data);
    
            return out.toString();
        } finally {
            try {
                if (null != jmxc)
                    jmxc.close();
            } catch (java.io.IOException exception) {
            }
    
            jmxc = null;
            mbsc = null;
        }
    }
    

    From source file:com.jkoolcloud.tnt4j.streams.custom.kafka.interceptors.reporters.metrics.MetricsReporter.java

    /**
     * Collects JMX attributes of MBeans defined by <tt>objNameStr</tt>.
     *
     * @param objNameStr/*from www  .j a  va  2 s  . co m*/
     *            MBeans object name pattern to query
     * @param mBeanServer
     *            MBean server instance to use
     * @param activity
     *            activity instance to put JMX metrics snapshots
     * @throws Exception
     *             if JMX attributes collecting fails
     */
    public void collectMetricsJMX(String objNameStr, MBeanServer mBeanServer, Activity activity) throws Exception {
        ObjectName oName = new ObjectName(objNameStr);
        Set<ObjectName> metricsBeans = mBeanServer.queryNames(oName, null);
    
        for (ObjectName mBeanName : metricsBeans) {
            try {
                PropertySnapshot snapshot = new PropertySnapshot(mBeanName.getCanonicalName());
                MBeanInfo metricsBean = mBeanServer.getMBeanInfo(mBeanName);
                MBeanAttributeInfo[] pMetricsAttrs = metricsBean.getAttributes();
                for (MBeanAttributeInfo pMetricsAttr : pMetricsAttrs) {
                    try {
                        String attrName = pMetricsAttr.getName();
                        Object attrValue = mBeanServer.getAttribute(mBeanName, attrName);
                        processAttrValue(snapshot, new PropertyNameBuilder(pMetricsAttr.getName()), attrValue);
                    } catch (Exception exc) {
                        Utils.logThrowable(LOGGER, OpLevel.WARNING,
                                StreamsResources.getBundle(KafkaStreamConstants.RESOURCE_BUNDLE_NAME),
                                "MetricsReporter.bean.attr.fail", mBeanName, pMetricsAttr.getName(), exc);
                    }
                }
    
                if (getSnapshotPropIgnoreCase(snapshot, OBJ_NAME_ENTRY_KEY) == null) {
                    snapshot.add(OBJ_NAME_ENTRY_KEY, mBeanName.getCanonicalName());
                }
                if (useObjectNameProperties) {
                    snapshot.add("domain", mBeanName.getDomain()); // NON-NLS
                    Map<String, String> objNameProps = mBeanName.getKeyPropertyList();
                    for (Map.Entry<String, String> objNameProp : objNameProps.entrySet()) {
                        String propKey = objNameProp.getKey();
                        Object mv = snapshot.get(propKey);
                        snapshot.add(propKey + (mv == null ? "" : "_"), objNameProp.getValue()); // NON-NLS
                    }
                }
                activity.addSnapshot(snapshot);
            } catch (Exception exc) {
                Utils.logThrowable(LOGGER, OpLevel.WARNING,
                        StreamsResources.getBundle(KafkaStreamConstants.RESOURCE_BUNDLE_NAME),
                        "MetricsReporter.bean.info.fail", mBeanName, exc);
            }
        }
    }
    

    From source file:com.brienwheeler.lib.jmx.logging.Log4jMBeanExporter.java

    @SuppressWarnings("unchecked")
    private synchronized void shutdown() {
        shutdown = true;//from ww w . j  a v  a 2s  .  c o  m
        killDelayedThread();
    
        MBeanServer server = JmxUtils.locateMBeanServer();
        HierarchyDynamicMBean hdm = hierarchyDynamicMBean.get();
        for (ObjectName registeredName : registeredNames) {
            try {
                server.unregisterMBean(registeredName);
    
                // The AbstractDynamicMBean base class of the HierarchyDynamicMBean tracks these names too
                // and will later try to unregister them and throw warning log messages unless we violate its
                // privacy and clean out its internal bookkeeping
                Field fld = ReflectionUtils.findField(hdm.getClass(), "mbeanList", Vector.class);
                fld.setAccessible(true);
                Vector<ObjectName> mbeanList = (Vector<ObjectName>) ReflectionUtils.getField(fld, hdm);
                mbeanList.remove(registeredName);
            } catch (Exception e) {
                log.error("Error unregistering " + registeredName.getCanonicalName(), e);
            }
        }
        registeredNames.clear();
    
        if (registeredHierarchy) {
            try {
                ObjectName mbo = new ObjectName(LOG4J_HIERARCHY_DEFAULT);
                server.unregisterMBean(mbo);
            } catch (Exception e) {
                log.error("Error unregistering Log4j MBean Hierarchy", e);
            }
            registeredHierarchy = false;
        }
    }