Example usage for javax.management MBeanServer getAttribute

List of usage examples for javax.management MBeanServer getAttribute

Introduction

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

Prototype

public Object getAttribute(ObjectName name, String attribute)
        throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException;

Source Link

Usage

From source file:org.lobzik.home_sapiens.pi.AppData.java

public static List<String> getHTTPEndPoints() throws Exception { //tomcat-specific
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    Set<ObjectName> objs = mbs.queryNames(new ObjectName("*:type=Connector,*"),
            Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
    String hostname = InetAddress.getLocalHost().getHostName();
    InetAddress[] addresses = InetAddress.getAllByName(hostname);
    ArrayList<String> endPoints = new ArrayList<String>();
    for (Iterator<ObjectName> i = objs.iterator(); i.hasNext();) {
        ObjectName obj = i.next();
        String scheme = mbs.getAttribute(obj, "scheme").toString();
        if (!scheme.toLowerCase().equals("http")) {
            continue;
        }//from  w ww.  j a v a 2s . co m
        String port = obj.getKeyProperty("port");
        for (InetAddress addr : addresses) {
            String host = addr.getHostAddress();
            String ep = scheme + "://" + host + ":" + port;
            endPoints.add(ep);
        }
    }
    return endPoints;
}

From source file:at.ac.tuwien.dsg.cloud.salsa.engine.utils.SystemFunctions.java

public static List<String> getEndPoints()
        throws MalformedObjectNameException, NullPointerException, UnknownHostException,
        AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    Set<ObjectName> objs = mbs.queryNames(new ObjectName("*:type=Connector,*"),
            Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
    String hostname = InetAddress.getLocalHost().getHostName();
    InetAddress[] addresses = InetAddress.getAllByName(hostname);
    ArrayList<String> endPoints = new ArrayList<>();
    for (Iterator<ObjectName> i = objs.iterator(); i.hasNext();) {
        ObjectName obj = i.next();
        String scheme = mbs.getAttribute(obj, "scheme").toString();
        String port = obj.getKeyProperty("port");
        for (InetAddress addr : addresses) {
            String host = addr.getHostAddress();
            String ep = scheme + "://" + host + ":" + port;
            endPoints.add(ep);/*from ww  w  . ja v  a2s.  c  o  m*/
        }
    }
    return endPoints;
}

From source file:Utilities.java

/**
 * Prints bean attributes to a {@link VarOutputSink}.
 * //from   ww w .  j av a 2s .co  m
 * @param sink The {@link VarOutputSink} to which attributes will be sent
 * @param mbs The {@link MBeanServer} with respect to which the
 *          {@code objectName} is accessed
 * @param objectName The {@link ObjectName} that identifies this bean
 */
public static void printMBeanAttributes(VarOutputSink sink, MBeanServer mbs, ObjectName objectName) {
    MBeanInfo info = getMBeanInfoSafely(sink, mbs, objectName);
    if (info == null) {
        sink.printVariable(objectName.getCanonicalName(), "can't fetch info");
        return;
    }
    MBeanAttributeInfo[] attrInfo = info.getAttributes();
    if (attrInfo.length > 0) {
        for (int i = 0; i < attrInfo.length; i++) {
            String attrName = attrInfo[i].getName();
            Object attrValue = null;
            String attrValueString = null;
            try {
                attrValue = mbs.getAttribute(objectName, attrName);
            } catch (AttributeNotFoundException e) {
                attrValueString = "AttributeNotFoundException";
            } catch (InstanceNotFoundException e) {
                attrValueString = "InstanceNotFoundException";
            } catch (MBeanException e) {
                attrValueString = "MBeanException";
            } catch (ReflectionException e) {
                attrValueString = "ReflectionException";
            }
            if (attrValueString == null) {
                attrValueString = attrValue.toString();
            }
            sink.printVariable(attrName, attrValueString);
        }
    }
}

From source file:org.apache.catalina.mbeans.MBeanDumper.java

/**
 * The following code to dump MBeans has been copied from JMXProxyServlet.
 *
 *///from w  ww  . ja v a 2 s.c o  m
public static String dumpBeans(MBeanServer mbeanServer, Set<ObjectName> names) {
    StringBuilder buf = new StringBuilder();
    Iterator<ObjectName> it = names.iterator();
    while (it.hasNext()) {
        ObjectName oname = it.next();
        buf.append("Name: ");
        buf.append(oname.toString());
        buf.append(CRLF);

        try {
            MBeanInfo minfo = mbeanServer.getMBeanInfo(oname);
            // can't be null - I think
            String code = minfo.getClassName();
            if ("org.apache.commons.modeler.BaseModelMBean".equals(code)) {
                code = (String) mbeanServer.getAttribute(oname, "modelerType");
            }
            buf.append("modelerType: ");
            buf.append(code);
            buf.append(CRLF);

            MBeanAttributeInfo attrs[] = minfo.getAttributes();
            Object value = null;

            for (int i = 0; i < attrs.length; i++) {
                if (!attrs[i].isReadable())
                    continue;
                String attName = attrs[i].getName();
                if ("modelerType".equals(attName))
                    continue;
                if (attName.indexOf("=") >= 0 || attName.indexOf(":") >= 0 || attName.indexOf(" ") >= 0) {
                    continue;
                }

                try {
                    value = mbeanServer.getAttribute(oname, attName);
                } catch (JMRuntimeException rme) {
                    Throwable cause = rme.getCause();
                    if (cause instanceof UnsupportedOperationException) {
                        if (log.isDebugEnabled()) {
                            log.debug("Error getting attribute " + oname + " " + attName, rme);
                        }
                    } else if (cause instanceof NullPointerException) {
                        if (log.isDebugEnabled()) {
                            log.debug("Error getting attribute " + oname + " " + attName, rme);
                        }
                    } else {
                        log.error("Error getting attribute " + oname + " " + attName, rme);
                    }
                    continue;
                } catch (Throwable t) {
                    ExceptionUtils.handleThrowable(t);
                    log.error("Error getting attribute " + oname + " " + attName, t);
                    continue;
                }
                if (value == null)
                    continue;
                String valueString;
                try {
                    Class<?> c = value.getClass();
                    if (c.isArray()) {
                        int len = Array.getLength(value);
                        StringBuilder sb = new StringBuilder(
                                "Array[" + c.getComponentType().getName() + "] of length " + len);
                        if (len > 0) {
                            sb.append(CRLF);
                        }
                        for (int j = 0; j < len; j++) {
                            sb.append("\t");
                            Object item = Array.get(value, j);
                            if (item == null) {
                                sb.append("NULL VALUE");
                            } else {
                                try {
                                    sb.append(escape(item.toString()));
                                } catch (Throwable t) {
                                    ExceptionUtils.handleThrowable(t);
                                    sb.append("NON-STRINGABLE VALUE");
                                }
                            }
                            if (j < len - 1) {
                                sb.append(CRLF);
                            }
                        }
                        valueString = sb.toString();
                    } else {
                        valueString = escape(value.toString());
                    }
                    buf.append(attName);
                    buf.append(": ");
                    buf.append(valueString);
                    buf.append(CRLF);
                } catch (Throwable t) {
                    ExceptionUtils.handleThrowable(t);
                }
            }
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
        }
        buf.append(CRLF);
    }
    return buf.toString();

}

From source file:org.apache.hadoop.hbase.util.JSONBean.java

private static void writeAttribute(final JsonGenerator jg, final MBeanServer mBeanServer, ObjectName oname,
        final boolean description, final MBeanAttributeInfo attr) throws IOException {
    if (!attr.isReadable()) {
        return;// w  ww  .j  a  v  a2  s .c  om
    }
    String attName = attr.getName();
    if ("modelerType".equals(attName)) {
        return;
    }
    if (attName.indexOf("=") >= 0 || attName.indexOf(":") >= 0 || attName.indexOf(" ") >= 0) {
        return;
    }
    String descriptionStr = description ? attr.getDescription() : null;
    Object value = null;
    try {
        value = mBeanServer.getAttribute(oname, attName);
    } catch (RuntimeMBeanException e) {
        // UnsupportedOperationExceptions happen in the normal course of business,
        // so no need to log them as errors all the time.
        if (e.getCause() instanceof UnsupportedOperationException) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Getting attribute " + attName + " of " + oname + " threw " + e);
            }
        } else {
            LOG.error("getting attribute " + attName + " of " + oname + " threw an exception", e);
        }
        return;
    } catch (RuntimeErrorException e) {
        // RuntimeErrorException happens when an unexpected failure occurs in getAttribute
        // for example https://issues.apache.org/jira/browse/DAEMON-120
        LOG.debug("getting attribute " + attName + " of " + oname + " threw an exception", e);
        return;
    } catch (AttributeNotFoundException e) {
        //Ignored the attribute was not found, which should never happen because the bean
        //just told us that it has this attribute, but if this happens just don't output
        //the attribute.
        return;
    } catch (MBeanException e) {
        //The code inside the attribute getter threw an exception so log it, and
        // skip outputting the attribute
        LOG.error("getting attribute " + attName + " of " + oname + " threw an exception", e);
        return;
    } catch (RuntimeException e) {
        //For some reason even with an MBeanException available to them Runtime exceptions
        //can still find their way through, so treat them the same as MBeanException
        LOG.error("getting attribute " + attName + " of " + oname + " threw an exception", e);
        return;
    } catch (ReflectionException e) {
        //This happens when the code inside the JMX bean (setter?? from the java docs)
        //threw an exception, so log it and skip outputting the attribute
        LOG.error("getting attribute " + attName + " of " + oname + " threw an exception", e);
        return;
    } catch (InstanceNotFoundException e) {
        //Ignored the mbean itself was not found, which should never happen because we
        //just accessed it (perhaps something unregistered in-between) but if this
        //happens just don't output the attribute.
        return;
    }

    writeAttribute(jg, attName, descriptionStr, value);
}

