Example usage for java.lang.management ManagementFactory getPlatformMBeanServer

List of usage examples for java.lang.management ManagementFactory getPlatformMBeanServer

Introduction

In this page you can find the example usage for java.lang.management ManagementFactory getPlatformMBeanServer.

Prototype

public static synchronized MBeanServer getPlatformMBeanServer() 

Source Link

Document

Returns the platform javax.management.MBeanServer MBeanServer .

Usage

From source file:org.lealone.cluster.gms.FailureDetector.java

public FailureDetector() {
    // Register this instance with JMX
    try {//from ww  w . j  ava  2  s .c o m
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        mbs.registerMBean(this, new ObjectName(Utils.getJmxObjectName("FailureDetector")));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.rackspacecloud.blueflood.cache.TtlCacheTest.java

@After
public void deregister() throws Exception {
    final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    final String name = String.format(TtlCache.class.getPackage().getName() + ":type=%s,scope=%s,name=Stats",
            TtlCache.class.getSimpleName(), "Test");
    final ObjectName nameObj = new ObjectName(name);
    mbs.unregisterMBean(nameObj);/*from www . java 2 s .  c  o m*/

    // involves a little unsafe knowledge of TtlCache internals.
    Metrics.defaultRegistry().removeMetric(TtlCache.class, "Load Errors", "Test");
    Metrics.defaultRegistry().removeMetric(TtlCache.class, "Http Errors", "Test");
}

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

@SuppressWarnings({ "unchecked" })
@Test/* ww w. j ava2  s .c  o  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:herddb.jdbc.MultipleDataSourcesSameJVMJMXTest.java

@Test
public void test() throws Exception {
    try (Server server = new Server(new ServerConfiguration(folder.newFolder().toPath()))) {
        server.start();/*w  w w  . ja v a2s.  c o  m*/
        server.waitForStandaloneBoot();
        try (HDBClient client = new HDBClient(new ClientConfiguration(folder.newFolder().toPath()));) {
            client.setClientSideMetadataProvider(new StaticClientSideMetadataProvider(server));
            try (BasicHerdDBDataSource dataSource = new BasicHerdDBDataSource(client);
                    BasicHerdDBDataSource dataSource_2 = new BasicHerdDBDataSource(client);
                    Connection con = dataSource.getConnection();
                    Connection con_2 = dataSource_2.getConnection();
                    Statement statement = con.createStatement();
                    Statement statement_2 = con.createStatement();) {
                statement.execute("CREATE TABLE mytable (key string primary key, name string)");

                assertEquals(1, statement.executeUpdate("INSERT INTO mytable (key,name) values('k1','name1')"));
                assertEquals(1,
                        statement_2.executeUpdate("INSERT INTO mytable (key,name) values('k2','name2')"));
                assertEquals(1, statement.executeUpdate("INSERT INTO mytable (key,name) values('k3','name3')"));

                try (ResultSet rs = statement
                        .executeQuery("SELECT * FROM mytable a" + " INNER JOIN mytable b ON 1=1")) {
                    int count = 0;
                    while (rs.next()) {
                        count++;
                    }
                    assertEquals(9, count);
                }
                MBeanServer jmxServer = ManagementFactory.getPlatformMBeanServer();

                Object attributeValue = jmxServer.getAttribute(
                        new ObjectName("org.apache.commons.pool2:type=GenericObjectPool,name=HerdDBClient"),
                        "BorrowedCount");
                assertEquals(1L, attributeValue);

                Object attributeValue2 = jmxServer.getAttribute(
                        new ObjectName("org.apache.commons.pool2:type=GenericObjectPool,name=HerdDBClient2"),
                        "BorrowedCount");
                assertEquals(1L, attributeValue2);

            }
        }
    }
}

From source file:org.bigmouth.nvwa.transport.DelegatedSender.java

