Java Code Examples for javax.management.MBeanServerConnection#getAttributes()

The following examples show how to use javax.management.MBeanServerConnection#getAttributes() . 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: BrokerStatsRetriever.java    From doctorkafka with Apache License 2.0 6 votes vote down vote up
public static double getProcessCpuLoad(MBeanServerConnection mbs)
    throws MalformedObjectNameException, NullPointerException, InstanceNotFoundException,
           ReflectionException, IOException {
  ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem");
  AttributeList list = mbs.getAttributes(name, new String[]{"ProcessCpuLoad"});

  if (list.isEmpty()) {
    return 0.0;
  }

  Attribute att = (Attribute) list.get(0);
  Double value = (Double) att.getValue();

  // usually takes a couple of seconds before we get real values
  if (value == -1.0) {
    return 0.0;
  }
  // returns a percentage value with 1 decimal point precision
  return ((int) (value * 1000) / 10.0);
}
 
Example 2
Source File: Client.java    From vjtools with Apache License 2.0 5 votes vote down vote up
protected static Object doAttributeOperation(MBeanServerConnection mbsc, ObjectInstance instance, String command,
		MBeanAttributeInfo[] infos) throws Exception {
	// Usually we get attributes. If an argument, then we're being asked
	// to set attribute.
	CommandParse parse = new CommandParse(command);
	if (parse.getArgs() == null || parse.getArgs().length == 0) {
		// Special-casing. If the subCommand is 'Attributes', then return
		// list of all attributes.
		if (command.equals("Attributes")) {
			String[] names = new String[infos.length];
			for (int i = 0; i < infos.length; i++) {
				names[i] = infos[i].getName();
			}
			return mbsc.getAttributes(instance.getObjectName(), names);
		}
		return mbsc.getAttribute(instance.getObjectName(), parse.getCmd());
	}
	if (parse.getArgs().length != 1) {
		throw new IllegalArgumentException("One only argument setting " + "attribute values: " + parse.getArgs());
	}
	// Get first attribute of name 'cmd'. Assumption is no method
	// overrides. Then, look at the attribute and use its type.
	MBeanAttributeInfo info = (MBeanAttributeInfo) getFeatureInfo(infos, parse.getCmd());
	java.lang.reflect.Constructor c = Class.forName(info.getType()).getConstructor(new Class[] { String.class });
	Attribute a = new Attribute(parse.getCmd(), c.newInstance(new Object[] { parse.getArgs()[0] }));
	mbsc.setAttribute(instance.getObjectName(), a);
	return null;
}
 
Example 3
Source File: Client.java    From vjtools with Apache License 2.0 5 votes vote down vote up
protected static Object doAttributeOperation(MBeanServerConnection mbsc, ObjectInstance instance, String command,
		MBeanAttributeInfo[] infos) throws Exception {
	// Usually we get attributes. If an argument, then we're being asked
	// to set attribute.
	CommandParse parse = new CommandParse(command);
	if (parse.getArgs() == null || parse.getArgs().length == 0) {
		// Special-casing. If the subCommand is 'Attributes', then return
		// list of all attributes.
		if (command.equals("Attributes")) {
			String[] names = new String[infos.length];
			for (int i = 0; i < infos.length; i++) {
				names[i] = infos[i].getName();
			}
			return mbsc.getAttributes(instance.getObjectName(), names);
		}
		return mbsc.getAttribute(instance.getObjectName(), parse.getCmd());
	}
	if (parse.getArgs().length != 1) {
		throw new IllegalArgumentException("One only argument setting " + "attribute values: " + parse.getArgs());
	}
	// Get first attribute of name 'cmd'. Assumption is no method
	// overrides. Then, look at the attribute and use its type.
	MBeanAttributeInfo info = (MBeanAttributeInfo) getFeatureInfo(infos, parse.getCmd());
	java.lang.reflect.Constructor c = Class.forName(info.getType()).getConstructor(new Class[] { String.class });
	Attribute a = new Attribute(parse.getCmd(), c.newInstance(new Object[] { parse.getArgs()[0] }));
	mbsc.setAttribute(instance.getObjectName(), a);
	return null;
}
 
Example 4
Source File: KafkaMetrics.java    From kmanager with Apache License 2.0 5 votes vote down vote up
private MeterMetric getMeterMetric(MBeanServerConnection mbsc, ObjectName objectName) {
  String[] attributes = {"Count", "MeanRate", "OneMinuteRate", "FiveMinuteRate", "FifteenMinuteRate"};
  AttributeList attributeList = null;
  try {
    attributeList = mbsc.getAttributes(objectName, attributes);
  } catch (Exception e) {
    LOG.warn("getMeterMetric failed! " + e.getMessage());
    return new MeterMetric(0L, 0D, 0D, 0D, 0D);
  }
  return new MeterMetric(getLongValue(attributeList, attributes[0]), getDoubleValue(attributeList, attributes[1]),
      getDoubleValue(attributeList, attributes[2]), getDoubleValue(attributeList, attributes[3]),
      getDoubleValue(attributeList, attributes[4]));
}
 
