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.zanata.ZanataInit.java

private void checkAppServerVersion() throws MalformedObjectNameException, AttributeNotFoundException,
        MBeanException, ReflectionException, InstanceNotFoundException {
    MBeanServer jmx = ManagementFactory.getPlatformMBeanServer();
    ObjectName server = new ObjectName("jboss.as:management-root=server");
    String releaseCodename = (String) jmx.getAttribute(server, "releaseCodename");
    String releaseVersion = (String) jmx.getAttribute(server, "releaseVersion");
    String productName = (String) jmx.getAttribute(server, "productName");
    String productVersion = (String) jmx.getAttribute(server, "productVersion");
    log.info("App server release codename: {}", releaseCodename);
    log.info("App server release version: {}", releaseVersion);
    switch ((productName == null) ? "" : productName) {
    case "JBoss EAP":

    case "EAP":
        checkEAPVersion(productVersion);
        break;/*from  w  w w . jav a 2 s  .  c o m*/

    case "WildFly Full":
        checkWildFlyVersion(productVersion);
        break;

    default:
        log.warn("Unknown app server.  This application requires EAP >= {} or WildFly Full >= {}",
                MIN_EAP_VERSION, MIN_WILDFLY_VERSION);
        break;

    }
}

From source file:de.thorstenberger.taskmodel.view.webapp.filter.ExportPDFFilter.java

/**
 * Try to find a nonssl connector to retrieve shared resources like stylesheets, images etc. Fallback: Use request
 * url./*w  w  w  . j  a  va 2s.co m*/
 *
 * @param request
 * @return
 */
private String getLocalURL(final HttpServletRequest request) {

    final MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        for (final Object mbean : beanServer.queryMBeans(new ObjectName("*:type=Connector,*"), null)) {
            final ObjectInstance oi = (ObjectInstance) mbean;
            final Boolean isSecure = (Boolean) beanServer.getAttribute(oi.getObjectName(), "secure");
            final String protocol = (String) beanServer.getAttribute(oi.getObjectName(), "protocol");
            final int port = (Integer) beanServer.getAttribute(oi.getObjectName(), "port");
            if (!isSecure && protocol.startsWith("HTTP")) {
                log.debug(String.format("Using unsecured tomcat connector at port %d", port));
                return "http://localhost:" + port;
            }
        }
    } catch (final MalformedObjectNameException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final NullPointerException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final AttributeNotFoundException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final InstanceNotFoundException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final MBeanException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final ReflectionException e) {
        log.warn("Could not access JMX mbeans.", e);
    }
    String requestURL = request.getRequestURL().toString();
    log.warn("No mbeans of type '*:type=Connector,*' configured, using request url (assuming non-ssl): "
            + requestURL);
    return requestURL;
}

From source file:org.sakaiproject.nakamura.cluster.ClusterTrackingServiceImpl.java

/**
 * Activate the service, getting the id of the jvm instance and register the instance.
 *
 * @param ctx/*from   w w w .j a v  a 2 s. c  o m*/
 * @throws Exception
 */
@SuppressWarnings("unchecked")
protected void activate(ComponentContext ctx) throws Exception {

    Dictionary<String, Object> properties = ctx.getProperties();
    thisSecureUrl = (String) properties.get(PROP_SECURE_HOST_URL);

    componentStartTime = String.valueOf(System.currentTimeMillis());
    MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
    ObjectName name = new ObjectName("java.lang:type=Runtime");
    serverId = ((String) mbeanServer.getAttribute(name, "Name")).replace("@", "-");
    isActive = true;
    pingInstance();
    isReady = true;
}

From source file:de.msg.terminfindung.common.jmx.TestJmxUeberwachung.java

