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:com.app.server.EARDeployer.java

public void init(Vector serviceList, ServerConfig serverConfig, MBeanServer mbeanServer) {
    this.serviceList = serviceList;
    this.serverConfig = serverConfig;
    this.mbeanServer = mbeanServer;
    this.registry = registry;
    fsManager = new StandardFileSystemManager();
    try {/*w w  w  .j a  v  a 2  s.  com*/
        warObjectName = new ObjectName("com.app.server:type=deployer,service=WARDeployer");
        ejbObjectName = new ObjectName("com.app.server:type=deployer,service=EJBDeployer");
        sarObjectName = new ObjectName("com.app.server:type=deployer,service=SARDeployer");
        rarObjectName = new ObjectName("com.app.server:type=deployer,service=RARDeployer");
        ezbObjectName = new ObjectName("com.app.server:type=deployer,service=EZBeansDeployer");
        this.executorServiceMap = (Hashtable) mbeanServer.getAttribute(warObjectName, "ExecutorServiceMap");
        this.urlClassLoaderMap = (Hashtable) mbeanServer.getAttribute(warObjectName, "UrlClassLoaderMap");
        System.setProperty("java.io.tmpdir", serverConfig.getCachedir());
        /*DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir));
        //fsManager.setReplicator(new PrivilegedFileReplicator(replicator));
        fsManager.setTemporaryFileStore(replicator);*/
        fsManager.init();
    } catch (Exception e) {
        log.error("Error in initialization", e);
        // TODO Auto-generated catch block
        //e3.printStackTrace();
    }
}

From source file:org.sakaiproject.kernel.component.KernelLifecycle.java

/**
 * Execute the start phase of the lifecycle, creating the MBean and registering the newly started
 * Kernel with JMX.//  w  ww  .j a  v  a  2s .  c o m
 *
 * @see org.sakaiproject.kernel.loader.common.CommonLifecycle#start()
 */
public void start() {
    LOG.info("==========PHASE 1 STARTING =================");
    try {
        long start = System.currentTimeMillis();
        lifecycleEvent(CommonLifecycleEvent.BEFORE_START);
        lastLoadDate = new Date();

        // Start the kernel
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        RequiredModelMBean model = new RequiredModelMBean(createMBeanInfo());
        model.setManagedResource(this, "objectReference");
        ObjectName kernelName = new ObjectName(Kernel.MBEAN_KERNEL);
        mbs.registerMBean(model, kernelName);

        kernel = new KernelImpl();

        kernel.start();

        // Start the service manager
        serviceManager = new ServiceManagerImpl(kernel);
        serviceManager.start();

        // Start the component manager.
        componentManager = new ComponentManagerImpl(kernel);
        componentManager.start();

        try {
            System.runFinalization();
            Runtime.getRuntime().gc();
            CompositeData permGen = null;
            try {
                permGen = (CompositeData) mbs
                        .getAttribute(new ObjectName("java.lang:type=MemoryPool,name=Perm Gen"), "Usage");
            } catch (Exception ex) {
                permGen = (CompositeData) mbs
                        .getAttribute(new ObjectName("java.lang:type=MemoryPool,name=CMS Perm Gen"), "Usage");
            }
            CompositeData tenuredGen;
            try {
                tenuredGen = (CompositeData) mbs
                        .getAttribute(new ObjectName("java.lang:type=MemoryPool,name=Tenured Gen"), "Usage");
            } catch (Exception ex) {
                tenuredGen = (CompositeData) mbs
                        .getAttribute(new ObjectName("java.lang:type=MemoryPool,name=CMS Old Gen"), "Usage");
            }
            CompositeData codeCache = (CompositeData) mbs
                    .getAttribute(new ObjectName("java.lang:type=MemoryPool,name=Code Cache"), "Usage");
            CompositeData edenSpace = null;
            try {
                edenSpace = (CompositeData) mbs
                        .getAttribute(new ObjectName("java.lang:type=MemoryPool,name=Eden Space"), "Usage");
            } catch (Exception ex) {
                edenSpace = (CompositeData) mbs
                        .getAttribute(new ObjectName("java.lang:type=MemoryPool,name=Par Eden Space"), "Usage");

            }
            CompositeData survivorSpace = null;
            try {
                survivorSpace = (CompositeData) mbs
                        .getAttribute(new ObjectName("java.lang:type=MemoryPool,name=Survivor Space"), "Usage");
            } catch (Exception ex) {
                survivorSpace = (CompositeData) mbs.getAttribute(
                        new ObjectName("java.lang:type=MemoryPool,name=Par Survivor Space"), "Usage");
            }
            long permGenUsed = Long.parseLong(String.valueOf(permGen.get("used")));
            long codeCacheUsed = Long.parseLong(String.valueOf(codeCache.get("used")));
            long edenSpaceUsed = Long.parseLong(String.valueOf(edenSpace.get("used")));
            long tenuredGenUsed = Long.parseLong(String.valueOf(tenuredGen.get("used")));
            long survivorSpaceUsed = Long.parseLong(String.valueOf(survivorSpace.get("used")));

            LOG.info("Memory Stats after startup\n" + "\tPermgen Used " + permGenUsed / (ONEM) + " MB\n"
                    + "\tCode Cache Used " + codeCacheUsed / (ONEM) + " MB\n" + "\tEden Used "
                    + edenSpaceUsed / (ONEM) + " MB\n" + "\tTenured Used " + tenuredGenUsed / (ONEM) + " MB\n"
                    + "\tSurvivour Used " + survivorSpaceUsed / (ONEM) + " MB");
        } catch (RuntimeException ex2) {
            LOG.info("Startup Memory Stats Not available ", ex2);
        } catch (Exception ex2) {
            LOG.info("Startup Memory Stats Not available ", ex2);
        }
        lifecycleEvent(CommonLifecycleEvent.START);
        lifecycleEvent(CommonLifecycleEvent.AFTER_START);
        loadTime = System.currentTimeMillis() - start;

    } catch (Throwable ex) {
        LOG.error("Failed to start Component Lifecycle ", ex);
        throw new Error("Failed to start Component Lifecycle ", ex);
    }
    LOG.info("============END of LIFECYCLE STARTUP===============================");

}