Example 5
Source File: AddGetReleaseRemoveTest.java    From scheduling with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
public void action() throws Exception {

    final ResourceManager rm = rmHelper.getResourceManager();
    // The username and thr password must be the same a used to connect to the RM
    final String adminLogin = TestUsers.TEST.username;
    final String adminPassword = TestUsers.TEST.password;

    // All accounting values are checked through JMX
    final RMAuthentication auth = rmHelper.getRMAuth();
    final PublicKey pubKey = auth.getPublicKey();
    final Credentials adminCreds = Credentials.createCredentials(new CredData(adminLogin, adminPassword), pubKey);

    final JMXServiceURL jmxRmiServiceURL = new JMXServiceURL(auth.getJMXConnectorURL(JMXTransportProtocol.RMI));
    final HashMap<String, Object> env = new HashMap<>(1);
    env.put(JMXConnector.CREDENTIALS, new Object[] { adminLogin, adminCreds });

    // Connect to the JMX RMI Connector Server
    final ObjectName myAccountMBeanName = new ObjectName(RMJMXBeans.MYACCOUNT_MBEAN_NAME);
    final ObjectName managementMBeanName = new ObjectName(RMJMXBeans.MANAGEMENT_MBEAN_NAME);
    final JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxRmiServiceURL, env);
    final MBeanServerConnection conn = jmxConnector.getMBeanServerConnection();

    // Ensure that no refreshes was done and all account values are correctly initialized        
    AttributeList atts = conn.getAttributes(myAccountMBeanName,
                                            new String[] { "UsedNodeTime", "ProvidedNodeTime",
                                                           "ProvidedNodesCount" });

    long usedNodeTime = (Long) ((Attribute) atts.get(0)).getValue();
    long providedNodeTime = (Long) ((Attribute) atts.get(1)).getValue();
    int providedNodesCount = (Integer) ((Attribute) atts.get(2)).getValue();

    // ADD, GET, RELEASE, REMOVE
    // 1) ADD
    final long beforeAddTime = System.currentTimeMillis();
    testNode = rmHelper.createNode("test");
    Node node = testNode.getNode();
    final String nodeURL = node.getNodeInformation().getURL();
    rm.addNode(nodeURL).getBooleanValue();

    // We eat the configuring to free event
    rmHelper.waitForNodeEvent(RMEventType.NODE_ADDED, nodeURL);
    rmHelper.waitForNodeEvent(RMEventType.NODE_STATE_CHANGED, nodeURL);
    // 2) GET
    final long beforeGetTime = System.currentTimeMillis();
    node = rm.getAtMostNodes(1, null).get(0);

    // Sleep a certain amount of time that will be the minimum amount of the GET->RELEASE duration 
    Thread.sleep(GR_DURATION);

    // 3) RELEASE
    rm.releaseNode(node).getBooleanValue();
    final long getReleaseMaxDuration = System.currentTimeMillis() - beforeGetTime;

    // 4) REMOVE  
    rm.removeNode(nodeURL, true).getBooleanValue();
    final long addRemoveMaxDuration = System.currentTimeMillis() - beforeAddTime;

    // Refresh the account manager
    conn.invoke(managementMBeanName, "clearAccoutingCache", null, null);

    // Check account values validity                      
    atts = conn.getAttributes(myAccountMBeanName,
                              new String[] { "UsedNodeTime", "ProvidedNodeTime", "ProvidedNodesCount" });
    usedNodeTime = (Long) ((Attribute) atts.get(0)).getValue() - usedNodeTime;
    providedNodeTime = (Long) ((Attribute) atts.get(1)).getValue() - providedNodeTime;
    providedNodesCount = (Integer) ((Attribute) atts.get(2)).getValue() - providedNodesCount;

    Assert.assertTrue("Invalid value of the usedNodeTime attribute (usedNodeTime=" + usedNodeTime + ")",
                      (usedNodeTime >= GR_DURATION));
    Assert.assertTrue("Invalid value of the usedNodeTime attribute (getReleaseMaxDuration=" +
                      getReleaseMaxDuration + ")", (usedNodeTime <= getReleaseMaxDuration));
    Assert.assertTrue("Invalid value of the providedNodeTime attribute",
                      (providedNodeTime >= usedNodeTime) && (providedNodeTime <= addRemoveMaxDuration));
}
 