From source file:com.atolcd.alfresco.audit.web.scripts.RuntimeInfoGet.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {

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

        // Map that will be passed to the template
        Map<String, Object> model = new HashMap<String, Object>();

        ObjectName runtimeName = new ObjectName("Alfresco:Name=Runtime");
        MBeanServer mbs = getMBeanServer(runtimeName);

        model.put("FreeMemory", (Long) mbs.getAttribute(runtimeName, "FreeMemory") / 1024 / 1024);
        model.put("MaxMemory", (Long) mbs.getAttribute(runtimeName, "MaxMemory") / 1024 / 1024);
        model.put("TotalMemory", (Long) mbs.getAttribute(runtimeName, "TotalMemory") / 1024 / 1024);

        return model;
    } catch (Exception e) {
        throw new WebScriptException("[RuntimeInfosGet] Error in executeImpl function : \n" + e.getMessage());
    }

}

From source file:com.atolcd.alfresco.audit.web.scripts.DatabaseInfoGet.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {

    try {//  ww w . ja va  2 s  .c o m
        // Map that will be passed to the template
        Map<String, Object> model = new HashMap<String, Object>();

        // Copy server object in a local object "MBeanProxy"
        ObjectName dbName = new ObjectName("Alfresco:Name=DatabaseInformation");
        MBeanServer mbs = getMBeanServer(dbName);

        model.put("DatabaseProductName", mbs.getAttribute(dbName, "DatabaseProductName"));
        model.put("DatabaseProductVersion", mbs.getAttribute(dbName, "DatabaseProductVersion"));
        model.put("DriverName", mbs.getAttribute(dbName, "DriverName"));
        model.put("DriverVersion", mbs.getAttribute(dbName, "DriverVersion"));
        model.put("URL", mbs.getAttribute(dbName, "URL"));
        model.put("UserName", mbs.getAttribute(dbName, "UserName"));

        return model;
    } catch (Exception e) {
        throw new WebScriptException("[DatabaseInfoGet] Error in executeImpl function : \n" + e.getMessage());
    }

}

