下面列出了javax.management.MBeanServerConnection#getAttribute ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Returns members for mentioned group. Scans groups list of memberMbeans
* If group is null returns all members
* @param connection
* @param group
* @return
* @throws NullPointerException
* @throws MalformedObjectNameException
* @throws IOException
* @throws ReflectionException
* @throws MBeanException
* @throws InstanceNotFoundException
* @throws AttributeNotFoundException
*/
public static Set<String> getMembersForGroup(MBeanServerConnection connection, String group) throws MalformedObjectNameException, NullPointerException, InstanceNotFoundException, MBeanException, ReflectionException, IOException, AttributeNotFoundException {
Set<String> memberSet = new HashSet<String>();
ObjectName ds = new ObjectName("GemFire:service=System,type=Distributed");
String[] memberList = (String[]) connection.invoke(ds, "listMembers", null, null);
for(String member : memberList){
ObjectName memberMBean = new ObjectName("GemFire:type=Member,member="+member);
String groups[] = (String[]) connection.getAttribute(memberMBean, "Groups");
for(String g : groups){
if(g.equals(group) || group==null){
memberSet.add(member);
}
}
}
return memberSet;
}
private static void printAttrs(
MBeanServerConnection mbsc1, Class<? extends Exception> expectX)
throws Exception {
Set<ObjectName> names = mbsc1.queryNames(null, null);
for (ObjectName name : names) {
System.out.println(name + ":");
MBeanInfo mbi = mbsc1.getMBeanInfo(name);
MBeanAttributeInfo[] mbais = mbi.getAttributes();
for (MBeanAttributeInfo mbai : mbais) {
String attr = mbai.getName();
Object value;
try {
value = mbsc1.getAttribute(name, attr);
} catch (Exception e) {
if (expectX != null && expectX.isInstance(e))
value = "<" + e + ">";
else
throw e;
}
String s = " " + attr + " = " + value;
if (s.length() > 80)
s = s.substring(0, 77) + "...";
System.out.println(s);
}
}
}
private static void printAttrs(
MBeanServerConnection mbsc1, Class<? extends Exception> expectX)
throws Exception {
Set<ObjectName> names = mbsc1.queryNames(null, null);
for (ObjectName name : names) {
System.out.println(name + ":");
MBeanInfo mbi = mbsc1.getMBeanInfo(name);
MBeanAttributeInfo[] mbais = mbi.getAttributes();
for (MBeanAttributeInfo mbai : mbais) {
String attr = mbai.getName();
Object value;
try {
value = mbsc1.getAttribute(name, attr);
} catch (Exception e) {
if (expectX != null && expectX.isInstance(e))
value = "<" + e + ">";
else
throw e;
}
String s = " " + attr + " = " + value;
if (s.length() > 80)
s = s.substring(0, 77) + "...";
System.out.println(s);
}
}
}
private static void printAttrs(
MBeanServerConnection mbsc1, Class<? extends Exception> expectX)
throws Exception {
Set<ObjectName> names = mbsc1.queryNames(null, null);
for (ObjectName name : names) {
System.out.println(name + ":");
MBeanInfo mbi = mbsc1.getMBeanInfo(name);
MBeanAttributeInfo[] mbais = mbi.getAttributes();
for (MBeanAttributeInfo mbai : mbais) {
String attr = mbai.getName();
Object value;
try {
value = mbsc1.getAttribute(name, attr);
} catch (Exception e) {
if (expectX != null && expectX.isInstance(e))
value = "<" + e + ">";
else
throw e;
}
String s = " " + attr + " = " + value;
if (s.length() > 80)
s = s.substring(0, 77) + "...";
System.out.println(s);
}
}
}
private static void printAttrs(
MBeanServerConnection mbsc1, Class<? extends Exception> expectX)
throws Exception {
Set<ObjectName> names = mbsc1.queryNames(null, null);
for (ObjectName name : names) {
System.out.println(name + ":");
MBeanInfo mbi = mbsc1.getMBeanInfo(name);
MBeanAttributeInfo[] mbais = mbi.getAttributes();
for (MBeanAttributeInfo mbai : mbais) {
String attr = mbai.getName();
Object value;
try {
value = mbsc1.getAttribute(name, attr);
} catch (Exception e) {
if (expectX != null && expectX.isInstance(e))
value = "<" + e + ">";
else
throw e;
}
String s = " " + attr + " = " + value;
if (s.length() > 80)
s = s.substring(0, 77) + "...";
System.out.println(s);
}
}
}
private void getAttribute(String userName, JmxManagementInterface jmx) throws Exception {
boolean successExpected = isReadAllowed(userName);
MBeanServerConnection connection = jmx.getConnection();
ObjectName domain = new ObjectName("java.lang:type=OperatingSystem");
try {
Object attribute = connection.getAttribute(domain, "Name");
assertTrue("Failure was expected", successExpected);
assertEquals(System.getProperty("os.name"), attribute.toString());
} catch (JMRuntimeException e) {
if (e.getMessage().contains("WFLYJMX0037")) {
assertFalse("Success was expected but failure happened: " + e, successExpected);
} else {
throw e;
}
}
}
public static void main(String[] args) throws Exception {
JMXServiceURL serviceUrl = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:33655/jmxrmi");
JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceUrl, null);
MBeanServerConnection mbeanConn = jmxConnector.getMBeanServerConnection();
ObjectName objectName = new ObjectName("edu.javacourse.jmx:name=Statistics");
while(true) {
Object currentTime = mbeanConn.getAttribute(objectName, "CurrentTime");
Object randomNumber = mbeanConn.getAttribute(objectName, "RandomNumber");
System.out.println(currentTime.getClass().getCanonicalName() + ": " + currentTime);
System.out.println(randomNumber.getClass().getCanonicalName() + ": " + randomNumber);
System.out.println();
Thread.sleep(2000);
}
}
private static void printAttrs(
MBeanServerConnection mbsc1, Class<? extends Exception> expectX)
throws Exception {
Set<ObjectName> names = mbsc1.queryNames(null, null);
for (ObjectName name : names) {
System.out.println(name + ":");
MBeanInfo mbi = mbsc1.getMBeanInfo(name);
MBeanAttributeInfo[] mbais = mbi.getAttributes();
for (MBeanAttributeInfo mbai : mbais) {
String attr = mbai.getName();
Object value;
try {
value = mbsc1.getAttribute(name, attr);
} catch (Exception e) {
if (expectX != null && expectX.isInstance(e))
value = "<" + e + ">";
else
throw e;
}
String s = " " + attr + " = " + value;
if (s.length() > 80)
s = s.substring(0, 77) + "...";
System.out.println(s);
}
}
}
/**
* Get property value.
*
* @param jmxServerConnection Connection to the JMX server
* @param name The MBean name
* @return The error message if any
* @throws Exception An error occurred
*/
protected String jmxGet(MBeanServerConnection jmxServerConnection, String name) throws Exception {
String error = null;
if(isEcho()) {
handleOutput("MBean " + name + " get attribute " + attribute );
}
Object result = jmxServerConnection.getAttribute(
new ObjectName(name), attribute);
if (result != null) {
echoResult(attribute,result);
createProperty(result);
} else
error = "Attribute " + attribute + " is empty";
return error;
}
public boolean makeServerConnection(JMXConnector jmxConnector) throws IOException, MBeanException,
AttributeNotFoundException, InstanceNotFoundException, ReflectionException, MalformedObjectNameException{
MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection();
Set<ObjectName> mbeans = mBeanServerConnection.queryNames(new ObjectName("CoUGAR:name=healthChecker,*"), null);
if (!mbeans.isEmpty()) {
mBeanServerConnection.getAttribute(mbeans.iterator().next(), "SystemInService");
return true;
}
return false;
}
/**
* @param jmxServerConnection
* @param name
* @return The value of the given named attribute
* @throws Exception
*/
protected String jmxGet(MBeanServerConnection jmxServerConnection,String name) throws Exception {
String error = null;
if(isEcho()) {
handleOutput("MBean " + name + " get attribute " + attribute );
}
Object result = jmxServerConnection.getAttribute(
new ObjectName(name), attribute);
if (result != null) {
echoResult(attribute,result);
createProperty(result);
} else
error = "Attribute " + attribute + " is empty";
return error;
}
private void setJMXMBeanAttribute(String mBeanName, String attributeName,
Object newMbeanValue) {
try {
MBeanServerConnection mBeanServerConnection = getJMXConnection();
ObjectName mbeanName = new ObjectName(mBeanName);
Object currentAttributeValue = mBeanServerConnection.getAttribute(mbeanName, attributeName);
Object reflectedValue = reflect.getRealProperty(currentAttributeValue.getClass(), newMbeanValue);
Attribute attribute = new Attribute(attributeName, reflectedValue);
mBeanServerConnection.setAttribute(mbeanName, attribute);
} catch (Exception e) {
throw new RuntimeException(JMX_SETTING_ERROR + mBeanName + ": " + attributeName, e);
}
}
private static void testWithException(boolean send)
throws Exception {
ClassLoader zoobyCL = new ZoobyClassLoader();
Class<?> zoobyClass = Class.forName("Zooby", false, zoobyCL);
Object zooby = zoobyClass.newInstance();
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///");
JMXConnectorServer cs =
JMXConnectorServerFactory.newJMXConnectorServer(url, null, pmbs);
cs.start();
JMXServiceURL addr = cs.getAddress();
JMXConnector cc = JMXConnectorFactory.connect(addr);
MBeanServerConnection mbsc = cc.getMBeanServerConnection();
Object rzooby;
if (send) {
System.out.println("Sending object...");
mbsc.setAttribute(getSetName, new Attribute("It", zooby));
rzooby = getSetInstance.getIt();
} else {
System.out.println("Receiving object...");
getSetInstance.setIt(zooby);
rzooby = mbsc.getAttribute(getSetName, "It");
}
if (!rzooby.getClass().getName().equals("Zooby")) {
throw new Exception("FAILED: remote object is not a Zooby");
}
if (rzooby.getClass().getClassLoader() ==
zooby.getClass().getClassLoader()) {
throw new Exception("FAILED: same class loader: " +
zooby.getClass().getClassLoader());
}
cc.close();
cs.stop();
}
private Number validateTableAttr(String tableName, MBeanServerConnection mBeanServer, ObjectName name, Attribute attribute, String sql, OutputType type) throws TestException, AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException, IOException {
mbeanHelper.runQueryAndPrintValue(sql);
Number expected = (Number)mbeanHelper.runQueryAndGetValue(sql, type);
Number actual = ((Number)mBeanServer.getAttribute(name, attribute.getName()));
if(!actual.toString().equals(expected.toString())) {
saveError(attribute.getName() + " attribute did not match for " + tableName + " where expected = " + expected + " and actual : " + actual);
} else {
Log.getLogWriter().info(attribute.getName() + " attribute match for " + tableName + " where expected = " + expected + " and actual : " + actual);
}
return actual;
}
private static void testWithException(boolean send)
throws Exception {
ClassLoader zoobyCL = new ZoobyClassLoader();
Class<?> zoobyClass = Class.forName("Zooby", false, zoobyCL);
Object zooby = zoobyClass.newInstance();
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///");
JMXConnectorServer cs =
JMXConnectorServerFactory.newJMXConnectorServer(url, null, pmbs);
cs.start();
JMXServiceURL addr = cs.getAddress();
JMXConnector cc = JMXConnectorFactory.connect(addr);
MBeanServerConnection mbsc = cc.getMBeanServerConnection();
Object rzooby;
if (send) {
System.out.println("Sending object...");
mbsc.setAttribute(getSetName, new Attribute("It", zooby));
rzooby = getSetInstance.getIt();
} else {
System.out.println("Receiving object...");
getSetInstance.setIt(zooby);
rzooby = mbsc.getAttribute(getSetName, "It");
}
if (!rzooby.getClass().getName().equals("Zooby")) {
throw new Exception("FAILED: remote object is not a Zooby");
}
if (rzooby.getClass().getClassLoader() ==
zooby.getClass().getClassLoader()) {
throw new Exception("FAILED: same class loader: " +
zooby.getClass().getClassLoader());
}
cc.close();
cs.stop();
}
@Test(groups = {"wso2.esb"}, description = "Send messages using ConcurrentConsumers " +
"and MaxConcurrentConsumers Axis2 level properties")
public void maxConcurrentConsumersTest() throws Exception {
serverManager.restartGracefully();
super.init(); // after restart the server instance initialization
JMXServiceURL url =
new JMXServiceURL("service:jmx:rmi://" +
context.getDefaultInstance().getHosts().get("default") +
":11311/jndi/rmi://" + context.getDefaultInstance().getHosts().
get("default") + ":10199/jmxrmi");
HashMap<String, String[]> environment = new HashMap<String, String[]>();
String[] credentials = new String[]{"admin", "admin"};
environment.put(JMXConnector.CREDENTIALS, credentials);
MBeanServerConnection mBeanServerConnection = JMXConnectorFactory.
connect(url, environment).getMBeanServerConnection();
int beforeThreadCount = (Integer) mBeanServerConnection.getAttribute(
new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME), "ThreadCount");
String queueName = "SimpleStockQuoteService";
for (int x = 0; x < 200; x++) {
JMSQueueMessageProducer sender = new JMSQueueMessageProducer
(JMSBrokerConfigurationProvider.getInstance().getBrokerConfiguration());
try {
sender.connect(queueName);
for (int i = 0; i < 3; i++) {
sender.pushMessage("<?xml version='1.0' encoding='UTF-8'?>" +
"<soapenv:Envelope xmlns:soapenv=\"http://schemas." +
"xmlsoap.org/soap/envelope/\"" +
" xmlns:ser=\"http://services.samples\" xmlns:xsd=\"" +
"http://services.samples/xsd\">" +
" <soapenv:Header/>" +
" <soapenv:Body>" +
" <ser:placeOrder>" +
" <ser:order>" +
" <xsd:price>100</xsd:price>" +
" <xsd:quantity>2000</xsd:quantity>" +
" <xsd:symbol>JMSTransport</xsd:symbol>" +
" </ser:order>" +
" </ser:placeOrder>" +
" </soapenv:Body>" +
"</soapenv:Envelope>");
}
} finally {
sender.disconnect();
}
}
int afterThreadCount = (Integer) mBeanServerConnection.getAttribute(
new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME), "ThreadCount");
assertTrue((afterThreadCount - beforeThreadCount) <= 150, "Expected thread count range" +
" not met");
}
private final int doBasicMXBeanTest(MBeanServerConnection mbsc) {
int errorCount = 0 ;
System.out.println("---- doBasicMXBeanTest") ;
try {
ObjectName objName =
new ObjectName("sqe:type=BasicMXBean") ;
mbsc.createMBean(BASIC_MXBEAN_CLASS_NAME, objName);
MBeanInfo mbInfo = mbsc.getMBeanInfo(objName);
printMBeanInfo(mbInfo);
System.out.println("---- OK\n") ;
System.out.println("getMBeanInfo\t\t"
+ mbInfo);
System.out.println("---- OK\n") ;
System.out.println("Check mxbean field in the MBeanInfo");
String mxbeanField =
(String)mbInfo.getDescriptor().getFieldValue(JMX.MXBEAN_FIELD);
if ( mxbeanField == null || ! mxbeanField.equals("true")) {
System.out.println("---- ERROR : Improper mxbean field value "
+ mxbeanField);
errorCount++;
}
System.out.println("---- OK\n") ;
System.out.println("Set attribute ObjectNameAtt");
Attribute att = new Attribute("ObjectNameAtt", objName);
mbsc.setAttribute(objName, att);
ObjectName value =
(ObjectName)mbsc.getAttribute(objName, "ObjectNameAtt");
if ( ! value.equals(objName) ) {
errorCount++;
System.out.println("---- ERROR : setAttribute failed, got "
+ value
+ " while expecting "
+ objName);
}
System.out.println("---- OK\n") ;
System.out.println("Call operation doNothing");
mbsc.invoke(objName, "doNothing", null, null);
System.out.println("---- OK\n") ;
System.out.println("Call operation getWeather");
Object weather = mbsc.invoke(objName,
"getWeather",
new Object[]{Boolean.TRUE},
new String[]{"boolean"});
System.out.println("Weather is " + weather);
System.out.println("---- OK\n") ;
} catch (Exception e) {
Utils.printThrowable(e, true) ;
errorCount++ ;
System.out.println("---- ERROR\n") ;
}
return errorCount ;
}
/**
* Make some check about the instance of TestJMXAuthenticator.
* The authenticator is supposed to have set some properties on
* a ServerDelegate MBean.
* We compare the number of times it has been called with the expected value.
* We also check the Principal that has been given to the authenticator
* was not null.
* That method is of use to authentication with the JSR 262.
* @param mbs
* @param expectedAuthenticatorCallCount
* @return The number of errors encountered.
* @throws java.lang.Exception
*/
protected int checkAuthenticator(MBeanServerConnection mbs,
int expectedAuthenticatorCallCount) throws Exception {
int errorCount = 0;
// Ensure the authenticator has been called the right number
// of times.
int callCount =
((Integer) mbs.getAttribute(
new ObjectName(SERVER_DELEGATE_MBEAN_NAME),
"TestJMXAuthenticatorCallCount")).intValue();
if (callCount == expectedAuthenticatorCallCount) {
System.out.println("---- OK Authenticator has been called "
+ expectedAuthenticatorCallCount + " time");
} else {
errorCount++;
System.out.println("---- ERROR Authenticator has been called " + callCount
+ " times in place of " + expectedAuthenticatorCallCount);
}
// Ensure the provider has been called with
// a non null Principal.
String principalString =
(String) mbs.getAttribute(
new ObjectName(SERVER_DELEGATE_MBEAN_NAME),
"TestJMXAuthenticatorPrincipalString");
if (principalString == null) {
errorCount++;
System.out.println("---- ERROR Authenticator has been called"
+ " with a null Principal");
} else {
if (principalString.length() > 0) {
System.out.println("---- OK Authenticator has been called"
+ " with the Principal " + principalString);
} else {
errorCount++;
System.out.println("---- ERROR Authenticator has been called"
+ " with an empty Principal");
}
}
return errorCount;
}
Object getAttribute(MBeanServerConnection mbsc,
ObjectName object,
String attribute)
throws AttributeNotFoundException,
InstanceNotFoundException,
MBeanException,
ReflectionException,
IOException {
// Check for "ObservedAttribute" replacement.
// This could happen if a thread A called setObservedAttribute()
// while other thread B was in the middle of the monitor() method
// and received the old observed attribute value.
//
final boolean lookupMBeanInfo;
synchronized (this) {
if (!isActive())
throw new IllegalArgumentException(
"The monitor has been stopped");
if (!attribute.equals(getObservedAttribute()))
throw new IllegalArgumentException(
"The observed attribute has been changed");
lookupMBeanInfo =
(firstAttribute == null && attribute.indexOf('.') != -1);
}
// Look up MBeanInfo if needed
//
final MBeanInfo mbi;
if (lookupMBeanInfo) {
try {
mbi = mbsc.getMBeanInfo(object);
} catch (IntrospectionException e) {
throw new IllegalArgumentException(e);
}
} else {
mbi = null;
}
// Check for complex type attribute
//
final String fa;
synchronized (this) {
if (!isActive())
throw new IllegalArgumentException(
"The monitor has been stopped");
if (!attribute.equals(getObservedAttribute()))
throw new IllegalArgumentException(
"The observed attribute has been changed");
if (firstAttribute == null) {
if (attribute.indexOf('.') != -1) {
MBeanAttributeInfo mbaiArray[] = mbi.getAttributes();
for (MBeanAttributeInfo mbai : mbaiArray) {
if (attribute.equals(mbai.getName())) {
firstAttribute = attribute;
break;
}
}
if (firstAttribute == null) {
String tokens[] = attribute.split("\\.", -1);
firstAttribute = tokens[0];
for (int i = 1; i < tokens.length; i++)
remainingAttributes.add(tokens[i]);
isComplexTypeAttribute = true;
}
} else {
firstAttribute = attribute;
}
}
fa = firstAttribute;
}
return mbsc.getAttribute(object, fa);
}
private String[] getGfxdClusterMembers(MBeanServerConnection mbeanServer) throws Exception {
ObjectName name = new ObjectName(ManagementConstants.OBJECTNAME__CLUSTER_MXBEAN);
String[] members = (String[]) mbeanServer.getAttribute(name, "Members");
return members;
}