@Test
public void testJmxUeberwachung() throws Exception {
    // SpringContext initialisieren und Komponente holen
    //Meldung meldung = (Meldung) SpringContextHolder.getBean("meldung");
    // Holen des MBeanServers
    ArrayList<MBeanServer> mBeanServerList = MBeanServerFactory.findMBeanServer(null);
    MBeanServer mBeanServer = mBeanServerList.get(0);
    // Lesen der gewnschten Information per JMX
    // de.bund.bva.isyfact.terminfindung:type=ServiceStatistik,name=&quot;Erstellung-Statistik&quot;
    Hashtable<String, String> table = new Hashtable<>();
    table.put("type", "ServiceStatistik");
    table.put("name", "\"Erstellung-Statistik\"");
    ObjectName testObjectName = new ObjectName("de.bund.bva.isyfact.terminfindung", table);
    String testAttributeName = "DurchschnittsDauerLetzteAufrufe";
    String result = mBeanServer.getAttribute(testObjectName, testAttributeName).toString();
    // Auswerten des Ergebnisses
    assertEquals("0", result);
    // Einen Anwendungsfall ausfhren
    contr.initialisiereModel(new ErstellenModel());
    result = mBeanServer.getAttribute(testObjectName, testAttributeName).toString();
    assertNotEquals("0", result);
}

From source file:org.apache.webapp.admin.AttributeTag.java

/**
 * Render the JMX MBean attribute identified by this tag
 *
 * @exception JspException if a processing exception occurs
 *//*from  www  .j av a  2  s  . co  m*/
public int doEndTag() throws JspException {

    // Retrieve the object name identified by our attributes
    Object bean = null;
    if (scope == null) {
        bean = pageContext.findAttribute(name);
    } else if ("page".equalsIgnoreCase(scope)) {
        bean = pageContext.getAttribute(name, PageContext.PAGE_SCOPE);
    } else if ("request".equalsIgnoreCase(scope)) {
        bean = pageContext.getAttribute(name, PageContext.REQUEST_SCOPE);
    } else if ("session".equalsIgnoreCase(scope)) {
        bean = pageContext.getAttribute(name, PageContext.SESSION_SCOPE);
    } else if ("application".equalsIgnoreCase(scope)) {
        bean = pageContext.getAttribute(name, PageContext.APPLICATION_SCOPE);
    } else {
        throw new JspException("Invalid scope value '" + scope + "'");
    }
    if (bean == null) {
        throw new JspException("No bean '" + name + "' found");
    }
    if (property != null) {
        try {
            bean = PropertyUtils.getProperty(bean, property);
        } catch (Throwable t) {
            throw new JspException("Exception retrieving property '" + property + "': " + t);
        }
        if (bean == null) {
            throw new JspException("No property '" + property + "' found");
        }
    }

    // Convert to an object name as necessary
    ObjectName oname = null;
    try {
        if (bean instanceof ObjectName) {
            oname = (ObjectName) bean;
        } else if (bean instanceof String) {
            oname = new ObjectName((String) bean);
        } else {
            oname = new ObjectName(bean.toString());
        }
    } catch (Throwable t) {
        throw new JspException("Exception creating object name for '" + bean + "': " + t);
    }

    // Acquire a reference to our MBeanServer
    MBeanServer mserver = (MBeanServer) pageContext.getAttribute("org.apache.catalina.MBeanServer",
            PageContext.APPLICATION_SCOPE);
    if (mserver == null)
        throw new JspException("MBeanServer is not available");

    // Retrieve the specified attribute from the specified MBean
    Object value = null;
    try {
        value = mserver.getAttribute(oname, attribute);
    } catch (Throwable t) {
        throw new JspException("Exception retrieving attribute '" + attribute + "'");
    }

    // Render this value to our current output writer
    if (value != null) {
        JspWriter out = pageContext.getOut();
        try {
            out.print(value);
        } catch (IOException e) {
            throw new JspException("IOException: " + e);
        }
    }

    // Evaluate the remainder of this page
    return (EVAL_PAGE);

}

From source file:org.hyperic.hq.plugin.weblogic.jmx.ServerQuery.java

