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

The following examples show how to use javax.management.MBeanServer#getAttribute() . 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: MetricsReportService.java    From kafka-monitor with Apache License 2.0 6 votes vote down vote up
private List<MbeanAttributeValue> getMBeanAttributeValues(String mbeanExpr, String attributeExpr) {
    List<MbeanAttributeValue> values = new ArrayList<>();
    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    try {
        Set<ObjectName> mbeanNames = server.queryNames(new ObjectName(mbeanExpr), null);
        for (ObjectName mbeanName : mbeanNames) {
            MBeanInfo mBeanInfo = server.getMBeanInfo(mbeanName);
            MBeanAttributeInfo[] attributeInfos = mBeanInfo.getAttributes();
            for (MBeanAttributeInfo attributeInfo : attributeInfos) {
                if (attributeInfo.getName().equals(attributeExpr) || attributeExpr.length() == 0 || attributeExpr.equals("*")) {
                    double value = (Double) server.getAttribute(mbeanName, attributeInfo.getName());
                    values.add(new MbeanAttributeValue(mbeanName.getCanonicalName(), attributeInfo.getName(), value));
                }
            }
        }
    } catch (Exception e) {
        logger.error("", e);
    }
    return values;
}
 
Example 2
Source File: HelloWorldExample.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void main(String[] args) throws Exception
{
   // Create an instance of MBeanServer
   MBeanServer server = MBeanServerFactory.createMBeanServer();

   // Create an ObjectName for the MBean
   ObjectName name = new ObjectName(":mbean=helloworld");

   // Create and register the MBean in the MBeanServer
   server.createMBean("mx4j.examples.mbeans.helloworld.HelloWorld", name, null);

   // Invoke a method on it
   server.invoke(name, "reloadConfiguration", new Object[0], new String[0]);

   // Invoke an attribute on it
   Integer times = (Integer)server.getAttribute(name, "HowManyTimes");

   System.out.println("The configuration was reloaded " + times + " times.");
}
 
Example 3
Source File: MBeanExporterTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testAutodetectLazyMBeans() throws Exception {
	ConfigurableApplicationContext ctx = load("autodetectLazyMBeans.xml");
	try {
		ctx.getBean("exporter");
		MBeanServer server = ctx.getBean("server", MBeanServer.class);

		ObjectName oname = ObjectNameManager.getInstance("spring:mbean=true");
		assertNotNull(server.getObjectInstance(oname));
		String name = (String) server.getAttribute(oname, "Name");
		assertEquals("Invalid name returned", "Rob Harrop", name);

		oname = ObjectNameManager.getInstance("spring:mbean=another");
		assertNotNull(server.getObjectInstance(oname));
		name = (String) server.getAttribute(oname, "Name");
		assertEquals("Invalid name returned", "Juergen Hoeller", name);
	}
	finally {
		ctx.close();
	}
}
 
Example 4
Source File: MBeanExporterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testAutodetectLazyMBeans() throws Exception {
	ConfigurableApplicationContext ctx = load("autodetectLazyMBeans.xml");
	try {
		ctx.getBean("exporter");
		MBeanServer server = ctx.getBean("server", MBeanServer.class);

		ObjectName oname = ObjectNameManager.getInstance("spring:mbean=true");
		assertNotNull(server.getObjectInstance(oname));
		String name = (String) server.getAttribute(oname, "Name");
		assertEquals("Invalid name returned", "Rob Harrop", name);

		oname = ObjectNameManager.getInstance("spring:mbean=another");
		assertNotNull(server.getObjectInstance(oname));
		name = (String) server.getAttribute(oname, "Name");
		assertEquals("Invalid name returned", "Juergen Hoeller", name);
	}
	finally {
		ctx.close();
	}
}
 
Example 5
Source File: AnnotationLazyInitMBeanTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void componentScan() throws Exception {
	ConfigurableApplicationContext ctx =
			new ClassPathXmlApplicationContext("org/springframework/jmx/export/annotation/componentScan.xml");
	try {
		MBeanServer server = (MBeanServer) ctx.getBean("server");
		ObjectName oname = ObjectNameManager.getInstance("bean:name=testBean4");
		assertNotNull(server.getObjectInstance(oname));
		String name = (String) server.getAttribute(oname, "Name");
		assertNull(name);
	}
	finally {
		ctx.close();
	}
}
 