From source file:org.apache.solr.cloud.api.collections.CollectionsAPIDistributedZkTest.java

private void checkNoTwoShardsUseTheSameIndexDir() throws Exception {
    Map<String, Set<String>> indexDirToShardNamesMap = new HashMap<>();

    List<MBeanServer> servers = new LinkedList<>();
    servers.add(ManagementFactory.getPlatformMBeanServer());
    servers.addAll(MBeanServerFactory.findMBeanServer(null));
    for (final MBeanServer server : servers) {
        Set<ObjectName> mbeans = new HashSet<>();
        mbeans.addAll(server.queryNames(null, null));
        for (final ObjectName mbean : mbeans) {

            try {
                Map<String, String> props = mbean.getKeyPropertyList();
                String category = props.get("category");
                String name = props.get("name");
                if ((category != null && category.toString().equals(Category.CORE.toString()))
                        && (name != null && name.equals("indexDir"))) {
                    String indexDir = server.getAttribute(mbean, "Value").toString();
                    String key = props.get("dom2") + "." + props.get("dom3") + "." + props.get("dom4");
                    if (!indexDirToShardNamesMap.containsKey(indexDir)) {
                        indexDirToShardNamesMap.put(indexDir.toString(), new HashSet<>());
                    }/*from  w ww . jav a2s .c o  m*/
                    indexDirToShardNamesMap.get(indexDir.toString()).add(key);
                }
            } catch (Exception e) {
                // ignore, just continue - probably a "Value" attribute
                // not found
            }
        }
    }

    assertTrue(
            "Something is broken in the assert for no shards using the same indexDir - probably something was changed in the attributes published in the MBean of "
                    + SolrCore.class.getSimpleName() + " : " + indexDirToShardNamesMap,
            indexDirToShardNamesMap.size() > 0);
    for (Entry<String, Set<String>> entry : indexDirToShardNamesMap.entrySet()) {
        if (entry.getValue().size() > 1) {
            fail("We have shards using the same indexDir. E.g. shards " + entry.getValue().toString()
                    + " all use indexDir " + entry.getKey());
        }
    }

}

From source file:com.streamsets.datacollector.bundles.content.SdcInfoContentGenerator.java

