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.jmxtrans.embedded.util.pool.ManagedGenericKeyedObjectPoolTest.java

@Test
public void testMbeanAttributeAccess() throws Exception {
    BaseKeyedPooledObjectFactory<String, String> factory = new BaseKeyedPooledObjectFactory<String, String>() {
        @Override//from w  w w  .  j  a  va  2  s .c  om
        public String create(String key) throws Exception {
            return key;
        }

        @Override
        public PooledObject<String> wrap(String value) {
            return new DefaultPooledObject<String>(value);
        }
    };
    GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig();
    config.setJmxNameBase("org.jmxtrans.embedded:type=GenericKeyedObjectPool,writer=MyWriter,name=");
    config.setJmxNamePrefix("my-host_1234");
    GenericKeyedObjectPool<String, String> objectPool = new GenericKeyedObjectPool<String, String>(factory,
            config);

    ObjectName objectName = new ObjectName(
            "org.jmxtrans.embedded:type=GenericKeyedObjectPool,writer=MyWriter,name=my-host_1234");
    MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        Object numIdle = mbeanServer.getAttribute(objectName, "NumIdle");
        assertThat(numIdle, instanceOf(Number.class));

    } finally {
        mbeanServer.unregisterMBean(objectName);
    }
}

From source file:com.beginner.core.utils.ProjectUtil.java

/**
 * ?Web???(???)//from   ww  w.  j  ava  2  s  . c o  m
 */
public static String getPort() {
    String result = "";
    try {
        MBeanServer mBeanServer = null;
        List<MBeanServer> mBeanServers = MBeanServerFactory.findMBeanServer(null);
        if (mBeanServers.size() > 0) {
            for (MBeanServer _mBeanServer : mBeanServers) {
                mBeanServer = _mBeanServer;
                break;
            }
        }
        if (mBeanServer == null) {
            throw new IllegalStateException("?JVM?MBeanServer.");
        }
        Set<ObjectName> objectNames = null;
        objectNames = mBeanServer.queryNames(new ObjectName("Catalina:type=Connector,*"), null);
        if (objectNames == null || objectNames.size() <= 0) {
            throw new IllegalStateException("?JVM?MBeanServer : "
                    + mBeanServer.getDefaultDomain() + " ??.");
        }
        for (ObjectName objectName : objectNames) {
            String protocol = (String) mBeanServer.getAttribute(objectName, "protocol");
            if (protocol.equals("HTTP/1.1")) {
                int port = (Integer) mBeanServer.getAttribute(objectName, "port");
                result = port + StringUtils.EMPTY;
            }
        }
    } catch (Exception e) {
        logger.error("?WEB?HTTP/1.1???", e);
    }
    return result;
}

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. j a  v a2  s. c om
        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:com.atolcd.alfresco.audit.web.scripts.FileServerInfoGet.java

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

    try {// ww w . ja  va  2s .  com

        ObjectName fscName = new ObjectName("Alfresco:Name=FileServerConfig");
        MBeanServer mbs = getMBeanServer(fscName);

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

        model.put("cifs_enabled", mbs.getAttribute(fscName, "CIFSServerEnabled"));
        model.put("cifs_name", mbs.getAttribute(fscName, "CIFSServerName"));
        model.put("cifs_address", mbs.getAttribute(fscName, "CIFSServerAddress"));
        model.put("ftp_enabled", mbs.getAttribute(fscName, "FTPServerEnabled"));
        model.put("nfs_enabled", mbs.getAttribute(fscName, "NFSServerEnabled"));

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

From source file:org.jolokia.jmx.JolokiaMBeanServerTest.java

@Test
public void simple() throws NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanException,
        MalformedObjectNameException, AttributeNotFoundException, ReflectionException,
        InstanceNotFoundException, ParseException, InvalidTargetObjectTypeException, NoSuchMethodException,
        IntrospectionException {/*from w  w  w  .  j  a  v a 2s.  c o  m*/
    JolokiaMBeanServer server = new JolokiaMBeanServer();

    ObjectName oName = new ObjectName("test:type=jsonMBean");
    server.registerMBean(new JsonAnnoTest(), oName);

    CompositeData chiliCD = (CompositeData) server.getAttribute(oName, "Chili");
    assertEquals((String) chiliCD.get("name"), "Bhut Jolokia");
    assertEquals(chiliCD.get("scoville"), 1000000L);

    MBeanServer pServer = ManagementFactory.getPlatformMBeanServer();
    String chiliS = (String) pServer.getAttribute(oName, "Chili");
    JSONObject chiliJ = (JSONObject) new JSONParser().parse(chiliS);
    assertEquals(chiliJ.get("name"), "Bhut Jolokia");
    assertEquals(chiliJ.get("scoville"), 1000000L);

    server.unregisterMBean(oName);
    Assert.assertFalse(pServer.isRegistered(oName));
    Assert.assertFalse(server.isRegistered(oName));
}

From source file:org.apache.hadoop.hdfs.server.datanode.TestDataNodeMXBean.java

@SuppressWarnings("unchecked")
private int getTotalNumBlocks(MBeanServer mbs, ObjectName mxbeanName) throws Exception {
    int totalBlocks = 0;
    String volumeInfo = (String) mbs.getAttribute(mxbeanName, "VolumeInfo");
    Map<?, ?> m = (Map<?, ?>) JSON.parse(volumeInfo);
    Collection<Map<String, Long>> values = (Collection<Map<String, Long>>) m.values();
    for (Map<String, Long> volumeInfoMap : values) {
        totalBlocks += volumeInfoMap.get("numBlocks");
    }/*from w ww  .  jav a  2  s .c o m*/
    return totalBlocks;
}

From source file:org.jolokia.jmx.JolokiaMBeanServerTest.java

@Test
public void withConstraint()
        throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException,
        MBeanException, AttributeNotFoundException, ReflectionException, InstanceNotFoundException,
        ParseException, InvalidTargetObjectTypeException, NoSuchMethodException, IntrospectionException {
    JolokiaMBeanServer server = new JolokiaMBeanServer();

    ObjectName oName = new ObjectName("test:type=jsonMBean");

    server.registerMBean(new JsonAnnoPlainTest(), oName);

    MBeanServer plattformServer = ManagementFactory.getPlatformMBeanServer();

    String deepDive = (String) plattformServer.getAttribute(oName, "DeepDive");
    JSONObject deepDiveS = (JSONObject) new JSONParser().parse(deepDive);
    assertEquals(deepDiveS.size(), 1);//  w w w .j  a  v a  2  s .  com
    // Serialization is truncated because of maxDepth = 1
    assertTrue(deepDiveS.get("map") instanceof String);
    assertTrue(deepDiveS.get("map").toString().matches(".*hot=.*Chili.*"));
    server.unregisterMBean(oName);
    Assert.assertFalse(plattformServer.isRegistered(oName));
    Assert.assertFalse(server.isRegistered(oName));
}

From source file:org.apache.geode.management.internal.web.controllers.ShellCommandsController.java

@RequestMapping(method = RequestMethod.GET, value = "/mbean/attribute")
public ResponseEntity<?> getAttribute(@RequestParam("resourceName") final String resourceName,
        @RequestParam("attributeName") final String attributeName)
        throws AttributeNotFoundException, MBeanException, ReflectionException, InstanceNotFoundException,
        IOException, MalformedObjectNameException {
    // Exceptions are caught by the @ExceptionHandler AbstractCommandsController.handleAppException
    MBeanServer mBeanServer = getMBeanServer();
    ObjectName objectName = ObjectName.getInstance(decode(resourceName));
    final Object attributeValue = mBeanServer.getAttribute(objectName, decode(attributeName));
    byte[] serializedResult = IOUtils.serializeObject(attributeValue);
    return new ResponseEntity<>(serializedResult, HttpStatus.OK);
}

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

@Test
public void test() throws Exception {
    Configuration conf = new Configuration();
    MiniDFSCluster cluster = null;//w  w w  .  j a  v a2 s .com

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

        FSNamesystem fsn = cluster.getNameNode().namesystem;

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

        Object pendingDeletionBlocks = mbs.getAttribute(mxbeanName, "PendingDeletionBlocks");
        assertNotNull(pendingDeletionBlocks);
        assertTrue(pendingDeletionBlocks instanceof Long);
    } finally {
        if (cluster != null) {
            cluster.shutdown();
        }
    }
}

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

