Java management query And Get Attribute - Java javax.management

Java examples for javax.management:ObjectName

Description

Java management query And Get Attribute

Demo Code


//package com.java2s;
import javax.management.MBeanServerConnection;
import javax.management.ObjectInstance;
import javax.management.ObjectName;

import java.util.Hashtable;
import java.util.Set;

public class Main {
    public static <T> T queryAndGetAttribute(
            MBeanServerConnection connection, String domain, String name,
            String type, String scope, String attribute) throws Exception {
        return queryAndGetAttribute(connection,
                getObjectName(domain, name, type, scope), attribute);
    }/*  ww w. j a v  a  2s  .  c  o m*/

    public static <T> T queryAndGetAttribute(
            MBeanServerConnection connection, ObjectName objectName,
            String attribute) throws Exception {
        Set<ObjectInstance> instances = queryConnectionBy(connection,
                objectName);

        if (instances != null && instances.size() == 1) {
            return getAttribute(connection, objectName, attribute);
        } else {
            return null;
        }
    }

    public static ObjectName getObjectName(String domain, String name,
            String type, String scope) throws Exception {
        Hashtable<String, String> map = new Hashtable<String, String>();
        if (name != null)
            map.put("name", name);
        if (type != null)
            map.put("type", type);
        if (scope != null)
            map.put("scope", scope);
        return ObjectName.getInstance(domain, map);
    }

    public static Set<ObjectInstance> queryConnectionBy(
            MBeanServerConnection connection, ObjectName objectName)
            throws Exception {
        return connection.queryMBeans(objectName, null);
    }

    public static Set<ObjectInstance> queryConnectionBy(
            MBeanServerConnection connection, String domain, String name,
            String type, String scope) throws Exception {
        return queryConnectionBy(connection,
                getObjectName(domain, name, type, scope));
    }

    @SuppressWarnings("unchecked")
    public static <T> T getAttribute(MBeanServerConnection connection,
            ObjectName objectName, String attribute) throws Exception {
        return (T) connection.getAttribute(objectName, attribute);
    }
}

Related Tutorials