private void writeJmx(BundleWriter writer) throws IOException {
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();

    try (JsonGenerator generator = writer.createGenerator("runtime/jmx.json")) {
        generator.useDefaultPrettyPrinter();
        generator.writeStartObject();/* www  .  j  ava  2  s.  c om*/
        generator.writeArrayFieldStart("beans");

        for (ObjectName objectName : mBeanServer.queryNames(null, null)) {
            MBeanInfo info;
            try {
                info = mBeanServer.getMBeanInfo(objectName);
            } catch (InstanceNotFoundException | IntrospectionException | ReflectionException ex) {
                LOG.warn("Exception accessing MBeanInfo ", ex);
                continue;
            }

            generator.writeStartObject();
            generator.writeStringField("name", objectName.toString());
            generator.writeObjectFieldStart("attributes");

            for (MBeanAttributeInfo attr : info.getAttributes()) {
                try {
                    writeAttribute(generator, attr.getName(),
                            mBeanServer.getAttribute(objectName, attr.getName()));
                } catch (MBeanException | AttributeNotFoundException | InstanceNotFoundException
                        | ReflectionException | RuntimeMBeanException ex) {
                    generator.writeStringField(attr.getName(), "Exception: " + ex.toString());
                }
            }

            generator.writeEndObject();
            generator.writeEndObject();
            writer.writeLn("");
        }

        generator.writeEndArray();
        generator.writeEndObject();
    } finally {
        writer.markEndOfFile();
    }
}

From source file:architecture.ee.web.spring.controller.SecureMoSKitoController.java

private List<URL> getClassPathUrlsForTomcat(final String context, final String contextPropertyName) {
    List<MBeanServer> servers = MBeanServerFactory.findMBeanServer(null);
    for (MBeanServer s : servers) {
        Set<ObjectInstance> instances = s.queryMBeans(null, new QueryExp() {

            public boolean apply(ObjectName name) throws BadStringOperationException,
                    BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException {
                String type = name.getKeyProperty("type");
                log.debug(name.getDomain() + " : " + name.getKeyPropertyList());
                if (!type.equals("WebappClassLoader"))
                    return false;
                if (!name.getDomain().equals("Catalina"))
                    return false;
                if (!name.getKeyProperty(contextPropertyName).equals(context))
                    return false;
                return true;
            }//from www. ja  va2  s. co m

            public void setMBeanServer(MBeanServer s) {
            }
        });
        if (instances.size() > 0) {
            try {
                URL[] urls = (URL[]) s.getAttribute(instances.iterator().next().getObjectName(), "URLs");
                return Arrays.asList(urls);
            } catch (Exception e) {
            }

        }
    }
    return null;
}

From source file:org.camelcookbook.monitoring.managed.ManagedSpringTest.java

@Test
public void testManagedResource() throws Exception {
    final ManagementAgent managementAgent = context.getManagementStrategy().getManagementAgent();
    assertNotNull(managementAgent);//from  w  w  w  .j a v a  2s .  co  m

    final MBeanServer mBeanServer = managementAgent.getMBeanServer();
    assertNotNull(mBeanServer);

    final String mBeanServerDefaultDomain = managementAgent.getMBeanServerDefaultDomain();
    assertEquals("org.apache.camel", mBeanServerDefaultDomain);

    final String managementName = context.getManagementName();
    assertNotNull("CamelContext should have a management name if JMX is enabled", managementName);
    LOG.info("managementName = {}", managementName);

    // Get the Camel Context MBean
    ObjectName onContext = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/"
            + managementName + ",type=context,name=\"" + context.getName() + "\"");

    assertTrue("Should be registered", mBeanServer.isRegistered(onContext));

    // Get myManagedBean
    ObjectName onManagedBean = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/"
            + managementName + ",type=processors,name=\"myManagedBean\"");
    LOG.info("Canonical Name = {}", onManagedBean.getCanonicalName());
    assertTrue("Should be registered", mBeanServer.isRegistered(onManagedBean));

    // Send a couple of messages to get some route statistics
    template.sendBody("direct:start", "Hello Camel");
    template.sendBody("direct:start", "Camel Rocks!");

    // Get MBean attribute
    int camelsSeenCount = (Integer) mBeanServer.getAttribute(onManagedBean, "CamelsSeenCount");
    assertEquals(2, camelsSeenCount);

    // Stop the route via JMX
    mBeanServer.invoke(onManagedBean, "resetCamelsSeenCount", null, null);

    camelsSeenCount = (Integer) mBeanServer.getAttribute(onManagedBean, "CamelsSeenCount");
    assertEquals(0, camelsSeenCount);
}

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/*w  w  w.jav a 2 s  .com*/
 *            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:org.camelcookbook.monitoring.naming.JmxNamingContextSpringTest.java

