Java Code Examples for javax.management.MBeanServer#queryNames()

The following examples show how to use javax.management.MBeanServer#queryNames() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RepositoryWildcardTest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
private static int mbeanQuery(MBeanServer mbs,
                              String name,
                              Set<ObjectName> expectedSet)
    throws Exception {
    int error = 0;
    System.out.println("Test: queryNames(" + name + ")");
    Set<ObjectName> returnedSet =
            mbs.queryNames(ObjectName.getInstance(name), null);
    System.out.println("ReturnedSet = " + new TreeSet(returnedSet));
    System.out.println("ExpectedSet = " + new TreeSet(expectedSet));
    if (returnedSet.equals(expectedSet)) {
        System.out.println("Test passed!");
    } else {
        error++;
        System.out.println("Test failed!");
    }
    return error;
}
 
Example 2
Source File: FlumePersistentPerf.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@After
public void teardown() throws Exception {
    System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
    ctx.reconfigure();
    primary.stop();
    alternate.stop();
    final File file = new File("target/file-channel");
    deleteFiles(file);
    final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    final Set<ObjectName> names = server.queryNames(new ObjectName("org.apache.flume.*:*"), null);
    for (final ObjectName name : names) {
        try {
            server.unregisterMBean(name);
        } catch (final Exception ex) {
            System.out.println("Unable to unregister " + name.toString());
        }
    }
}
 
Example 3
Source File: RepositoryWildcardTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static int mbeanQuery(MBeanServer mbs,
                              String name,
                              Set<ObjectName> expectedSet)
    throws Exception {
    int error = 0;
    System.out.println("Test: queryNames(" + name + ")");
    Set<ObjectName> returnedSet =
            mbs.queryNames(ObjectName.getInstance(name), null);
    System.out.println("ReturnedSet = " + new TreeSet(returnedSet));
    System.out.println("ExpectedSet = " + new TreeSet(expectedSet));
    if (returnedSet.equals(expectedSet)) {
        System.out.println("Test passed!");
    } else {
        error++;
        System.out.println("Test failed!");
    }
    return error;
}
 
Example 4
Source File: RepositoryWildcardTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static int mbeanQuery(MBeanServer mbs,
                              String name,
                              Set<ObjectName> expectedSet)
    throws Exception {
    int error = 0;
    System.out.println("Test: queryNames(" + name + ")");
    Set<ObjectName> returnedSet =
            mbs.queryNames(ObjectName.getInstance(name), null);
    System.out.println("ReturnedSet = " + new TreeSet(returnedSet));
    System.out.println("ExpectedSet = " + new TreeSet(expectedSet));
    if (returnedSet.equals(expectedSet)) {
        System.out.println("Test passed!");
    } else {
        error++;
        System.out.println("Test failed!");
    }
    return error;
}
 
Example 5
Source File: ManagementUtil.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public static boolean checkLocalMemberMBean(){
  MBeanServer server = ManagementFactory.getPlatformMBeanServer();
  try {      
    Set<ObjectName> objectNames = server.queryNames(null, null);
    logFine("Mbean Set registered at platform mbean server : " + objectNames);      
    boolean flag = false;
    for(ObjectName n : objectNames){
      if(n.toString().contains(getLocalMemberMBean())){
        flag = true;
        logFine("Found Member MBean " + n + " in gemfire mbean set");
        break;
      }
    }      
    return flag;
  } finally{      
  }    
}
 
Example 6
Source File: BaseTool.java    From zooadmin with MIT License 6 votes vote down vote up
public static String getServer() {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    ArrayList<String> endPoints = new ArrayList<String>();
    try {
        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);
        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);
            }
        }
    } catch (Exception e) {
        return "";
    }
    if (endPoints.size() > 0) {
        return endPoints.get(0);
    } else {
        return "";
    }
}
 