private void getSSLAttrs(MBeanServer mServer) {
    try {//from  www  .  ja  v  a  2 s  .c o m
        //SSLListenPort attribute only exists in ServerRuntimeMBean
        //so we have to get it for the nodes via the SSLMBean
        Object port = mServer.getAttribute(getSSL(), ATTR_LISTEN_PORT);
        this.attrs.put(ATTR_SSL_LISTEN_PORT, port.toString());
    } catch (Exception e) {
        //unlikely/ok
    }
}

From source file:org.apache.hadoop.hdfs.server.namenode.TestNameNodeMXBean.java

@SuppressWarnings({ "unchecked" })
@Test/*from ww  w .  ja  v a  2s. co  m*/
public void testNameNodeMXBeanInfo() throws Exception {
    Configuration conf = new Configuration();
    conf.setLong(DFSConfigKeys.DFS_DATANODE_MAX_LOCKED_MEMORY_KEY,
            NativeIO.POSIX.getCacheManipulator().getMemlockLimit());
    MiniDFSCluster cluster = null;

    try {
        cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
        cluster.waitActive();

        FSNamesystem fsn = cluster.getNameNode().namesystem;

        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName mxbeanName = new ObjectName("Hadoop:service=NameNode,name=NameNodeInfo");
        // get attribute "ClusterId"
        String clusterId = (String) mbs.getAttribute(mxbeanName, "ClusterId");
        assertEquals(fsn.getClusterId(), clusterId);
        // get attribute "BlockPoolId"
        String blockpoolId = (String) mbs.getAttribute(mxbeanName, "BlockPoolId");
        assertEquals(fsn.getBlockPoolId(), blockpoolId);
        // get attribute "Version"
        String version = (String) mbs.getAttribute(mxbeanName, "Version");
        assertEquals(fsn.getVersion(), version);
        assertTrue(version.equals(VersionInfo.getVersion() + ", r" + VersionInfo.getRevision()));
        // get attribute "Used"
        Long used = (Long) mbs.getAttribute(mxbeanName, "Used");
        assertEquals(fsn.getUsed(), used.longValue());
        // get attribute "Total"
        Long total = (Long) mbs.getAttribute(mxbeanName, "Total");
        assertEquals(fsn.getTotal(), total.longValue());
        // get attribute "safemode"
        String safemode = (String) mbs.getAttribute(mxbeanName, "Safemode");
        assertEquals(fsn.getSafemode(), safemode);
        // get attribute nondfs
        Long nondfs = (Long) (mbs.getAttribute(mxbeanName, "NonDfsUsedSpace"));
        assertEquals(fsn.getNonDfsUsedSpace(), nondfs.longValue());
        // get attribute percentremaining
        Float percentremaining = (Float) (mbs.getAttribute(mxbeanName, "PercentRemaining"));
        assertEquals(fsn.getPercentRemaining(), percentremaining, DELTA);
        // get attribute Totalblocks
        Long totalblocks = (Long) (mbs.getAttribute(mxbeanName, "TotalBlocks"));
        assertEquals(fsn.getTotalBlocks(), totalblocks.longValue());
        // get attribute alivenodeinfo
        String alivenodeinfo = (String) (mbs.getAttribute(mxbeanName, "LiveNodes"));
        Map<String, Map<String, Object>> liveNodes = (Map<String, Map<String, Object>>) JSON
                .parse(alivenodeinfo);
        assertTrue(liveNodes.size() == 2);
        for (Map<String, Object> liveNode : liveNodes.values()) {
            assertTrue(liveNode.containsKey("nonDfsUsedSpace"));
            assertTrue(((Long) liveNode.get("nonDfsUsedSpace")) > 0);
            assertTrue(liveNode.containsKey("capacity"));
            assertTrue(((Long) liveNode.get("capacity")) > 0);
            assertTrue(liveNode.containsKey("numBlocks"));
            assertTrue(((Long) liveNode.get("numBlocks")) == 0);
        }
        assertEquals(fsn.getLiveNodes(), alivenodeinfo);
        // get attribute deadnodeinfo
        String deadnodeinfo = (String) (mbs.getAttribute(mxbeanName, "DeadNodes"));
        assertEquals(fsn.getDeadNodes(), deadnodeinfo);
        // get attribute NodeUsage
        String nodeUsage = (String) (mbs.getAttribute(mxbeanName, "NodeUsage"));
        assertEquals("Bad value for NodeUsage", fsn.getNodeUsage(), nodeUsage);
        // get attribute NameJournalStatus
        String nameJournalStatus = (String) (mbs.getAttribute(mxbeanName, "NameJournalStatus"));
        assertEquals("Bad value for NameJournalStatus", fsn.getNameJournalStatus(), nameJournalStatus);
        // get attribute JournalTransactionInfo
        String journalTxnInfo = (String) mbs.getAttribute(mxbeanName, "JournalTransactionInfo");
        assertEquals("Bad value for NameTxnIds", fsn.getJournalTransactionInfo(), journalTxnInfo);
        // get attribute "NNStarted"
        String nnStarted = (String) mbs.getAttribute(mxbeanName, "NNStarted");
        assertEquals("Bad value for NNStarted", fsn.getNNStarted(), nnStarted);
        // get attribute "CompileInfo"
        String compileInfo = (String) mbs.getAttribute(mxbeanName, "CompileInfo");
        assertEquals("Bad value for CompileInfo", fsn.getCompileInfo(), compileInfo);
        // get attribute CorruptFiles
        String corruptFiles = (String) (mbs.getAttribute(mxbeanName, "CorruptFiles"));
        assertEquals("Bad value for CorruptFiles", fsn.getCorruptFiles(), corruptFiles);
        // get attribute NameDirStatuses
        String nameDirStatuses = (String) (mbs.getAttribute(mxbeanName, "NameDirStatuses"));
        assertEquals(fsn.getNameDirStatuses(), nameDirStatuses);
        Map<String, Map<String, String>> statusMap = (Map<String, Map<String, String>>) JSON
                .parse(nameDirStatuses);
        Collection<URI> nameDirUris = cluster.getNameDirs(0);
        for (URI nameDirUri : nameDirUris) {
            File nameDir = new File(nameDirUri);
            System.out.println("Checking for the presence of " + nameDir + " in active name dirs.");
            assertTrue(statusMap.get("active").containsKey(nameDir.getAbsolutePath()));
        }
        assertEquals(2, statusMap.get("active").size());
        assertEquals(0, statusMap.get("failed").size());

        // This will cause the first dir to fail.
        File failedNameDir = new File(nameDirUris.iterator().next());
        assertEquals(0, FileUtil.chmod(new File(failedNameDir, "current").getAbsolutePath(), "000"));
        cluster.getNameNodeRpc().rollEditLog();

        nameDirStatuses = (String) (mbs.getAttribute(mxbeanName, "NameDirStatuses"));
        statusMap = (Map<String, Map<String, String>>) JSON.parse(nameDirStatuses);
        for (URI nameDirUri : nameDirUris) {
            File nameDir = new File(nameDirUri);
            String expectedStatus = nameDir.equals(failedNameDir) ? "failed" : "active";
            System.out.println(
                    "Checking for the presence of " + nameDir + " in " + expectedStatus + " name dirs.");
            assertTrue(statusMap.get(expectedStatus).containsKey(nameDir.getAbsolutePath()));
        }
        assertEquals(1, statusMap.get("active").size());
        assertEquals(1, statusMap.get("failed").size());
        assertEquals(0L, mbs.getAttribute(mxbeanName, "CacheUsed"));
        assertEquals(NativeIO.POSIX.getCacheManipulator().getMemlockLimit() * cluster.getDataNodes().size(),
                mbs.getAttribute(mxbeanName, "CacheCapacity"));
        assertNull("RollingUpgradeInfo should be null when there is no rolling" + " upgrade",
                mbs.getAttribute(mxbeanName, "RollingUpgradeStatus"));
    } finally {
        if (cluster != null) {
            for (URI dir : cluster.getNameDirs(0)) {
                FileUtil.chmod(new File(new File(dir), "current").getAbsolutePath(), "755");
            }
            cluster.shutdown();
        }
    }
}