Example 6
Source File: MXBeanTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void testMXBean(MBeanServer mbs, ObjectName on)
        throws Exception {
    MBeanInfo mbi = mbs.getMBeanInfo(on);
    MBeanAttributeInfo[] attrs = mbi.getAttributes();
    int nattrs = attrs.length;
    if (mbi.getAttributes().length != 1)
        failure("wrong number of attributes: " + attrs);
    else {
        MBeanAttributeInfo mbai = attrs[0];
        if (mbai.getName().equals("Ints")
            && mbai.isReadable() && !mbai.isWritable()
            && mbai.getDescriptor().getFieldValue("openType")
                .equals(new ArrayType<int[]>(SimpleType.INTEGER, true))
            && attrs[0].getType().equals("[I"))
            success("MBeanAttributeInfo");
        else
            failure("MBeanAttributeInfo: " + mbai);
    }

    int[] ints = (int[]) mbs.getAttribute(on, "Ints");
    if (equal(ints, new int[] {1, 2, 3}, null))
        success("getAttribute");
    else
        failure("getAttribute: " + Arrays.toString(ints));

    ExplicitMXBean proxy =
        JMX.newMXBeanProxy(mbs, on, ExplicitMXBean.class);
    int[] pints = proxy.getInts();
    if (equal(pints, new int[] {1, 2, 3}, null))
        success("getAttribute through proxy");
    else
        failure("getAttribute through proxy: " + Arrays.toString(pints));
}
 
Example 7
Source File: DerivedGaugeMonitorTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void check(String attr, MBeanServer server, ObjectName mon,
        ObjectName mbean, long start) throws Exception {
    final Object obj = server.getAttribute(mon, "DerivedGauge");
    final long now = System.currentTimeMillis();
    final long gran = (Long)server.getAttribute(mon, "GranularityPeriod");
    if (now > start +2*gran) {
        throw new Exception(attr+": Can't verify test case: " +
                "granularity period expired!");
    }
    check(attr,server,mon,mbean,obj);
}
 
Example 8
Source File: TestFSNamesystemMBean.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  try {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

    // Metrics that belong to "FSNamesystem", these are metrics that
    // come from hadoop metrics framework for the class FSNamesystem.
    ObjectName mxbeanNamefsn = new ObjectName(
        "Hadoop:service=NameNode,name=FSNamesystem");

    // Metrics that belong to "FSNamesystemState".
    // These are metrics that FSNamesystem registers directly with MBeanServer.
    ObjectName mxbeanNameFsns = new ObjectName(
        "Hadoop:service=NameNode,name=FSNamesystemState");

    // Metrics that belong to "NameNodeInfo".
    // These are metrics that FSNamesystem registers directly with MBeanServer.
    ObjectName mxbeanNameNni = new ObjectName(
        "Hadoop:service=NameNode,name=NameNodeInfo");

    final Set<ObjectName> mbeans = new HashSet<ObjectName>();
    mbeans.add(mxbeanNamefsn);
    mbeans.add(mxbeanNameFsns);
    mbeans.add(mxbeanNameNni);

    for(ObjectName mbean : mbeans) {
      MBeanInfo attributes = mbs.getMBeanInfo(mbean);
      for (MBeanAttributeInfo attributeInfo : attributes.getAttributes()) {
        mbs.getAttribute(mbean, attributeInfo.getName());
      }
    }

    succeeded = true;
  } catch (Exception e) {
  }
}
 
Example 9
Source File: LazyInitMBeanTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void invokeOnLazyInitBean() throws Exception {
	ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("org/springframework/jmx/export/lazyInit.xml");
	assertFalse(ctx.getBeanFactory().containsSingleton("testBean"));
	assertFalse(ctx.getBeanFactory().containsSingleton("testBean2"));
	try {
		MBeanServer server = (MBeanServer) ctx.getBean("server");
		ObjectName oname = ObjectNameManager.getInstance("bean:name=testBean2");
		String name = (String) server.getAttribute(oname, "Name");
		assertEquals("Invalid name returned", "foo", name);
	}
	finally {
		ctx.close();
	}
}
 
