Example usage for javax.management ObjectName ObjectName

List of usage examples for javax.management ObjectName ObjectName

Introduction

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

Prototype

public ObjectName(String name) throws MalformedObjectNameException 

Source Link

Document

Construct an object name from the given string.

Usage

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  ww w. j a  v a2  s .  co 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:fr.xebia.management.statistics.ProfileAspect.java

public ObjectName getObjectName() throws MalformedObjectNameException {
    if (objectName == null) {
        String objectNameAsString = jmxDomain + ":type=ProfileAspect";
        if (StringUtils.hasLength(name)) {
            objectNameAsString += ",name=" + ObjectName.quote(name);
        }//w w  w  .j ava  2  s .c om
        objectName = new ObjectName(objectNameAsString);
    }
    return objectName;
}

From source file:io.hawt.osgi.jmx.RBACDecorator.java

/**
 * If we have access to {@link ConfigurationAdmin}, we can add RBAC information
 * @param result//www  .j av  a2  s.com
 */
@Override
@SuppressWarnings("unchecked")
public void decorate(Map<String, Object> result) throws Exception {
    try {
        ServiceReference<ConfigurationAdmin> cmRef = bundleContext
                .getServiceReference(ConfigurationAdmin.class);
        ServiceReference<JMXSecurityMBean> jmxSecRef = bundleContext
                .getServiceReference(JMXSecurityMBean.class);
        if (cmRef != null && jmxSecRef != null) {
            ConfigurationAdmin configAdmin = bundleContext.getService(cmRef);
            JMXSecurityMBean jmxSec = bundleContext.getService(jmxSecRef);
            if (configAdmin != null && jmxSec != null) {
                // 1. each pair of MBean/operation has to be marked with RBAC flag (can/can't invoke)
                // 2. the information is provided by org.apache.karaf.management.JMXSecurityMBean.canInvoke(java.util.Map)
                // 3. we'll peek into available configadmin jmx.acl* configs, to see which MBeans/operations have to
                //    be examined and which will produce same results
                // 4. only then we'll prepare Map as parameter for canInvoke()

                Configuration[] configurations = configAdmin.listConfigurations("(service.pid=jmx.acl*)");
                List<String> allJmxAclPids = new LinkedList<>();
                for (Configuration cfg : configurations) {
                    allJmxAclPids.add(cfg.getPid());
                }
                if (allJmxAclPids.size() == 0) {
                    return;
                }

                Map<String, Map<String, Object>> domains = (Map<String, Map<String, Object>>) result
                        .get("domains");

                // cache contains MBeanInfos for different MBeans/ObjectNames
                Map<String, Map<String, Object>> cache = (Map<String, Map<String, Object>>) result.get("cache");
                // new cache will contain MBeanInfos + RBAC info
                Map<String, Map<String, Object>> rbacCache = new HashMap<>();

                // the fact that some MBeans share JSON MBeanInfo doesn't mean that they can share RBAC info
                // - each MBean's name may have RBAC information configured in different PIDs.

                // when iterating through all reapeating MBeans that share MBeanInfo (that doesn't have RBAC info
                // yet), we have to decide if it'll use shared info after RBAC check or will switch to dedicated
                // info. we have to be careful not to end with most MBeans *not* sharing MBeanInfo (in case if
                // somehow the shared info will be "special case" from RBAC point of view)

                Map<String, List<String>> queryForMBeans = new HashMap<>();
                Map<String, List<String>> queryForMBeanOperations = new HashMap<>();

                for (String domain : domains.keySet()) {
                    Map<String, Object> domainMBeansCheck = new HashMap<>(domains.get(domain));
                    Map<String, Object> domainMBeans = domains.get(domain);
                    for (String name : domainMBeansCheck.keySet()) {
                        Object mBeanInfo = domainMBeansCheck.get(name);
                        String fullName = domain + ":" + name;
                        ObjectName n = new ObjectName(fullName);
                        if (mBeanInfo instanceof Map) {
                            // not shared JSONified MBeanInfo
                            prepareKarafRbacInvocations(fullName, (Map<String, Object>) mBeanInfo,
                                    queryForMBeans, queryForMBeanOperations);
                        } else /*if (mBeanInfo instanceof String)*/ {
                            // shared JSONified MBeanInfo

                            // shard mbeanNames sharing MBeanInfo by the hierarchy of jmx.acl* PIDs used to
                            // check RBAC info
                            String key = (String) mBeanInfo;
                            String pidListKey = pidListKey(allJmxAclPids, n);
                            if (!rbacCache.containsKey(key + ":" + pidListKey)) {
                                // shallow copy - we can share op/not/attr/desc, but we put specific
                                // canInvoke/opByString keys
                                HashMap<String, Object> sharedMBeanAndRbacInfo = new HashMap<>(cache.get(key));
                                rbacCache.put(key + ":" + pidListKey, sharedMBeanAndRbacInfo);
                                // we'll be checking RBAC only for single (first) MBean having this pidListKey
                                prepareKarafRbacInvocations(fullName, sharedMBeanAndRbacInfo, queryForMBeans,
                                        queryForMBeanOperations);
                            }
                            // switch key from shared MBeanInfo-only to shared MBean+RbacInfo
                            domainMBeans.put(name, key + ":" + pidListKey);
                        }
                    }
                }

                // RBAC per MBeans (can invoke *any* operation or attribute?)
                TabularData dataForMBeans = jmxSec.canInvoke(queryForMBeans);
                Collection<?> results = dataForMBeans.values();
                for (Object cd : results) {
                    ObjectName objectName = new ObjectName((String) ((CompositeData) cd).get("ObjectName"));
                    boolean canInvoke = ((CompositeData) cd).get("CanInvoke") != null
                            ? (Boolean) ((CompositeData) cd).get("CanInvoke")
                            : false;
                    Object mBeanInfoOrKey = domains.get(objectName.getDomain())
                            .get(objectName.getKeyPropertyListString());
                    Map<String, Object> mBeanInfo;
                    if (mBeanInfoOrKey instanceof Map) {
                        mBeanInfo = (Map<String, Object>) mBeanInfoOrKey;
                    } else /*if (mBeanInfoOrKey instanceof String) */ {
                        mBeanInfo = rbacCache.get(mBeanInfoOrKey.toString());
                    }
                    if (mBeanInfo != null) {
                        mBeanInfo.put("canInvoke", canInvoke);
                    }
                }

                // RBAC per { MBean,operation } (can invoke status for each operation)
                TabularData dataForMBeanOperations = jmxSec.canInvoke(queryForMBeanOperations);
                results = dataForMBeanOperations.values();
                for (Object cd : results) {
                    ObjectName objectName = new ObjectName((String) ((CompositeData) cd).get("ObjectName"));
                    String method = (String) ((CompositeData) cd).get("Method");
                    boolean canInvoke = ((CompositeData) cd).get("CanInvoke") != null
                            ? (Boolean) ((CompositeData) cd).get("CanInvoke")
                            : false;
                    Object mBeanInfoOrKey = domains.get(objectName.getDomain())
                            .get(objectName.getKeyPropertyListString());
                    Map<String, Object> mBeanInfo;
                    if (mBeanInfoOrKey instanceof Map) {
                        mBeanInfo = (Map<String, Object>) mBeanInfoOrKey;
                    } else /*if (mBeanInfoOrKey instanceof String) */ {
                        mBeanInfo = rbacCache.get(mBeanInfoOrKey.toString());
                    }
                    if (mBeanInfo != null) {
                        ((Map<String, Object>) ((Map<String, Object>) mBeanInfo.get("opByString")).get(method))
                                .put("canInvoke", canInvoke);
                    }
                }

                result.remove("cache");
                result.put("cache", rbacCache);
            }
        }
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        // simply do not decorate
    }
}