From source file:com.atolcd.alfresco.audit.web.scripts.SystemPropertiesGet.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {

    try {/*from www .j a v a 2 s  .  com*/
        // Map that will be passed to the template
        Map<String, Object> model = new HashMap<String, Object>();

        // Copy server object in a local object "MBeanProxy"
        ObjectName systemName = new ObjectName("Alfresco:Name=SystemProperties");
        MBeanServer mbsc = getMBeanServer(systemName);

        model.put("AlfrescoHome", mbsc.getAttribute(systemName, "alfresco.jmx.dir"));
        model.put("CatalinaHome", mbsc.getAttribute(systemName, "catalina.home"));
        model.put("HibernateDialect", mbsc.getAttribute(systemName, "hibernate.dialect"));
        model.put("JavaClassPath", mbsc.getAttribute(systemName, "java.class.path"));
        model.put("JavaHome", mbsc.getAttribute(systemName, "java.home"));
        model.put("JavaRuntimeName", mbsc.getAttribute(systemName, "java.runtime.name"));
        model.put("JavaRuntimeVersion", mbsc.getAttribute(systemName, "java.runtime.version"));
        model.put("JavaVersion", mbsc.getAttribute(systemName, "java.version"));
        model.put("OsArch", mbsc.getAttribute(systemName, "os.arch"));
        model.put("OsName", mbsc.getAttribute(systemName, "os.name"));
        model.put("OsVersion", mbsc.getAttribute(systemName, "os.version"));
        model.put("UserCountry", mbsc.getAttribute(systemName, "user.country"));
        model.put("UserLanguage", mbsc.getAttribute(systemName, "user.language"));
        model.put("UserTimezone", mbsc.getAttribute(systemName, "user.timezone"));

        return model;
    } catch (Exception e) {
        throw new WebScriptException("[SystemPropertiesGet] Error in executeImpl function");
    }
}