Example 6
Source File: AddGetTest.java    From scheduling with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Test function.
 * @throws Exception
 */
@org.junit.Test
public void action() throws Exception {

    final ResourceManager rm = rmHelper.getResourceManager();
    // The username and thr password must be the same a used to connect to the RM
    final String adminLogin = TestUsers.TEST.username;
    final String adminPassword = TestUsers.TEST.password;

    // All accounting values are checked through JMX
    final RMAuthentication auth = (RMAuthentication) rmHelper.getRMAuth();
    final PublicKey pubKey = auth.getPublicKey();
    final Credentials adminCreds = Credentials.createCredentials(new CredData(adminLogin, adminPassword), pubKey);

    final JMXServiceURL jmxRmiServiceURL = new JMXServiceURL(auth.getJMXConnectorURL(JMXTransportProtocol.RMI));
    final HashMap<String, Object> env = new HashMap<>(1);
    env.put(JMXConnector.CREDENTIALS, new Object[] { adminLogin, adminCreds });

    // Connect to the JMX RMI Connector Server
    final ObjectName myAccountMBeanName = new ObjectName(RMJMXBeans.MYACCOUNT_MBEAN_NAME);
    final ObjectName managementMBeanName = new ObjectName(RMJMXBeans.MANAGEMENT_MBEAN_NAME);
    final JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxRmiServiceURL, env);
    final MBeanServerConnection conn = jmxConnector.getMBeanServerConnection();

    // Tests on database
    //(nodeprovider=demo)                      

    // Ensure that no refreshes was done and all account values are correctly initialized        
    AttributeList atts = conn.getAttributes(myAccountMBeanName,
                                            new String[] { "UsedNodeTime", "ProvidedNodeTime",
                                                           "ProvidedNodesCount" });
    long usedNodeTime = (Long) ((Attribute) atts.get(0)).getValue();
    long providedNodeTime = (Long) ((Attribute) atts.get(1)).getValue();
    int providedNodesCount = (Integer) ((Attribute) atts.get(2)).getValue();

    Assert.assertEquals("The accounts must not be refreshed automatically therefore the LastRefreshDurationInMilliseconds must be 0",
                        (Long) 0l,
                        (Long) conn.getAttribute(managementMBeanName, "LastRefreshDurationInMilliseconds"));
    Assert.assertTrue("The usedNodeTime attribute must be 0", usedNodeTime == 0);
    Assert.assertTrue("The providedNodeTime attribute must be 0", providedNodeTime == 0);
    Assert.assertTrue("The providedNodesCount attribute must be 0", providedNodesCount == 0);

    // ADD, GET
    // 1) ADD
    final long beforeAddTime = System.currentTimeMillis();
    testNode = rmHelper.createNode("test");
    Node node = testNode.getNode();
    final String nodeURL = node.getNodeInformation().getURL();
    rm.addNode(nodeURL).getBooleanValue();
    //we eat the configuring to free
    rmHelper.waitForAnyNodeEvent(RMEventType.NODE_ADDED);
    rmHelper.waitForAnyNodeEvent(RMEventType.NODE_STATE_CHANGED);

    // 2) GET
    final long beforeGetTime = System.currentTimeMillis();
    node = rm.getAtMostNodes(1, null).get(0);

    // Sleep a certain amount of time that will be the minimum amount of the GET duration 
    Thread.sleep(GR_DURATION);

    // Refresh the account manager
    conn.invoke(managementMBeanName, "clearAccoutingCache", null, null);

    final long currentTime = System.currentTimeMillis();
    final long addRefreshMaxDuration = currentTime - beforeAddTime;
    final long getRefreshMaxDuration = currentTime - beforeGetTime;

    // Check account values validity                      
    atts = conn.getAttributes(myAccountMBeanName,
                              new String[] { "UsedNodeTime", "ProvidedNodeTime", "ProvidedNodesCount" });
    usedNodeTime = (Long) ((Attribute) atts.get(0)).getValue();
    providedNodeTime = (Long) ((Attribute) atts.get(1)).getValue();
    providedNodesCount = (Integer) ((Attribute) atts.get(2)).getValue();

    Assert.assertTrue("Invalid value of the usedNodeTime attribute",
                      (usedNodeTime >= GR_DURATION) && (usedNodeTime <= addRefreshMaxDuration));
    Assert.assertTrue("Invalid value of the providedNodeTime attribute",
                      (providedNodeTime >= usedNodeTime) && (providedNodeTime <= getRefreshMaxDuration));
    Assert.assertTrue("Invalid value of the providedNodesCount attribute", (providedNodesCount == 1));
}