From source file:com.taobao.tddl.common.util.TDDLMBeanServer.java

private void registerMBeanWithIdPrefix0(Object o, String idPrefix) {
    // MBean/*from   ww  w.j  a  v  a 2s.  c  o  m*/
    if (null != mbs) {
        if (null == idPrefix || idPrefix.length() == 0) {
            idPrefix = "default";
        }
        idPrefix = idPrefix.replace(":", "-");

        try {
            String id = this.getId(o.getClass().getName(), idPrefix);

            mbs.registerMBean(o, new ObjectName(o.getClass().getPackage().getName() + ":type="
                    + o.getClass().getSimpleName() + ",id=" + id));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

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

/**
 * Integration test for the registration service
 *//*  w w  w . j  a va2 s.  co m*/
public void testRegistrationServiceThreeTrue() throws Exception {
    ManagementService.registerMBeans(manager, mBeanServer, true, true, true, false);
    assertEquals(27, mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null).size());

}

From source file:com.stratio.cassandra.lucene.IndexService.java

void init() {

    // Initialize index
    List<SortField> keySortFields = keySortFields();
    Sort keySort = new Sort(keySortFields.toArray(new SortField[keySortFields.size()]));
    try {/*from   w  ww  .j a  v  a 2s. c  om*/
        lucene.init(keySort, fieldsToLoad());
    } catch (Exception e) {
        logger.error(String.format("Initialization of Lucene FS directory for index '%s' has failed, "
                + "this could be caused by on-disk data corruption, "
                + "or by an upgrade to an incompatible version, "
                + "try to drop the failing index and create it again:", name), e);
    }

    // Register JMX MBean
    try {
        mbean = new ObjectName(mbeanName);
        ManagementFactory.getPlatformMBeanServer().registerMBean(this, this.mbean);
    } catch (JMException e) {
        logger.error("Error while registering Lucene index JMX MBean", e);
    }
}

From source file:io.github.albertopires.mjc.JConsoleM.java

public long getHeapUsage() throws Exception {
    ObjectName mbeanName;//from www .  ja  va  2  s  .  c o  m
    mbeanName = new ObjectName("java.lang:type=Memory");
    CompositeDataSupport o;
    o = (CompositeDataSupport) mbsc.getAttribute(mbeanName, "HeapMemoryUsage");
    return ((Long) o.get("used")).longValue();
}

From source file:be.fedict.trust.service.snmp.SNMPInterceptor.java

public static void increment(String oid, String service, Long increment) {

    LOG.debug("increment counter oid=" + oid + " @ service=" + service + " with " + increment);

    try {/*from   www.  j  av  a 2 s .  com*/
        for (MBeanServer mBeanServer : MBeanServerFactory.findMBeanServer(null)) {
            mBeanServer.invoke(new ObjectName(service), "increment", new Object[] { oid, increment },
                    new String[] { "java.lang.String", "java.lang.Long" });

        }
    } catch (Exception e) {
        LOG.error("Failed to contact SNMP Mbean: " + e.getMessage(), e);
    }

}

From source file:com.sun.grizzly.http.jk.common.ChannelUn.java

public void init() throws IOException {
    if (file == null) {
        LoggerUtils.getLogger().log(Level.FINEST, "No file, disabling unix channel");
        return;//from  w ww.j  a v a 2 s .c om
        //throw new IOException( "No file for the unix socket channel");
    }
    if (wEnv != null && wEnv.getLocalId() != 0) {
        localId = wEnv.getLocalId();
    }

    if (localId != 0) {
        file = file + localId;
    }
    File socketFile = new File(file);
    if (!socketFile.isAbsolute()) {
        String home = wEnv.getJkHome();
        if (home == null) {
            LoggerUtils.getLogger().log(Level.FINEST, "No jkhome");
        } else {
            File homef = new File(home);
            socketFile = new File(homef, file);
            LoggerUtils.getLogger().log(Level.FINEST, "Making the file absolute " + socketFile);
        }
    }

    if (!socketFile.exists()) {
        try {
            FileOutputStream fos = new FileOutputStream(socketFile);
            fos.write(1);
            fos.close();
        } catch (Throwable t) {
            LoggerUtils.getLogger().log(Level.SEVERE,
                    "Attempting to create the file failed, disabling channel" + socketFile);
            return;
        }
    }
    // The socket file cannot be removed ...
    if (!socketFile.delete()) {
        LoggerUtils.getLogger().log(Level.SEVERE, "Can't remove socket file " + socketFile);
        return;
    }

    super.initNative("channel.un:" + file);

    if (apr == null || !apr.isLoaded()) {
        LoggerUtils.getLogger().log(Level.FINEST, "Apr is not available, disabling unix channel ");
        apr = null;
        return;
    }

    // Set properties and call init.
    setNativeAttribute("file", file);
    // unixListenSocket=apr.unSocketListen( file, 10 );

    setNativeAttribute("listen", "10");
    // setNativeAttribute( "debug", "10" );

    // Initialize the thread pool and execution chain
    if (next == null && wEnv != null) {
        if (nextName != null) {
            setNext(wEnv.getHandler(nextName));
        }
        if (next == null) {
            next = wEnv.getHandler("dispatch");
        }
        if (next == null) {
            next = wEnv.getHandler("request");
        }
    }

    super.initJkComponent();
    JMXRequestNote = wEnv.getNoteId(WorkerEnv.ENDPOINT_NOTE, "requestNote");
    // Run a thread that will accept connections.
    if (this.domain != null) {
        try {
            tpOName = new ObjectName(domain + ":type=ThreadPool,name=" + getChannelName());

            Registry.getRegistry(null, null).registerComponent(tp, tpOName, null);

            rgOName = new ObjectName(domain + ":type=GlobalRequestProcessor,name=" + getChannelName());
            Registry.getRegistry(null, null).registerComponent(global, rgOName, null);
        } catch (Exception e) {
            LoggerUtils.getLogger().log(Level.SEVERE, "Can't register threadpool");
        }
    }
    tp.start();
    AprAcceptor acceptAjp = new AprAcceptor(this);
    tp.runIt(acceptAjp);
    LoggerUtils.getLogger().info("JK: listening on unix socket: " + file);

}

From source file:com.zabbix.gateway.JMXItemChecker.java

@Override
protected String getStringValue(String key) throws Exception {
    ZabbixItem item = new ZabbixItem(key);

    if (item.getKeyId().equals("jmx")) {
        if (2 != item.getArgumentCount())
            throw new ZabbixException("required key format: jmx[<object name>,<attribute name>]");

        ObjectName objectName = new ObjectName(item.getArgument(1));
        String attributeName = item.getArgument(2);
        String realAttributeName;
        String fieldNames = "";

        // Attribute name and composite data field names are separated by dots. On the other hand the
        // name may contain a dot too. In this case user needs to escape it with a backslash. Also the
        // backslash symbols in the name must be escaped. So a real separator is unescaped dot and
        // separatorIndex() is used to locate it.

        int sep = HelperFunctionChest.separatorIndex(attributeName);

        if (-1 != sep) {
            logger.trace("'{}' contains composite data", attributeName);

            realAttributeName = attributeName.substring(0, sep);
            fieldNames = attributeName.substring(sep + 1);
        } else/*from  w  ww  . j  ava 2 s.c o m*/
            realAttributeName = attributeName;

        // unescape possible dots or backslashes that were escaped by user
        realAttributeName = HelperFunctionChest.unescapeUserInput(realAttributeName);

        logger.trace("attributeName:'{}'", realAttributeName);
        logger.trace("fieldNames:'{}'", fieldNames);

        return getPrimitiveAttributeValue(mbsc.getAttribute(objectName, realAttributeName), fieldNames);
    } else if (item.getKeyId().equals("jmx.discovery")) {
        ObjectName objectName = null;
        String attributeName = null;
        if (item.getArgumentCount() >= 1) {
            objectName = new ObjectName(item.getArgument(1));
        }

        if (item.getArgumentCount() >= 2) {
            attributeName = item.getArgument(2);
        }

        JSONArray counters = new JSONArray();

        logger.trace("attributeName = {}, item.getArgumentCount() = " + item.getArgumentCount(), attributeName);

        for (ObjectName name : mbsc.queryNames(objectName, null)) {
            logger.trace("discovered object '{}'", name);

            for (MBeanAttributeInfo attrInfo : mbsc.getMBeanInfo(name).getAttributes()) {
                logger.trace("discovered attribute '{}'", attrInfo.getName());

                if (!attrInfo.isReadable()) {
                    logger.trace("attribute not readable, skipping");
                    continue;
                }

                try {
                    if (null == attributeName || attrInfo.getName().equals(attributeName)) {
                        logger.trace("looking for attributes of primitive types");
                        String descr = (attrInfo.getName().equals(attrInfo.getDescription()) ? null
                                : attrInfo.getDescription());
                        findPrimitiveAttributes(counters, name, descr, attrInfo.getName(),
                                mbsc.getAttribute(name, attrInfo.getName()));
                    }
                } catch (Exception e) {
                    Object[] logInfo = { name, attrInfo.getName(), e };
                    logger.trace("processing '{},{}' failed", logInfo);
                }
            }
        }

        JSONObject mapping = new JSONObject();
        mapping.put(ItemChecker.JSON_TAG_DATA, counters);
        return mapping.toString(2);
    } else
        throw new ZabbixException("key ID '%s' is not supported", item.getKeyId());
}