@Test
public void testNamingContextSpring() throws Exception {
    final ManagementAgent managementAgent = context.getManagementStrategy().getManagementAgent();
    assertNotNull(managementAgent);//from   w  w  w  .  ja  v  a2s . co m

    final MBeanServer mBeanServer = managementAgent.getMBeanServer();
    assertNotNull(mBeanServer);

    final String mBeanServerDefaultDomain = managementAgent.getMBeanServerDefaultDomain();
    assertEquals("org.apache.camel", mBeanServerDefaultDomain);

    final String managementName = context.getManagementName();
    assertNotNull("CamelContext should have a management name if JMX is enabled", managementName);
    LOG.info("managementName = {}", managementName);

    // Get the Camel Context MBean
    ObjectName onContext = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/"
            + managementName + ",type=context,name=\"" + context.getName() + "\"");
    assertTrue("Should be registered", mBeanServer.isRegistered(onContext));

    // Get the first Route MBean by id
    ObjectName onRoute1 = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/"
            + managementName + ",type=routes,name=\"first-route\"");
    LOG.info("Canonical Name = {}", onRoute1.getCanonicalName());
    assertTrue("Should be registered", mBeanServer.isRegistered(onRoute1));

    // Send a couple of messages to get some route statistics
    template.sendBody("direct:start", "Hello Camel");
    template.sendBody("direct:start", "Camel Rocks!");

    // Get an MBean attribute for the number of messages processed
    assertEquals(2L, mBeanServer.getAttribute(onRoute1, "ExchangesCompleted"));

    // Get the other Route MBean by id
    ObjectName onRoute2 = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/"
            + managementName + ",type=routes,name=\"other-route\"");
    assertTrue("Should be registered", mBeanServer.isRegistered(onRoute2));

    // Get an MBean attribute for the number of messages processed
    assertEquals(0L, mBeanServer.getAttribute(onRoute2, "ExchangesCompleted"));

    // Send some messages to the other route
    template.sendBody("direct:startOther", "Hello Other Camel");
    template.sendBody("direct:startOther", "Other Camel Rocks!");

    // Verify that the MBean statistics updated correctly
    assertEquals(2L, mBeanServer.getAttribute(onRoute2, "ExchangesCompleted"));

    // Check this routes running state
    assertEquals("Started", mBeanServer.getAttribute(onRoute2, "State"));

    // Stop the route via JMX
    mBeanServer.invoke(onRoute2, "stop", null, null);

    // verify the route now shows its state as stopped
    assertEquals("Stopped", mBeanServer.getAttribute(onRoute2, "State"));
}

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