@Test
public void testHostsIncludeForDeadCount() throws Exception {
    Configuration conf = getConf();
    // Configure an excludes file
    FileSystem localFileSys = FileSystem.getLocal(conf);
    Path workingDir = localFileSys.getWorkingDirectory();
    Path dir = new Path(workingDir, "build/test/data/temp/decommission");
    Path excludeFile = new Path(dir, "exclude");
    Path includeFile = new Path(dir, "include");
    assertTrue(localFileSys.mkdirs(dir));
    StringBuilder includeHosts = new StringBuilder();
    includeHosts.append("localhost:52").append("\n").append("127.0.0.1:7777").append("\n");
    DFSTestUtil.writeFile(localFileSys, excludeFile, "");
    DFSTestUtil.writeFile(localFileSys, includeFile, includeHosts.toString());
    conf.set(DFSConfigKeys.DFS_HOSTS_EXCLUDE, excludeFile.toUri().getPath());
    conf.set(DFSConfigKeys.DFS_HOSTS, includeFile.toUri().getPath());
    MiniDFSCluster cluster = null;/* www .j a v a  2s .  c o m*/
    try {
        cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0).build();
        final FSNamesystem ns = cluster.getNameNode().getNamesystem();
        assertTrue(ns.getNumDeadDataNodes() == 2);
        assertTrue(ns.getNumLiveDataNodes() == 0);
        // Testing using MBeans
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName mxbeanName = new ObjectName("Hadoop:service=NameNode,name=FSNamesystemState");
        String nodes = mbs.getAttribute(mxbeanName, "NumDeadDataNodes") + "";
        assertTrue((Integer) mbs.getAttribute(mxbeanName, "NumDeadDataNodes") == 2);
        assertTrue((Integer) mbs.getAttribute(mxbeanName, "NumLiveDataNodes") == 0);
    } finally {
        if (cluster != null) {
            cluster.shutdown();
        }
    }
}