From source file:org.apache.streams.jackson.MemoryUsageDeserializer.java

@Override
public MemoryUsageBroadcast deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
        throws IOException, JsonProcessingException {
    try {//  w w  w .  j  a v  a  2s .co  m
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();

        MemoryUsageBroadcast memoryUsageBroadcast = new MemoryUsageBroadcast();
        JsonNode attributes = jsonParser.getCodec().readTree(jsonParser);

        ObjectName name = new ObjectName(attributes.get("canonicalName").asText());
        MBeanInfo info = server.getMBeanInfo(name);
        memoryUsageBroadcast.setName(name.toString());

        for (MBeanAttributeInfo attribute : Arrays.asList(info.getAttributes())) {
            switch (attribute.getName()) {
            case "Verbose":
                memoryUsageBroadcast.setVerbose((boolean) server.getAttribute(name, attribute.getName()));
                break;
            case "ObjectPendingFinalizationCount":
                memoryUsageBroadcast.setObjectPendingFinalizationCount(
                        Long.parseLong(server.getAttribute(name, attribute.getName()).toString()));
                break;
            case "HeapMemoryUsage":
                memoryUsageBroadcast.setHeapMemoryUsage(
                        (Long) ((CompositeDataSupport) server.getAttribute(name, attribute.getName()))
                                .get("used"));
                break;
            case "NonHeapMemoryUsage":
                memoryUsageBroadcast.setNonHeapMemoryUsage(
                        (Long) ((CompositeDataSupport) server.getAttribute(name, attribute.getName()))
                                .get("used"));
                break;
            }
        }

        return memoryUsageBroadcast;
    } catch (Exception e) {
        LOGGER.error("Exception trying to deserialize MemoryUsageDeserializer object: {}", e);
        return null;
    }
}

