下面列出了怎么用javax.management.MBeanInfo的API类实例代码及写法,或者点击链接到github查看源代码。
public MBeanInfo getMBeanInfo(ObjectName name)
throws InstanceNotFoundException,
IntrospectionException,
ReflectionException,
IOException {
if (logger.debugOn()) logger.debug("getMBeanInfo", "name=" + name);
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.getMBeanInfo(name, delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.getMBeanInfo(name, delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
private static boolean test(Object mbean, boolean expectImmutable)
throws Exception {
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
ObjectName on = new ObjectName("a:b=c");
mbs.registerMBean(mbean, on);
MBeanInfo mbi = mbs.getMBeanInfo(on);
Descriptor d = mbi.getDescriptor();
String immutableValue = (String) d.getFieldValue("immutableInfo");
boolean immutable = ("true".equals(immutableValue));
if (immutable != expectImmutable) {
System.out.println("FAILED: " + mbean.getClass().getName() +
" -> " + immutableValue);
return false;
} else {
System.out.println("OK: " + mbean.getClass().getName());
return true;
}
}
public static void main(String[] args) throws Exception {
// Instantiate the MBean server
//
final MBeanAttributeInfo[] atts = makeAttInfos(attributes);
final MBeanConstructorInfo[] ctors = makeCtorInfos(constructors);
final MBeanOperationInfo[] ops = makeOpInfos(operations);
final MBeanNotificationInfo[] notifs =
makeNotifInfos(notificationclasses);
for (int i=0; i<mbeanclasses.length;i++) {
System.out.println("Create an MBeanInfo: " + mbeanclasses[i][0]);
final MBeanInfo mbi =
new MBeanInfo(mbeanclasses[i][1],mbeanclasses[i][0],
atts, ctors, ops, notifs);
}
// Test OK!
//
System.out.println("All MBeanInfo successfuly created!");
System.out.println("Bye! Bye!");
}
/**
* Invoke an operation
* @param name The bean name
* @param index The method index
* @param args The arguments
* @return The result
* @exception JMException Thrown if an error occurs
*/
public static OpResultInfo invokeOp(String name, int index, String[] args) throws JMException
{
MBeanServer server = getMBeanServer();
ObjectName objName = new ObjectName(name);
MBeanInfo info = server.getMBeanInfo(objName);
MBeanOperationInfo[] opInfo = info.getOperations();
MBeanOperationInfo op = opInfo[index];
MBeanParameterInfo[] paramInfo = op.getSignature();
String[] argTypes = new String[paramInfo.length];
for (int p = 0; p < paramInfo.length; p++)
argTypes[p] = paramInfo[p].getType();
return invokeOpByName(name, op.getName(), argTypes, args);
}
/**
* Gets the attribute name value map.
*
* @param objName
* the obj name
* @return the attribute name value map
*/
public Map<String, Object> getAttributes(ObjectName objName) {
Map<String, Object> attrMap = null;
try {
MBeanInfo mbeanInfo = mbeanServerConnection.getMBeanInfo(objName);
MBeanAttributeInfo[] mbeanAttributeInfo = mbeanInfo.getAttributes();
attrMap = new HashMap<String, Object>();
DecimalFormat df = new DecimalFormat("###.##");
for (int i = 0; i < mbeanAttributeInfo.length; i++) {
String attrName = mbeanAttributeInfo[i].getName();
Object attrValue = getAttribute(objName,
mbeanAttributeInfo[i].getName());
if (mbeanAttributeInfo[i].getType().equals("double")) {
attrValue = df.format((Double) getAttribute(objName,
mbeanAttributeInfo[i].getName()));
}
attrMap.put(attrName, attrValue);
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
return attrMap;
}
private ModelNode getInfo(ObjectName objectName) {
MBeanServerConnection connection = getConnection();
ModelNode attributes = null;
ModelNode headers = null;
Exception exception = null;
try {
MBeanInfo mBeanInfo = connection.getMBeanInfo(objectName);
MBeanAttributeInfo[] attributeInfos = mBeanInfo.getAttributes();
ModelNode[] data = modelNodeAttributesInfo(attributeInfos, objectName);
attributes = data[0];
headers = data[1];
} catch (Exception e) {
if (e instanceof JMException || e instanceof JMRuntimeException) {
exception = e;
} else {
throw new RuntimeException(e);
}
}
return modelNodeResult(attributes, exception, headers);
}
final PerInterface<M> getPerInterface(Class<?> mbeanInterface)
throws NotCompliantMBeanException {
PerInterfaceMap<M> map = getPerInterfaceMap();
synchronized (map) {
WeakReference<PerInterface<M>> wr = map.get(mbeanInterface);
PerInterface<M> pi = (wr == null) ? null : wr.get();
if (pi == null) {
try {
MBeanAnalyzer<M> analyzer = getAnalyzer(mbeanInterface);
MBeanInfo mbeanInfo =
makeInterfaceMBeanInfo(mbeanInterface, analyzer);
pi = new PerInterface<M>(mbeanInterface, this, analyzer,
mbeanInfo);
wr = new WeakReference<PerInterface<M>>(pi);
map.put(mbeanInterface, wr);
} catch (Exception x) {
throw Introspector.throwException(mbeanInterface,x);
}
}
return pi;
}
}
@Override
public MBeanInfo getMBeanInfo() {
MBeanAttributeInfo[] mbeanAttributes = new MBeanAttributeInfo[attributes.size()];
int i = 0;
for (Map.Entry<String, Object> entry : attributes.entrySet()) {
String attrName = entry.getKey();
Object attrValue = entry.getValue();
String typeName = (attrValue instanceof Number)
? Number.class.getName()
: String.class.getName();
boolean isReadable = true;
boolean isWritable = false;
boolean isIs = false;
mbeanAttributes[i++] = new MBeanAttributeInfo(
attrName, typeName, "???", isReadable, isWritable, isIs);
}
return new MBeanInfo(getClass().getName(), "???", mbeanAttributes, null, null, null);
}
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 MBeanInfo testMBeanForDatasource() throws Exception {
Map<String, String[]> env = new HashMap<>();
String[] credentials = { "admin", "admin" };
env.put(JMXConnector.CREDENTIALS, credentials);
try {
String url = "service:jmx:rmi://localhost:12311/jndi/rmi://localhost:11199/jmxrmi";
JMXServiceURL jmxUrl = new JMXServiceURL(url);
JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxUrl, env);
MBeanServerConnection mBeanServer = jmxConnector.getMBeanServerConnection();
ObjectName mbeanObject = new ObjectName(dataSourceName + ",-1234:type=DataSource");
MBeanInfo mBeanInfo = mBeanServer.getMBeanInfo(mbeanObject);
return mBeanInfo;
} catch (MalformedURLException | MalformedObjectNameException | IntrospectionException |
ReflectionException e) {
throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
}
}
/**
* Return the MBeanInfo for the given resource, based on the given
* per-interface data.
*/
final MBeanInfo getMBeanInfo(Object resource, PerInterface<M> perInterface) {
MBeanInfo mbi =
getClassMBeanInfo(resource.getClass(), perInterface);
MBeanNotificationInfo[] notifs = findNotifications(resource);
if (notifs == null || notifs.length == 0)
return mbi;
else {
return new MBeanInfo(mbi.getClassName(),
mbi.getDescription(),
mbi.getAttributes(),
mbi.getConstructors(),
mbi.getOperations(),
notifs,
mbi.getDescriptor());
}
}
final PerInterface<M> getPerInterface(Class<?> mbeanInterface)
throws NotCompliantMBeanException {
PerInterfaceMap<M> map = getPerInterfaceMap();
synchronized (map) {
WeakReference<PerInterface<M>> wr = map.get(mbeanInterface);
PerInterface<M> pi = (wr == null) ? null : wr.get();
if (pi == null) {
try {
MBeanAnalyzer<M> analyzer = getAnalyzer(mbeanInterface);
MBeanInfo mbeanInfo =
makeInterfaceMBeanInfo(mbeanInterface, analyzer);
pi = new PerInterface<M>(mbeanInterface, this, analyzer,
mbeanInfo);
wr = new WeakReference<PerInterface<M>>(pi);
map.put(mbeanInterface, wr);
} catch (Exception x) {
throw Introspector.throwException(mbeanInterface,x);
}
}
return pi;
}
}
/**
* Queries for all MBeans from the MBean Server and only looks at the relevant MBean and gets its
* metric numbers.
*/
private void extractMetrics() {
try {
QueryExp exp = Query.match(Query.attr("SensorName"), Query.value(CLUSTER_NAME + ".Job.*"));
Set<ObjectInstance> mbeans = new HashSet<>(
ManagementFactory.getPlatformMBeanServer().queryMBeans(new ObjectName("ClusterStatus:*"), exp));
for (ObjectInstance instance : mbeans) {
ObjectName beanName = instance.getObjectName();
if (instance.getClassName().endsWith("JobMonitor")) {
MBeanInfo info = _server.getMBeanInfo(beanName);
MBeanAttributeInfo[] infos = info.getAttributes();
for (MBeanAttributeInfo infoItem : infos) {
Object val = _server.getAttribute(beanName, infoItem.getName());
_beanValueMap.put(infoItem.getName(), val);
}
}
}
} catch (Exception e) {
// update failed
}
}
private static boolean test(Object mbean, boolean expectImmutable)
throws Exception {
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
ObjectName on = new ObjectName("a:b=c");
mbs.registerMBean(mbean, on);
MBeanInfo mbi = mbs.getMBeanInfo(on);
Descriptor d = mbi.getDescriptor();
String immutableValue = (String) d.getFieldValue("immutableInfo");
boolean immutable = ("true".equals(immutableValue));
if (immutable != expectImmutable) {
System.out.println("FAILED: " + mbean.getClass().getName() +
" -> " + immutableValue);
return false;
} else {
System.out.println("OK: " + mbean.getClass().getName());
return true;
}
}
public static void main(String[] args) throws Exception {
// Instantiate the MBean server
//
final MBeanAttributeInfo[] atts = makeAttInfos(attributes);
final MBeanConstructorInfo[] ctors = makeCtorInfos(constructors);
final MBeanOperationInfo[] ops = makeOpInfos(operations);
final MBeanNotificationInfo[] notifs =
makeNotifInfos(notificationclasses);
for (int i=0; i<mbeanclasses.length;i++) {
System.out.println("Create an MBeanInfo: " + mbeanclasses[i][0]);
final MBeanInfo mbi =
new MBeanInfo(mbeanclasses[i][1],mbeanclasses[i][0],
atts, ctors, ops, notifs);
}
// Test OK!
//
System.out.println("All MBeanInfo successfuly created!");
System.out.println("Bye! Bye!");
}
final PerInterface<M> getPerInterface(Class<?> mbeanInterface)
throws NotCompliantMBeanException {
PerInterfaceMap<M> map = getPerInterfaceMap();
synchronized (map) {
WeakReference<PerInterface<M>> wr = map.get(mbeanInterface);
PerInterface<M> pi = (wr == null) ? null : wr.get();
if (pi == null) {
try {
MBeanAnalyzer<M> analyzer = getAnalyzer(mbeanInterface);
MBeanInfo mbeanInfo =
makeInterfaceMBeanInfo(mbeanInterface, analyzer);
pi = new PerInterface<M>(mbeanInterface, this, analyzer,
mbeanInfo);
wr = new WeakReference<PerInterface<M>>(pi);
map.put(mbeanInterface, wr);
} catch (Exception x) {
throw Introspector.throwException(mbeanInterface,x);
}
}
return pi;
}
}
private void registerAndVerifyMBean(MBeanServer mbs) {
try {
ObjectName myInfoObj = new ObjectName("com.alibaba.tenant.mxbean:type=MyTest");
MXBeanImpl myMXBean = new MXBeanImpl();
StandardMBean smb = new StandardMBean(myMXBean, MXBean.class);
mbs.registerMBean(smb, myInfoObj);
assertTrue(mbs.isRegistered(myInfoObj));
//call the method of MXBean
MXBean mbean =
(MXBean)MBeanServerInvocationHandler.newProxyInstance(
mbs,new ObjectName("com.alibaba.tenant.mxbean:type=MyTest"), MXBean.class, true);
assertTrue("test".equals(mbean.getName()));
Set<ObjectInstance> instances = mbs.queryMBeans(new ObjectName("com.alibaba.tenant.mxbean:type=MyTest"), null);
ObjectInstance instance = (ObjectInstance) instances.toArray()[0];
assertTrue(myMXBean.getClass().getName().equals(instance.getClassName()));
MBeanInfo info = mbs.getMBeanInfo(myInfoObj);
assertTrue(myMXBean.getClass().getName().equals(info.getClassName()));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
private void listMetaData(CommandProcess process) {
Set<ObjectName> objectNames = queryObjectNames();
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
try {
TableElement table = createTable();
for (ObjectName objectName : objectNames) {
MBeanInfo mBeanInfo = mBeanServer.getMBeanInfo(objectName);
drawMetaInfo(mBeanInfo, objectName, table);
drawAttributeInfo(mBeanInfo.getAttributes(), table);
drawOperationInfo(mBeanInfo.getOperations(), table);
drawNotificationInfo(mBeanInfo.getNotifications(), table);
}
process.write(RenderUtil.render(table, process.width()));
} catch (Throwable e) {
logger.warn("listMetaData error", e);
} finally {
process.end();
}
}
/**
* Call <code>checkRead()</code>, then forward this method to the
* wrapped object.
*/
public MBeanInfo getMBeanInfo(ObjectName name)
throws
InstanceNotFoundException,
IntrospectionException,
ReflectionException {
checkRead();
return getMBeanServer().getMBeanInfo(name);
}
private int checkNonEmpty(MBeanInfo mbi) {
if ( mbi.toString().length() == 0 ) {
System.out.println("(ERROR) MBeanInfo is empty !");
return 1;
} else {
return 0;
}
}
@Test
public void testRegisterOperations() throws Exception {
IJmxTestBean bean = getBean();
assertNotNull(bean);
MBeanInfo inf = getMBeanInfo();
assertEquals("Incorrect number of operations registered",
getExpectedOperationCount(), inf.getOperations().length);
}
private void set(final String cmd) {
final String[] split = cmd.split(" ");
if (split.length < 2) {
streamManager.writeErr("you need to specify an attribute, an objectname and a value");
return;
}
final MBeanServer mBeanServer = LocalMBeanServer.get();
final String newValue = cmd.substring(split[0].length() + split[1].length() + 1).trim();
try {
final ObjectName oname = new ObjectName(split[1]);
final MBeanInfo minfo = mBeanServer.getMBeanInfo(oname);
final MBeanAttributeInfo attrs[] = minfo.getAttributes();
String type = String.class.getName();
for (int i = 0; i < attrs.length; i++) {
if (attrs[i].getName().equals(split[0])) {
type = attrs[i].getType();
break;
}
}
final Object valueObj = propertyEditorRegistry.getValue(type, newValue, Thread.currentThread().getContextClassLoader());
mBeanServer.setAttribute(oname, new Attribute(split[0], valueObj));
streamManager.writeOut("done");
} catch (Exception ex) {
streamManager.writeOut("Error - " + ex.toString());
}
}
@Override
public MBeanInfo getMBeanInfo() {
MBeanAttributeInfo attr = new MBeanAttributeInfo("name", "java.lang.String", "", true, false, false);
return new MBeanInfo(
TestDynamicMBean.class.getName(), "",
new MBeanAttributeInfo[]{attr},
new MBeanConstructorInfo[0],
new MBeanOperationInfo[0],
new MBeanNotificationInfo[0]);
}
@Before
public void setUp() throws Exception {
mockDisruptorConfig = createMock(DefaultDisruptorConfig.class);
mockMBeanInfo = createMock(MBeanInfo.class);
mockMBeanAttribute = createMock(MBeanAttributeInfo.class);
mockMBeanOperation = createMock(MBeanOperationInfo.class);
mockMBeanParameterInfo = createMock(MBeanParameterInfo.class);
jmxDisruptor = new JmxDisruptor(mockDisruptorConfig, "disruptorBean");
assertNotNull(mockDisruptorConfig);
}
private final int doMemoryManagerMXBeanTest(MBeanServerConnection mbsc) {
int errorCount = 0 ;
System.out.println("---- MemoryManagerMXBean") ;
try {
ObjectName filterName =
new ObjectName(ManagementFactory.MEMORY_MANAGER_MXBEAN_DOMAIN_TYPE
+ ",*");
Set<ObjectName> onSet = mbsc.queryNames(filterName, null);
for (Iterator<ObjectName> iter = onSet.iterator(); iter.hasNext(); ) {
ObjectName memoryManagerName = iter.next() ;
System.out.println("-------- " + memoryManagerName) ;
MBeanInfo mbInfo = mbsc.getMBeanInfo(memoryManagerName);
System.out.println("getMBeanInfo\t\t" + mbInfo);
errorCount += checkNonEmpty(mbInfo);
MemoryManagerMXBean memoryManager = null;
memoryManager =
JMX.newMXBeanProxy(mbsc,
memoryManagerName,
MemoryManagerMXBean.class) ;
System.out.println("getMemoryPoolNames\t\t"
+ Arrays.deepToString(memoryManager.getMemoryPoolNames()));
System.out.println("getName\t\t"
+ memoryManager.getName());
System.out.println("isValid\t\t"
+ memoryManager.isValid());
}
System.out.println("---- OK\n") ;
} catch (Exception e) {
Utils.printThrowable(e, true) ;
errorCount++ ;
System.out.println("---- ERROR\n") ;
}
return errorCount ;
}
/**
* Returns the attributes, operations, constructors and notifications
* that this RequiredModelMBean exposes for management.
*
* @return An instance of ModelMBeanInfo allowing retrieval all
* attributes, operations, and Notifications of this MBean.
*
**/
public MBeanInfo getMBeanInfo() {
if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
MODELMBEAN_LOGGER.logp(Level.FINER,
RequiredModelMBean.class.getName(),
"getMBeanInfo()","Entry");
}
if (modelMBeanInfo == null) {
if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
MODELMBEAN_LOGGER.logp(Level.FINER,
RequiredModelMBean.class.getName(),
"getMBeanInfo()","modelMBeanInfo is null");
}
modelMBeanInfo = createDefaultModelMBeanInfo();
//return new ModelMBeanInfo(" ", "", null, null, null, null);
}
if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
MODELMBEAN_LOGGER.logp(Level.FINER,
RequiredModelMBean.class.getName(),
"getMBeanInfo()","ModelMBeanInfo is " +
modelMBeanInfo.getClassName() + " for " +
modelMBeanInfo.getDescription());
MODELMBEAN_LOGGER.logp(Level.FINER,
RequiredModelMBean.class.getName(),
"getMBeanInfo()",printModelMBeanInfo(modelMBeanInfo));
}
return((MBeanInfo) modelMBeanInfo.clone());
}
PerInterface(Class<?> mbeanInterface, MBeanIntrospector<M> introspector,
MBeanAnalyzer<M> analyzer, MBeanInfo mbeanInfo) {
this.mbeanInterface = mbeanInterface;
this.introspector = introspector;
this.mbeanInfo = mbeanInfo;
analyzer.visit(new InitMaps());
}
private static void check(MBeanServer mbs, ObjectName on) throws Exception {
MBeanInfo mbi = mbs.getMBeanInfo(on);
// check the MBean itself
check(mbi);
// check attributes
MBeanAttributeInfo[] attrs = mbi.getAttributes();
for (MBeanAttributeInfo attr : attrs) {
check(attr);
if (attr.getName().equals("ReadOnly"))
check("@Full", attr.getDescriptor(), expectedFullDescriptor);
}
// check operations
MBeanOperationInfo[] ops = mbi.getOperations();
for (MBeanOperationInfo op : ops) {
check(op);
check(op.getSignature());
}
MBeanConstructorInfo[] constrs = mbi.getConstructors();
for (MBeanConstructorInfo constr : constrs) {
check(constr);
check(constr.getSignature());
}
}
/**
* Call <code>checkRead()</code>, then forward this method to the
* wrapped object.
*/
public MBeanInfo getMBeanInfo(ObjectName name)
throws
InstanceNotFoundException,
IntrospectionException,
ReflectionException {
checkRead();
return getMBeanServer().getMBeanInfo(name);
}
private final int doClassLoadingMXBeanTest(MBeanServerConnection mbsc) {
int errorCount = 0 ;
System.out.println("---- ClassLoadingMXBean") ;
try {
ObjectName classLoadingName =
new ObjectName(ManagementFactory.CLASS_LOADING_MXBEAN_NAME) ;
MBeanInfo mbInfo = mbsc.getMBeanInfo(classLoadingName);
errorCount += checkNonEmpty(mbInfo);
System.out.println("getMBeanInfo\t\t"
+ mbInfo);
ClassLoadingMXBean classLoading = null;
classLoading = JMX.newMXBeanProxy(mbsc,
classLoadingName,
ClassLoadingMXBean.class) ;
System.out.println("getLoadedClassCount\t\t"
+ classLoading.getLoadedClassCount());
System.out.println("getTotalLoadedClassCount\t\t"
+ classLoading.getTotalLoadedClassCount());
System.out.println("getUnloadedClassCount\t\t"
+ classLoading.getUnloadedClassCount());
System.out.println("isVerbose\t\t"
+ classLoading.isVerbose());
System.out.println("---- OK\n") ;
} catch (Exception e) {
Utils.printThrowable(e, true) ;
errorCount++ ;
System.out.println("---- ERROR\n") ;
}
return errorCount ;
}