Example 7
Source File: RepositoryWildcardTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static int mbeanQuery(MBeanServer mbs,
                              String name,
                              Set<ObjectName> expectedSet)
    throws Exception {
    int error = 0;
    System.out.println("Test: queryNames(" + name + ")");
    Set<ObjectName> returnedSet =
            mbs.queryNames(ObjectName.getInstance(name), null);
    System.out.println("ReturnedSet = " + new TreeSet(returnedSet));
    System.out.println("ExpectedSet = " + new TreeSet(expectedSet));
    if (returnedSet.equals(expectedSet)) {
        System.out.println("Test passed!");
    } else {
        error++;
        System.out.println("Test failed!");
    }
    return error;
}
 
Example 8
Source File: RepositoryWildcardTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static int mbeanQuery(MBeanServer mbs,
                              String name,
                              Set<ObjectName> expectedSet)
    throws Exception {
    int error = 0;
    System.out.println("Test: queryNames(" + name + ")");
    Set<ObjectName> returnedSet =
            mbs.queryNames(ObjectName.getInstance(name), null);
    System.out.println("ReturnedSet = " + new TreeSet(returnedSet));
    System.out.println("ExpectedSet = " + new TreeSet(expectedSet));
    if (returnedSet.equals(expectedSet)) {
        System.out.println("Test passed!");
    } else {
        error++;
        System.out.println("Test failed!");
    }
    return error;
}
 
Example 9
Source File: MbeanCommand.java    From LagMonitor with MIT License 6 votes vote down vote up
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
    String lastArg = args[args.length - 1];

    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();

    Stream<String> result = Stream.empty();
    if (args.length == 1) {
        Set<ObjectName> mbeans = mBeanServer.queryNames(null, null);
        result = mbeans.stream()
                .map(ObjectName::getCanonicalName)
                .filter(name -> name.startsWith(lastArg));
    } else if (args.length == 2) {
        try {
            ObjectName beanObject = ObjectName.getInstance(args[0]);
            result = Arrays.stream(mBeanServer.getMBeanInfo(beanObject).getAttributes())
                    .map(MBeanAttributeInfo::getName)
                    //ignore the object name - it's already known if the user invoke the command
                    .filter(attribute -> !"ObjectName".equals(attribute));
        } catch (Exception ex) {
            plugin.getLogger().log(Level.SEVERE, null, ex);
        }
    }

    return result.sorted(String.CASE_INSENSITIVE_ORDER).collect(toList());
}
 
Example 10
Source File: ServerManagement.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Wait till all service requests have been serviced. This method will only wait for a maximum
 * of {@link ServerManagement#TIMEOUT}
 *
 * @throws Exception If an error occurs while trying to connect to the Tomcat MBean
 */
public void waitForRequestCompletion() throws Exception {
    SecurityManager secMan = System.getSecurityManager();
    if (secMan != null) {
        secMan.checkPermission(new ManagementPermission("control"));
    }
    log.info("Waiting for request service completion...");
    /**
     * Get all MBeans with names such as Catalina:type=RequestProcessor,worker=http-9762,name=HttpRequest<n>
     * & Catalina:type=RequestProcessor,worker=http-9762,name=HttpsRequest<n>
     */
    MBeanServer mbs = MbeanManagementFactory.getMBeanServer();
    boolean areRequestsInService;
    long start = System.currentTimeMillis();
    do {
        // Check whether there are any processors which are currently in the SERVICE stage (3)
        QueryExp query = Query.eq(Query.attr("stage"), Query.value(3));  // 3 = org.apache.coyote.Constants.STAGE_SERVICE
        Set set = mbs.queryNames(new ObjectName("Catalina:type=RequestProcessor,*"), query);
        if (set.size() > 0) {
            areRequestsInService = true;
            if (System.currentTimeMillis() - start > TIMEOUT) {
                log.warn("Timeout occurred even though there are active connections.");
                break;
            }
            Thread.sleep(2000);
        } else {
            areRequestsInService = false;
        }
    } while (areRequestsInService);
    log.info("All requests have been served.");
}
 
Example 11
Source File: AvoidGetMBeanInfoCallsTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Standalone entry point.
 *
 * Run the test and report to stdout.
 */
public static void main(String args[]) throws Exception {

    echo(">>> Create MBeanServer");
    MBeanServer server = MBeanServerFactory.newMBeanServer();

    echo(">>> Default Domain: " + server.getDefaultDomain());

    echo(">>> Create and register Test MBean");
    Test mbean = new Test();
    ObjectName name = ObjectName.getInstance(":type=Test");
    server.registerMBean(mbean, name);

    echo(">>> Set entered flag to false in Test MBean");
    mbean.entered = false;

    echo(">>> Query Names:");
    Set<ObjectName> names = server.queryNames(null, null);
    for (ObjectName on : names) {
        echo("\t" + on.toString());
    }

    echo(">>> Entered flag = " + mbean.entered);

    if (mbean.entered) {
        echo(">>> Test FAILED!");
        throw new IllegalArgumentException("getMBeanInfo got called");
    } else {
        echo(">>> Test PASSED!");
    }
}
 
Example 12
Source File: ContextLoaderListener.java    From oneplatform with Apache License 2.0 5 votes vote down vote up
private static  int getServerPort(){
    int port = 0;
    try {
        MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
        Set<ObjectName> objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"),
                Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));

        port = Integer.valueOf(objectNames.iterator().next().getKeyProperty("port"));
    }catch (Exception e){
    	if(StringUtils.isNotBlank(System.getProperty("jetty.port"))){
    		port = Integer.parseInt(System.getProperty("jetty.port"));
    	}
    }
    return port;
}
 