@SuppressWarnings({ "unchecked" })
@Test/* ww w.  j  a  v a 2s  . c  om*/
public void testLastContactTime() throws Exception {
    Configuration conf = new Configuration();
    conf.setInt(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1);
    conf.setInt(DFSConfigKeys.DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY, 1);
    MiniDFSCluster cluster = null;
    FileSystem localFileSys = null;
    Path dir = null;

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

        FSNamesystem fsn = cluster.getNameNode().namesystem;

        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName mxbeanName = new ObjectName("Hadoop:service=NameNode,name=NameNodeInfo");

        // Define include file to generate deadNodes metrics
        localFileSys = FileSystem.getLocal(conf);
        Path workingDir = localFileSys.getWorkingDirectory();
        dir = new Path(workingDir, "build/test/data/temp/TestNameNodeMXBean");
        Path includeFile = new Path(dir, "include");
        assertTrue(localFileSys.mkdirs(dir));
        StringBuilder includeHosts = new StringBuilder();
        for (DataNode dn : cluster.getDataNodes()) {
            includeHosts.append(dn.getDisplayName()).append("\n");
        }
        DFSTestUtil.writeFile(localFileSys, includeFile, includeHosts.toString());
        conf.set(DFSConfigKeys.DFS_HOSTS, includeFile.toUri().getPath());
        fsn.getBlockManager().getDatanodeManager().refreshNodes(conf);

        cluster.stopDataNode(0);
        while (fsn.getBlockManager().getDatanodeManager().getNumLiveDataNodes() != 2) {
            Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
        }

        // get attribute deadnodeinfo
        String deadnodeinfo = (String) (mbs.getAttribute(mxbeanName, "DeadNodes"));
        assertEquals(fsn.getDeadNodes(), deadnodeinfo);
        Map<String, Map<String, Object>> deadNodes = (Map<String, Map<String, Object>>) JSON
                .parse(deadnodeinfo);
        assertTrue(deadNodes.size() > 0);
        for (Map<String, Object> deadNode : deadNodes.values()) {
            assertTrue(deadNode.containsKey("lastContact"));
            assertTrue(deadNode.containsKey("decommissioned"));
            assertTrue(deadNode.containsKey("xferaddr"));
        }
    } finally {
        if ((localFileSys != null) && localFileSys.exists(dir)) {
            FileUtils.deleteQuietly(new File(dir.toUri().getPath()));
        }
        if (cluster != null) {
            cluster.shutdown();
        }
    }
}

From source file:org.camelcookbook.monitoring.naming.JmxNamingPatternSpringTest.java

@Test
public void testNamingPatternSpring() throws Exception {
    final ManagementAgent managementAgent = context.getManagementStrategy().getManagementAgent();
    assertNotNull(managementAgent);//from www .j a  v a  2s .  c  o m

    final MBeanServer mBeanServer = managementAgent.getMBeanServer();
    assertNotNull(mBeanServer);

    final String mBeanServerDefaultDomain = managementAgent.getMBeanServerDefaultDomain();
    assertEquals("org.apache.camel", mBeanServerDefaultDomain);

    final String managementName = context.getManagementName();
    assertNotNull("CamelContext should have a management name if JMX is enabled", managementName);
    LOG.info("managementName = {}; name = {}", managementName, context.getName());
    assertTrue(managementName.startsWith("CustomName"));

    // Get the Camel Context MBean
    ObjectName onContext = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/"
            + managementName + ",type=context,name=\"" + context.getName() + "\"");
    assertTrue("Should be registered", mBeanServer.isRegistered(onContext));

    // Get the first Route MBean by id
    ObjectName onRoute1 = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/"
            + managementName + ",type=routes,name=\"first-route\"");
    LOG.info("Canonical Name = {}", onRoute1.getCanonicalName());
    assertTrue("Should be registered", mBeanServer.isRegistered(onRoute1));

    // Send a couple of messages to get some route statistics
    template.sendBody("direct:start", "Hello Camel");
    template.sendBody("direct:start", "Camel Rocks!");

    // Get an MBean attribute for the number of messages processed
    assertEquals(2L, mBeanServer.getAttribute(onRoute1, "ExchangesCompleted"));

    // Get the other Route MBean by id
    ObjectName onRoute2 = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/"
            + managementName + ",type=routes,name=\"other-route\"");
    assertTrue("Should be registered", mBeanServer.isRegistered(onRoute2));

    // Get an MBean attribute for the number of messages processed
    assertEquals(0L, mBeanServer.getAttribute(onRoute2, "ExchangesCompleted"));

    // Send some messages to the other route
    template.sendBody("direct:startOther", "Hello Other Camel");
    template.sendBody("direct:startOther", "Other Camel Rocks!");

    // Verify that the MBean statistics updated correctly
    assertEquals(2L, mBeanServer.getAttribute(onRoute2, "ExchangesCompleted"));

    // Check this routes running state
    assertEquals("Started", mBeanServer.getAttribute(onRoute2, "State"));

    // Stop the route via JMX
    mBeanServer.invoke(onRoute2, "stop", null, null);

    // verify the route now shows its state as stopped
    assertEquals("Stopped", mBeanServer.getAttribute(onRoute2, "State"));
}