Example 10
Source File: MXBeanTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private static void testMXBean(MBeanServer mbs, ObjectName on)
        throws Exception {
    MBeanInfo mbi = mbs.getMBeanInfo(on);
    MBeanAttributeInfo[] attrs = mbi.getAttributes();
    int nattrs = attrs.length;
    if (mbi.getAttributes().length != 1)
        failure("wrong number of attributes: " + attrs);
    else {
        MBeanAttributeInfo mbai = attrs[0];
        if (mbai.getName().equals("Ints")
            && mbai.isReadable() && !mbai.isWritable()
            && mbai.getDescriptor().getFieldValue("openType")
                .equals(new ArrayType<int[]>(SimpleType.INTEGER, true))
            && attrs[0].getType().equals("[I"))
            success("MBeanAttributeInfo");
        else
            failure("MBeanAttributeInfo: " + mbai);
    }

    int[] ints = (int[]) mbs.getAttribute(on, "Ints");
    if (equal(ints, new int[] {1, 2, 3}, null))
        success("getAttribute");
    else
        failure("getAttribute: " + Arrays.toString(ints));

    ExplicitMXBean proxy =
        JMX.newMXBeanProxy(mbs, on, ExplicitMXBean.class);
    int[] pints = proxy.getInts();
    if (equal(pints, new int[] {1, 2, 3}, null))
        success("getAttribute through proxy");
    else
        failure("getAttribute through proxy: " + Arrays.toString(pints));
}
 
Example 11
Source File: TestNameNodeMXBean.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Test(timeout=120000)
public void testTopUsersNoPeriods() throws Exception {
  final Configuration conf = new Configuration();
  conf.setBoolean(DFSConfigKeys.NNTOP_ENABLED_KEY, true);
  conf.set(DFSConfigKeys.NNTOP_WINDOWS_MINUTES_KEY, "");
  MiniDFSCluster cluster = null;
  try {
    cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0).build();
    cluster.waitActive();
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    ObjectName mxbeanNameFsns = new ObjectName(
        "Hadoop:service=NameNode,name=FSNamesystemState");
    FileSystem fs = cluster.getFileSystem();
    final Path path = new Path("/");
    final int NUM_OPS = 10;
    for (int i=0; i< NUM_OPS; i++) {
      fs.listStatus(path);
      fs.setTimes(path, 0, 1);
    }
    String topUsers =
        (String) (mbs.getAttribute(mxbeanNameFsns, "TopUserOpCounts"));
    assertNotNull("Expected TopUserOpCounts bean!", topUsers);
  } finally {
    if (cluster != null) {
      cluster.shutdown();
    }
  }
}
 
Example 12
Source File: DerivedGaugeMonitorTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void check(String attr, MBeanServer server, ObjectName mon,
        ObjectName mbean, long start) throws Exception {
    final Object obj = server.getAttribute(mon, "DerivedGauge");
    final long now = System.currentTimeMillis();
    final long gran = (Long)server.getAttribute(mon, "GranularityPeriod");
    if (now > start +2*gran) {
        throw new Exception(attr+": Can't verify test case: " +
                "granularity period expired!");
    }
    check(attr,server,mon,mbean,obj);
}
 
Example 13
Source File: LazyInitMBeanTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void invokeOnLazyInitBean() throws Exception {
	ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("org/springframework/jmx/export/lazyInit.xml");
	assertFalse(ctx.getBeanFactory().containsSingleton("testBean"));
	assertFalse(ctx.getBeanFactory().containsSingleton("testBean2"));
	try {
		MBeanServer server = (MBeanServer) ctx.getBean("server");
		ObjectName oname = ObjectNameManager.getInstance("bean:name=testBean2");
		String name = (String) server.getAttribute(oname, "Name");
		assertEquals("Invalid name returned", "foo", name);
	}
	finally {
		ctx.close();
	}
}
 