Example 13
Source File: SimpleManagementTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testAllGood() throws Exception {

    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    Set<ObjectName> onames;
    
    try (CamelContext camelctx = new DefaultCamelContext()) {
    	
        camelctx.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start").transform(body().prepend("Hello "));
            }
        });

        onames = server.queryNames(new ObjectName("org.apache.camel:*"), null);
        Assert.assertEquals(Collections.emptySet(), onames);

        camelctx.start();

        onames = server.queryNames(new ObjectName("org.apache.camel:*"), null);
        Assert.assertTrue(onames.size() > 0);

        ProducerTemplate producer = camelctx.createProducerTemplate();
        String result = producer.requestBody("direct:start", "Kermit", String.class);
        Assert.assertEquals("Hello Kermit", result);
    }

    onames = server.queryNames(new ObjectName("org.apache.camel:*"), null);
    Assert.assertEquals(Collections.emptySet(), onames);
}
 
Example 14
Source File: PlatformMBeanServerTest.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
private static void printMBeans(MBeanServer mbs) throws Exception {
    Set set = mbs.queryNames(null, null);
    for (Iterator iter = set.iterator(); iter.hasNext(); ) {
        System.out.println(iter.next());
    }
}
 
Example 15
Source File: PlatformMBeanServerTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private static void printMBeans(MBeanServer mbs) throws Exception {
    Set set = mbs.queryNames(null, null);
    for (Iterator iter = set.iterator(); iter.hasNext(); ) {
        System.out.println(iter.next());
    }
}
 
Example 16
Source File: Basic.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    Random rand = new Random();

    // allocate a few direct buffers
    int bufferCount = 5 + rand.nextInt(20);
    buffers = new ArrayList<ByteBuffer>(bufferCount);
    long totalCapacity = 0L;
    for (int i=0; i<bufferCount; i++) {
        int cap = 1024 + rand.nextInt(4096);
        buffers.add( ByteBuffer.allocateDirect(cap) );
        totalCapacity += cap;
    }

    // create a mapped buffer
    Path tmpfile = Files.createTempFile("blah", null);
    tmpfile.toFile().deleteOnExit();
    try (FileChannel fc = FileChannel.open(tmpfile, READ, WRITE)) {
        mbb = fc.map(FileChannel.MapMode.READ_WRITE, 10, 100);
        bufferCount++;
        totalCapacity += mbb.capacity();
    }

    // use platform MXBeans directly
    List<BufferPoolMXBean> pools =
        ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
    check(pools, bufferCount, totalCapacity);

    // use MBeanServer
    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    Set<ObjectName> mbeans = server.queryNames(
        new ObjectName("java.nio:type=BufferPool,*"), null);
    pools = new ArrayList<BufferPoolMXBean>();
    for (ObjectName name: mbeans) {
        BufferPoolMXBean pool = ManagementFactory
            .newPlatformMXBeanProxy(server, name.toString(), BufferPoolMXBean.class);
        pools.add(pool);
    }
    check(pools, bufferCount, totalCapacity);

    // attempt to unmap mapped buffer
    WeakReference<MappedByteBuffer> ref = new WeakReference<>(mbb);
    mbb = null;
    do {
        System.gc();
        Thread.sleep(250);
    } while (ref.get() != null);
}
 