From source file:org.neo4j.server.modules.WebAdminModuleTest.java

@Test
public void shouldRegisterASingleUri() throws Exception {
    WebServer webServer = mock(WebServer.class);

    NeoServerWithEmbeddedWebServer neoServer = mock(NeoServerWithEmbeddedWebServer.class);
    when(neoServer.baseUri()).thenReturn(new URI("http://localhost:7575"));
    when(neoServer.getWebServer()).thenReturn(webServer);

    Database db = mock(Database.class);
    db.graph = (mock(AbstractGraphDatabase.class));
    Kernel mockKernel = mock(Kernel.class);
    ObjectName mockObjectName = mock(ObjectName.class);
    when(mockKernel.getMBeanQuery()).thenReturn(mockObjectName);
    when(db.graph.getManagementBeans(Kernel.class)).thenReturn(Collections.singleton(mockKernel));

    when(neoServer.getDatabase()).thenReturn(db);
    when(neoServer.getConfiguration()).thenReturn(new MapConfiguration(new HashMap<Object, Object>()));

    Config config = mock(Config.class);
    when(db.graph.getConfig()).thenReturn(config);
    NodeManager nodeManager = mock(NodeManager.class);
    GraphDbModule graphDbModule = mock(GraphDbModule.class);
    when(config.getGraphDbModule()).thenReturn(graphDbModule);
    when(graphDbModule.getNodeManager()).thenReturn(nodeManager);

    CompositeDataSupport result = mock(CompositeDataSupport.class);
    when(result.get("used")).thenReturn(50L);
    when(result.get("max")).thenReturn(1000L);

    MBeanServer mbeanServer = mock(MBeanServer.class);
    when(mbeanServer.getAttribute(any(ObjectName.class), eq("HeapMemoryUsage"))).thenReturn(result);
    // when(mbeanServer.getAttribute(any(ObjectName.class), eq("Collector"))).thenReturn( new StatisticCollector() );

    setStaticFinalField(JmxUtils.class.getDeclaredField("mbeanServer"), mbeanServer);

    WebAdminModule module = new WebAdminModule();
    module.start(neoServer, null);//from  w w  w .j  a va 2  s .c  o  m

    verify(db).setRrdDb(any(RrdDb.class));
}

From source file:org.apache.synapse.commons.snmp.SynapseMOScalar.java

@Override
public Variable getValue() {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {//  w  w  w.  j a  v a2 s .c o m
        Object obj = mbs.getAttribute(objectName, attribute);
        if (obj instanceof Integer) {
            return new Integer32((Integer) obj);
        }

        if (snmpVersion > SnmpConstants.version1) {
            if (obj instanceof Long) {
                return new Counter64(((Long) obj).longValue());
            } else if (obj instanceof Date) {
                return new Counter64(((Date) obj).getTime());
            }
        }

        return new OctetString(obj.toString());
    } catch (Exception e) {
        log.error("Unexpected error while retrieving the value of OID: " + getID(), e);
        return null;
    }
}