Example 14
Source File: SystemUtils.java    From neural with MIT License 5 votes vote down vote up
private static Double getAttributeValue(MBeanServer beanServer, ObjectName objectName, String attribute) throws Exception {
    Object cpuLoadObject = beanServer.getAttribute(objectName, attribute);
    if (cpuLoadObject == null) {
        return null;
    }

    double cpuLoadValue = (double) cpuLoadObject;
    if (cpuLoadValue < 0) {
        // usually takes a couple of seconds before we get real values
        return 0.00;
    }

    // returns a percentage value with 1 decimal point precision
    return new BigDecimal(cpuLoadValue * 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
}
 
Example 15
Source File: TestSupport.java    From cache2k with Apache License 2.0 5 votes vote down vote up
/**
 * Looks up the given attributeName for the given cache.
 *
 * @throws javax.cache.CacheException - all exceptions are wrapped in CacheException
 */
public static Object lookupManagementAttribute(Cache cache, MBeanType type, String attributeName) {
  try {
    MBeanServer mBeanServer = TestSupport.resolveMBeanServer();
    ObjectName objectName = calculateObjectName(cache, type);
    return mBeanServer.getAttribute(objectName, attributeName);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 16
Source File: ComparatorExceptionTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    ObjectName name = new ObjectName("a:b=c");
    mbs.registerMBean(new TestImpl(), name);

    for (String attr : new String[] {"SortedSet", "SortedMap"}) {
        try {
            Object value = mbs.getAttribute(name, attr);
            fail("get " + attr + " did not throw exception");
        } catch (Exception e) {
            Throwable t = e;
            while (!(t instanceof IllegalArgumentException)) {
                if (t == null)
                    break;
                t = t.getCause();
            }
            if (t != null)
                System.out.println("Correct exception for " + attr);
            else {
                fail("get " + attr + " got wrong exception");
                e.printStackTrace(System.out);
            }
        }
    }

    if (failure != null)
        throw new Exception(failure);
}
 
Example 17
Source File: TestAggressiveHeap.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static boolean haveRequiredMemory() throws Exception {
    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    ObjectName os = new ObjectName("java.lang", "type", "OperatingSystem");
    Object attr = server.getAttribute(os, "TotalPhysicalMemorySize");
    String value = attr.toString();
    long memory = Long.parseLong(value);
    return memory >= minMemory;
}
 
Example 18
Source File: MbeanCommand.java    From LagMonitor with MIT License 5 votes vote down vote up
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (!canExecute(sender, command)) {
        return true;
    }

    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();

    if (args.length > 0) {
        try {
            ObjectName beanObject = ObjectName.getInstance(args[0]);
            if (args.length > 1) {
                Object result = mBeanServer.getAttribute(beanObject, args[1]);
                sender.sendMessage(ChatColor.DARK_GREEN + Objects.toString(result));
            } else {
                MBeanAttributeInfo[] attributes = mBeanServer.getMBeanInfo(beanObject).getAttributes();
                for (MBeanAttributeInfo attribute : attributes) {
                    if ("ObjectName".equals(attribute.getName())) {
                        //ignore the object name - it's already known if the user invoke the command
                        continue;
                    }

                    sender.sendMessage(ChatColor.YELLOW + attribute.getName());
                }
            }
        } catch (Exception ex) {
            plugin.getLogger().log(Level.SEVERE, null, ex);
        }
    } else {
        Set<ObjectInstance> allBeans = mBeanServer.queryMBeans(null, null);
        allBeans.stream()
                .map(ObjectInstance::getObjectName)
                .map(ObjectName::getCanonicalName)
                .forEach(bean -> sender.sendMessage(ChatColor.DARK_AQUA + bean));
    }

    return true;
}
 
Example 19
Source File: DerivedGaugeMonitorTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void check(String attr, MBeanServer server, ObjectName mon,
        ObjectName mbean) throws Exception {
    final Object obj = server.getAttribute(mon, "DerivedGauge");
    check(attr,server,mon,mbean,obj);
}
 
Example 20
Source File: DerivedGaugeMonitorTest.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void check(String attr, MBeanServer server, ObjectName mon,
        ObjectName mbean) throws Exception {
    final Object obj = server.getAttribute(mon, "DerivedGauge");
    check(attr,server,mon,mbean,obj);
}