Example 17
Source File: JMXJobManagerMetricTest.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that metrics registered on the JobManager are actually accessible via JMX.
 */
@Test
public void testJobManagerJMXMetricAccess() throws Exception {
	Deadline deadline = Deadline.now().plus(Duration.ofMinutes(2));

	try {
		JobVertex sourceJobVertex = new JobVertex("Source");
		sourceJobVertex.setInvokableClass(BlockingInvokable.class);

		JobGraph jobGraph = new JobGraph("TestingJob", sourceJobVertex);
		jobGraph.setSnapshotSettings(new JobCheckpointingSettings(
			Collections.<JobVertexID>emptyList(),
			Collections.<JobVertexID>emptyList(),
			Collections.<JobVertexID>emptyList(),
			new CheckpointCoordinatorConfiguration(
				500,
				500,
				50,
				5,
				CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION,
				true,
				false,
				0),
			null));

		ClusterClient<?> client = MINI_CLUSTER_RESOURCE.getClusterClient();
		client.setDetached(true);
		client.submitJob(jobGraph, JMXJobManagerMetricTest.class.getClassLoader());

		FutureUtils.retrySuccessfulWithDelay(
			() -> client.getJobStatus(jobGraph.getJobID()),
			Time.milliseconds(10),
			deadline,
			status -> status == JobStatus.RUNNING,
			TestingUtils.defaultScheduledExecutor()
		).get(deadline.timeLeft().toMillis(), TimeUnit.MILLISECONDS);

		MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
		Set<ObjectName> nameSet = mBeanServer.queryNames(new ObjectName("org.apache.flink.jobmanager.job.lastCheckpointSize:job_name=TestingJob,*"), null);
		Assert.assertEquals(1, nameSet.size());
		assertEquals(-1L, mBeanServer.getAttribute(nameSet.iterator().next(), "Value"));

		BlockingInvokable.unblock();
	} finally {
		BlockingInvokable.unblock();
	}
}
 
Example 18
Source File: JMXJobManagerMetricTest.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that metrics registered on the JobManager are actually accessible via JMX.
 */
@Test
public void testJobManagerJMXMetricAccess() throws Exception {
	Deadline deadline = Deadline.now().plus(Duration.ofMinutes(2));

	try {
		JobVertex sourceJobVertex = new JobVertex("Source");
		sourceJobVertex.setInvokableClass(BlockingInvokable.class);

		JobGraph jobGraph = new JobGraph("TestingJob", sourceJobVertex);
		jobGraph.setSnapshotSettings(new JobCheckpointingSettings(
			Collections.<JobVertexID>emptyList(),
			Collections.<JobVertexID>emptyList(),
			Collections.<JobVertexID>emptyList(),
			new CheckpointCoordinatorConfiguration(
				500,
				500,
				50,
				5,
				CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION,
				true,
				false,
				false,
				0),
			null));

		ClusterClient<?> client = MINI_CLUSTER_RESOURCE.getClusterClient();
		ClientUtils.submitJob(client, jobGraph);

		FutureUtils.retrySuccessfulWithDelay(
			() -> client.getJobStatus(jobGraph.getJobID()),
			Time.milliseconds(10),
			deadline,
			status -> status == JobStatus.RUNNING,
			TestingUtils.defaultScheduledExecutor()
		).get(deadline.timeLeft().toMillis(), TimeUnit.MILLISECONDS);

		MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
		Set<ObjectName> nameSet = mBeanServer.queryNames(new ObjectName("org.apache.flink.jobmanager.job.lastCheckpointSize:job_name=TestingJob,*"), null);
		Assert.assertEquals(1, nameSet.size());
		assertEquals(-1L, mBeanServer.getAttribute(nameSet.iterator().next(), "Value"));

		BlockingInvokable.unblock();
	} finally {
		BlockingInvokable.unblock();
	}
}
 