@Override
protected void doInit() {
    Preconditions.checkNotNull(this.nextSender, "nextSender");

    sendExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {

        @Override/*from   ww w  . ja  v  a  2 s  .  co  m*/
        public Thread newThread(Runnable r) {
            return new Thread(r, threadName + "-" + idx.get());
        }
    });

    sendQueue = new LinkedBlockingQueue<Object>(pendingMessageCount);
    startupProcessor();

    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    if (null != senderMBeanName) {
        DelegatedSenderMBean acceptorMBean = new DelegatedSenderMBean(this);
        try {
            ObjectName acceptorName = new ObjectName(this.senderMBeanName);
            mBeanServer.registerMBean(acceptorMBean, acceptorName);
        } catch (MalformedObjectNameException e) {
            LOG.error("Unable DelegatedSender jmx register:", e);
        } catch (NullPointerException e) {
            LOG.error("Unable DelegatedSender jmx register:", e);
        } catch (InstanceAlreadyExistsException e) {
            LOG.error("Unable DelegatedSender jmx register:", e);
        } catch (MBeanRegistrationException e) {
            LOG.error("Unable DelegatedSender jmx register:", e);
        } catch (NotCompliantMBeanException e) {
            LOG.error("Unable MinaSender jmx register:", e);
        }
    }
}

From source file:org.apache.streams.util.ComponentUtils.java

/**
 * Removes all mbeans registered undered a specific domain.  Made specificly to clean up at unit tests
 * @param domain//from   w w  w  .  ja v  a2  s  .  c o  m
 */
public static void removeAllMBeansOfDomain(String domain) throws Exception {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    domain = domain.endsWith(":") ? domain : domain + ":";
    ObjectName objectName = new ObjectName(domain + "*");
    Set<ObjectName> mbeanNames = mbs.queryNames(objectName, null);
    for (ObjectName name : mbeanNames) {
        mbs.unregisterMBean(name);
    }
}

From source file:com.amazonaws.client.metrics.jmx.MBeans.java

/**
 * Returns the first registered MBean server, or the platform MBean server
 * if there is none./*w ww. jav  a2s.  c  o m*/
 */
public static MBeanServer getMBeanServer() {
    List<MBeanServer> servers = MBeanServerFactory.findMBeanServer(null);
    MBeanServer server = servers.size() > 0 ? servers.get(0) : ManagementFactory.getPlatformMBeanServer();
    return server;
}

From source file:com.obergner.hzserver.ServerInfo.java

/**
 * @throws IOException/*from   w w w.ja  va  2 s.  com*/
 * @throws MalformedURLException
 * @throws NullPointerException
 * @throws MalformedObjectNameException
 * @throws NotCompliantMBeanException
 * @throws MBeanRegistrationException
 * @throws InstanceAlreadyExistsException
 * 
 */
public ServerInfo()
        throws MalformedURLException, IOException, InstanceAlreadyExistsException, MBeanRegistrationException,
        NotCompliantMBeanException, MalformedObjectNameException, NullPointerException {
    this.serverManifest = loadServerManifest();
    this.objectName = new ObjectName(getClass().getPackage().getName() + ":name=ServerInfo");
    ManagementFactory.getPlatformMBeanServer().registerMBean(this, this.objectName);
}

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

/**
 * Returns a subset of mbeans defined by qry.
 * Modeled after {@link JSONBean#dumpRegionServerMetrics()}
 * Example: String qry= "java.lang:type=Memory"
 * @throws MalformedObjectNameException if json have bad format
 * @throws IOException ///from  w ww.  ja v a 2 s. co m
 * @return String representation of json array.
 */
public static String dumpBeanToString(String qry) throws MalformedObjectNameException, IOException {
    StringWriter sw = new StringWriter(1024 * 100); // Guess this size
    try (PrintWriter writer = new PrintWriter(sw)) {
        JSONBean dumper = new JSONBean();
        try (JSONBean.Writer jsonBeanWriter = dumper.open(writer)) {
            MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
            jsonBeanWriter.write(mbeanServer, new ObjectName(qry), null, false);
        }
    }
    sw.close();
    return sw.toString();
}