From source file:org.apache.camel.web.util.JMXRouteStatistics.java

@SuppressWarnings("unchecked")
public Object getRouteStatistic(CamelContext camelContext, String routeID, String attribute) {
    // only possible if JMX is enabled
    if (!(camelContext.getManagementStrategy() instanceof ManagedManagementStrategy)) {
        return null;
    }//  w  w  w  .  j a  v  a2 s. c  o m

    try {
        MBeanServer server = camelContext.getManagementStrategy().getManagementAgent().getMBeanServer();
        String domain = camelContext.getManagementStrategy().getManagementAgent().getMBeanObjectDomainName();

        ObjectName objName = new ObjectName(domain + ":type=routes,*");
        List<ObjectName> cacheList = new LinkedList(server.queryNames(objName, null));
        for (Iterator<ObjectName> iter = cacheList.iterator(); iter.hasNext();) {
            objName = iter.next();
            String keyProps = objName.getCanonicalKeyPropertyListString();
            ObjectName objectInfoName = new ObjectName(domain + ":" + keyProps);
            String currentRouteID = (String) server.getAttribute(objectInfoName, "RouteId");
            if (currentRouteID.equals(routeID)) {
                Object value = server.getAttribute(objectInfoName, attribute);
                if (value instanceof Date) {
                    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
                    return df.format(value);
                } else {
                    return value;
                }
            }
        }
    } catch (Exception e) {
        LOG.warn("Error getting route statistic from JMX. This exception will be ignored.", e);
    }

    return null;
}

From source file:org.rhq.enterprise.gui.startup.StartupServlet.java

/**
 * Gets the number of milliseconds since the time when the server was started.
 * @return elapsed time since server started, 0 if not known
 *///from   w  ww .j a v  a 2s.com
private long getElapsedTimeSinceStartup() throws ServletException {
    long elapsed;
    try {
        ObjectName jbossServerName = new ObjectName("jboss.system:type=Server");
        MBeanServer jbossServer = MBeanServerLocator.locateJBoss();
        Date startTime = (Date) jbossServer.getAttribute(jbossServerName, "StartDate");
        long currentTime = System.currentTimeMillis();
        elapsed = currentTime - startTime.getTime();
    } catch (Exception e) {
        elapsed = 0;
    }
    return elapsed;
}