Example 19
Source File: LocalProcessControllerJUnitTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void testProcessMBean() throws Exception {
    final String testName = "testProcessMBean";
    final int pid = ProcessUtils.identifyPid();
    final Process process = new Process(pid, true);
    final ObjectName objectName = ObjectName.getInstance(
        getClass().getSimpleName() + ":testName=" + testName);
    final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    final ObjectInstance instance = server.registerMBean(process, objectName);
    assertNotNull(instance);
    try {
      // validate basics of the ProcessMBean
      Set<ObjectName> mbeanNames = server.queryNames(objectName, null);
      assertFalse("Zero matching mbeans", mbeanNames.isEmpty());
      assertEquals(1, mbeanNames.size());
      final ObjectName name = mbeanNames.iterator().next();
      
      final MBeanInfo info = server.getMBeanInfo(name);
      
      final MBeanOperationInfo[] operInfo = info.getOperations();
      assertEquals(1, operInfo.length);
      assertEquals("stop", operInfo[0].getName());
      
      final MBeanAttributeInfo[] attrInfo = info.getAttributes();
      assertEquals(2, attrInfo.length);
      // The order of these attributes is indeterminate
//      assertEquals("Pid", attrInfo[0].getName());
//      assertEquals("Process", attrInfo[1].getName());
      assertNotNull(server.getAttribute(name, "Pid"));
      assertNotNull(server.getAttribute(name, "Process"));
      
      assertEquals(pid, server.getAttribute(name, "Pid"));
      assertEquals(true, server.getAttribute(name, "Process"));

      // validate query using only Pid attribute
      QueryExp constraint = Query.eq(
          Query.attr("Pid"),
          Query.value(pid));
      mbeanNames = server.queryNames(objectName, constraint);
      assertFalse("Zero matching mbeans", mbeanNames.isEmpty());
      
      // validate query with wrong Pid finds nothing
      constraint = Query.eq(
          Query.attr("Pid"),
          Query.value(pid+1));
      mbeanNames = server.queryNames(objectName, constraint);
      assertTrue("Found matching mbeans", mbeanNames.isEmpty());
      
      // validate query using both attributes
      constraint = Query.and(
          Query.eq(Query.attr("Process"),Query.value(true)),
          Query.eq(Query.attr("Pid"),Query.value(pid)));
      mbeanNames = server.queryNames(objectName, constraint);
      assertFalse("Zero matching mbeans", mbeanNames.isEmpty());
      
      // validate query with wrong attribute finds nothing
      constraint = Query.and(
          Query.eq(Query.attr("Process"),Query.value(false)),
          Query.eq(Query.attr("Pid"),Query.value(pid)));
      mbeanNames = server.queryNames(objectName, constraint);
      assertTrue("Found matching mbeans", mbeanNames.isEmpty());
      
    } finally {
      try {
        server.unregisterMBean(objectName);
      } catch (Throwable t) {
        t.printStackTrace();
      }
    }
  }
 
Example 20
Source File: PlatformMBeanServerTest.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
private static void printMBeans(MBeanServer mbs) throws Exception {
    Set set = mbs.queryNames(null, null);
    for (Iterator iter = set.iterator(); iter.hasNext(); ) {
        System.out.println(iter.next());
    }
}