下面列出了怎么用javax.management.MBeanAttributeInfo的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
}
}
public void printAllMatchedAttributes(String attrRegExp) throws Exception {
err("List of the keys matching " + attrRegExp + " :");
Object val = null;
Pattern p = Pattern.compile(attrRegExp);
for (ObjectName oname : hadoopObjectNames) {
err(">>>>>>>>jmx name: " + oname.getCanonicalKeyPropertyListString());
MBeanInfo mbinfo = mbsc.getMBeanInfo(oname);
MBeanAttributeInfo[] mbinfos = mbinfo.getAttributes();
for (MBeanAttributeInfo mb : mbinfos) {
if (p.matcher(mb.getName()).lookingAt()) {
val = mbsc.getAttribute(oname, mb.getName());
System.out.format(format, mb.getName(), (val == null) ? "" : val.toString());
}
}
}
}
/**
* 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;
}
/** Get the type of an attribute of the object, from the metadata.
*
* @param oname
* @param attName
* @return null if metadata about the attribute is not found
* @since 1.1
*/
public String getType( ObjectName oname, String attName )
{
String type=null;
MBeanInfo info=null;
try {
info=server.getMBeanInfo(oname);
} catch (Exception e) {
log.info( "Can't find metadata for object" + oname );
return null;
}
MBeanAttributeInfo attInfo[]=info.getAttributes();
for( int i=0; i<attInfo.length; i++ ) {
if( attName.equals(attInfo[i].getName())) {
type=attInfo[i].getType();
return type;
}
}
return null;
}
/**
* print all attributes' values
*/
public void printAllValues() throws Exception {
err("List of all the available keys:");
Object val = null;
for (ObjectName oname : hadoopObjectNames) {
err(">>>>>>>>jmx name: " + oname.getCanonicalKeyPropertyListString());
MBeanInfo mbinfo = mbsc.getMBeanInfo(oname);
MBeanAttributeInfo[] mbinfos = mbinfo.getAttributes();
for (MBeanAttributeInfo mb : mbinfos) {
val = mbsc.getAttribute(oname, mb.getName());
System.out.format(format, mb.getName(), (val==null)?"":val.toString());
}
}
}
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);
}
@Override
public Map<String, Object> getStatistics() {
try {
MBeanInfo mBeanInfo = getConnection().getMBeanInfo(getMbeanName());
String[] statAttrs = Arrays.asList(mBeanInfo.getAttributes()).stream()
.filter(MBeanAttributeInfo::isReadable)
.map(MBeanAttributeInfo::getName)
.collect(Collectors.toList())
.toArray(new String[] {});
return getConnection().getAttributes(getMbeanName(), statAttrs)
.asList()
.stream()
.collect(Collectors.toMap(Attribute::getName, Attribute::getValue));
} catch (IOException | InstanceNotFoundException | ReflectionException | IntrospectionException ex) {
throw new RuntimeException(ex);
}
}
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!");
}
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!");
}
private MBeanInfo createMBeanInfo() {
Collection<Counter> counters = counterMap.values();
List<MBeanAttributeInfo> attributes = new ArrayList<>(counters.size());
for (Counter c : counters) {
if (!c.isVector()) {
String typeName = "java.lang.String";
synchronized (c) {
Object value = c.getValue();
if (value != null) {
typeName = value.getClass().getName();
}
}
attributes.add(new MBeanAttributeInfo(c.getName(), typeName,
String.format("%s [%s,%s]", c.getName(), c.getUnits(), c.getVariability()), true, false,
false));
}
}
MBeanAttributeInfo[] attributesArray = attributes.toArray(new MBeanAttributeInfo[attributes.size()]);
return new MBeanInfo(this.getClass().getName(),
"An MBean exposing the available JVM Performance Counters as attributes.", attributesArray, null, null,
null);
}
private void printMBeanInfo(MBeanInfo mbInfo) {
System.out.println("Description " + mbInfo.getDescription());
for (MBeanConstructorInfo ctor : mbInfo.getConstructors()) {
System.out.println("Constructor " + ctor.getName());
}
for (MBeanAttributeInfo att : mbInfo.getAttributes()) {
System.out.println("Attribute " + att.getName()
+ " [" + att.getType() + "]");
}
for (MBeanOperationInfo oper : mbInfo.getOperations()) {
System.out.println("Operation " + oper.getName());
}
for (MBeanNotificationInfo notif : mbInfo.getNotifications()) {
System.out.println("Notification " + notif.getName());
}
}
/**
* print all attributes' values
*/
public void printAllValues() throws Exception {
err("List of all the available keys:");
Object val = null;
for (ObjectName oname : hadoopObjectNames) {
err(">>>>>>>>jmx name: " + oname.getCanonicalKeyPropertyListString());
MBeanInfo mbinfo = mbsc.getMBeanInfo(oname);
MBeanAttributeInfo[] mbinfos = mbinfo.getAttributes();
for (MBeanAttributeInfo mb : mbinfos) {
val = mbsc.getAttribute(oname, mb.getName());
System.out.format(format, mb.getName(), (val==null)?"":val.toString());
}
}
}
@Test
public void testHappyPath() throws MalformedObjectNameException, JMException {
TestMbean testMbean = new TestMbean();
ModelMBean mbean = defaultManagementMBeanAssembler.assemble(testMbean, new ObjectName("org.activiti.jmx.Mbeans:type=something"));
assertNotNull(mbean);
assertNotNull(mbean.getMBeanInfo());
assertNotNull(mbean.getMBeanInfo().getAttributes());
MBeanAttributeInfo[] attributes = mbean.getMBeanInfo().getAttributes();
assertEquals(2, attributes.length);
assertTrue((attributes[0].getName().equals("TestAttributeString") && attributes[1].getName().equals("TestAttributeBoolean") || (attributes[1].getName().equals("TestAttributeString") && attributes[0]
.getName().equals("TestAttributeBoolean"))));
assertNotNull(mbean.getMBeanInfo().getOperations());
MBeanOperationInfo[] operations = mbean.getMBeanInfo().getOperations();
assertNotNull(operations);
assertEquals(3, operations.length);
}
@Test
public void returnsInfoAboutWritableAttributesInMBeanInfo() {
MBeanWithSettableAttributes settableMBean = new MBeanWithSettableAttributes(10, 20, "data");
DynamicMBean mbean = createDynamicMBeanFor(settableMBean);
MBeanInfo mBeanInfo = mbean.getMBeanInfo();
MBeanAttributeInfo[] attributesInfoArr = mBeanInfo.getAttributes();
Map<String, MBeanAttributeInfo> nameToAttr = nameToAttribute(attributesInfoArr);
assertEquals(3, nameToAttr.size());
assertTrue(nameToAttr.containsKey("notSettableInt"));
assertFalse(nameToAttr.get("notSettableInt").isWritable());
assertTrue(nameToAttr.containsKey("settableInt"));
assertTrue(nameToAttr.get("settableInt").isWritable());
assertTrue(nameToAttr.containsKey("settableStr"));
assertTrue(nameToAttr.get("settableStr").isWritable());
}
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!");
}
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);
}
}
}
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!");
}
@Test
public void testHappyPath() throws MalformedObjectNameException, JMException {
TestMbean testMbean = new TestMbean();
ModelMBean mbean = defaultManagementMBeanAssembler.assemble(testMbean, new ObjectName("org.flowable.jmx.Mbeans:type=something"));
assertNotNull(mbean);
assertNotNull(mbean.getMBeanInfo());
assertNotNull(mbean.getMBeanInfo().getAttributes());
MBeanAttributeInfo[] attributes = mbean.getMBeanInfo().getAttributes();
assertEquals(2, attributes.length);
assertTrue((attributes[0].getName().equals("TestAttributeString") && attributes[1].getName().equals("TestAttributeBoolean") || (attributes[1].getName().equals("TestAttributeString") && attributes[0]
.getName().equals("TestAttributeBoolean"))));
assertNotNull(mbean.getMBeanInfo().getOperations());
MBeanOperationInfo[] operations = mbean.getMBeanInfo().getOperations();
assertNotNull(operations);
assertEquals(3, operations.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());
}
}
public cfData execute( cfSession _session, List<cfData> parameters )throws cfmRunTimeException{
String domain = parameters.get(1).getString();
String type = parameters.get(0).getString();
cfStructData s = new cfStructData();
try {
MBeanServerConnection mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name = new ObjectName( domain + ":type=" + type );
MBeanInfo meanInfo = mbs.getMBeanInfo( name );
MBeanAttributeInfo[] mbeanAttributeInfo = meanInfo.getAttributes();
for ( int x=0; x < mbeanAttributeInfo.length; x++ ){
try{
String key = mbeanAttributeInfo[x].getName();
String dat = mbs.getAttribute( name, mbeanAttributeInfo[x].getName() ).toString();
s.setData( key, new cfStringData(dat) );
}catch(Exception ignore){}
}
} catch (Exception e) {
throwException( _session, "Failed to retrieve the attributes: " + e.getMessage() );
}
return s;
}
/**
* Deserializes a {@link ModelMBeanInfoSupport} from an {@link ObjectInputStream}.
*/
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
if (compat) {
// Read an object serialized in the old serial form
//
ObjectInputStream.GetField fields = in.readFields();
modelMBeanDescriptor =
(Descriptor) fields.get("modelMBeanDescriptor", null);
if (fields.defaulted("modelMBeanDescriptor")) {
throw new NullPointerException("modelMBeanDescriptor");
}
modelMBeanAttributes =
(MBeanAttributeInfo[]) fields.get("mmbAttributes", null);
if (fields.defaulted("mmbAttributes")) {
throw new NullPointerException("mmbAttributes");
}
modelMBeanConstructors =
(MBeanConstructorInfo[]) fields.get("mmbConstructors", null);
if (fields.defaulted("mmbConstructors")) {
throw new NullPointerException("mmbConstructors");
}
modelMBeanNotifications =
(MBeanNotificationInfo[]) fields.get("mmbNotifications", null);
if (fields.defaulted("mmbNotifications")) {
throw new NullPointerException("mmbNotifications");
}
modelMBeanOperations =
(MBeanOperationInfo[]) fields.get("mmbOperations", null);
if (fields.defaulted("mmbOperations")) {
throw new NullPointerException("mmbOperations");
}
} else {
// Read an object serialized in the new serial form
//
in.defaultReadObject();
}
}
@Test
public void testNickNameIsExposed() throws Exception {
ModelMBeanInfo inf = (ModelMBeanInfo) getMBeanInfo();
MBeanAttributeInfo attr = inf.getAttribute("NickName");
assertNickName(attr);
}
@Test
public void testNickNameIsExposed() throws Exception {
ModelMBeanInfo inf = (ModelMBeanInfo) getMBeanInfo();
MBeanAttributeInfo attr = inf.getAttribute("NickName");
assertNotNull("Nick Name should not be null", attr);
assertTrue("Nick Name should be writable", attr.isWritable());
assertTrue("Nick Name should be readable", attr.isReadable());
}
private MBeanNode getMBeanNode(ObjectName name) throws JMException {
final String mbeanName = name.toString();
final MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo(name);
final String description = formatDescription(mbeanInfo.getDescription());
final MBeanAttributeInfo[] attributeInfos = mbeanInfo.getAttributes();
final List<MBeanAttribute> attributes = getAttributes(name, attributeInfos);
// les attributs seront triés par ordre alphabétique dans getMBeanNodes
return new MBeanNode(mbeanName, description, attributes);
}
private void appendMbeanInformation( Map<String, List<MbeanAttributeModel>> mbeans, String selector ) throws Exception{
Set<ObjectName> foundObjectNames = mbeanServer.queryNames( new ObjectName( selector ), null );
for( ObjectName objectName : foundObjectNames ){
MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo( objectName );
String name = objectName.getKeyProperty( "name" );
if( name == null || mbeans.containsKey(name) ){
name = name + ":" + mbeanInfo.getDescription();
}
List<MbeanAttributeModel> attributes = new ArrayList<>();
mbeans.put( name, attributes );
for( MBeanAttributeInfo attributeInfo : mbeanInfo.getAttributes() ){
MbeanAttributeModel attribute = new MbeanAttributeModel();
attribute.setName( attributeInfo.getName() );
attribute.setDescription( attributeInfo.getDescription() );
Object attr = null;
try {
attr = mbeanServer.getAttribute(objectName, attribute.getName());
} catch (JMException jme) {
log.warn("Error while getting attribute \"" + attribute.getName() + "\", ignoring, " + jme.getMessage());
}
attribute.setValue( attr );
attributes.add( attribute );
}
}
}
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());
}
}
/**
* Description of the specified attribute name.
*
* @param attributeName - stringified name of the attribute
* @return the description
*/
public String describeAttribute(String attributeName) {
String ret = "Attribute not found";
try {
MBeanAttributeInfo[] attributes = beanInfo.getAttributes();
for (MBeanAttributeInfo attribute : attributes) {
if (attribute.getName().equals(attributeName)) {
return describeAttribute(attribute);
}
}
} catch (Exception e) {
throwException("Could not describe attribute '" + attributeName + "'. Reason: ", e);
}
return ret;
}
@Test
public void testNickNameIsExposed() throws Exception {
ModelMBeanInfo inf = (ModelMBeanInfo) getMBeanInfo();
MBeanAttributeInfo attr = inf.getAttribute("NickName");
assertNickName(attr);
}
/**
* Deserializes a {@link ModelMBeanInfoSupport} from an {@link ObjectInputStream}.
*/
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
if (compat) {
// Read an object serialized in the old serial form
//
ObjectInputStream.GetField fields = in.readFields();
modelMBeanDescriptor =
(Descriptor) fields.get("modelMBeanDescriptor", null);
if (fields.defaulted("modelMBeanDescriptor")) {
throw new NullPointerException("modelMBeanDescriptor");
}
modelMBeanAttributes =
(MBeanAttributeInfo[]) fields.get("mmbAttributes", null);
if (fields.defaulted("mmbAttributes")) {
throw new NullPointerException("mmbAttributes");
}
modelMBeanConstructors =
(MBeanConstructorInfo[]) fields.get("mmbConstructors", null);
if (fields.defaulted("mmbConstructors")) {
throw new NullPointerException("mmbConstructors");
}
modelMBeanNotifications =
(MBeanNotificationInfo[]) fields.get("mmbNotifications", null);
if (fields.defaulted("mmbNotifications")) {
throw new NullPointerException("mmbNotifications");
}
modelMBeanOperations =
(MBeanOperationInfo[]) fields.get("mmbOperations", null);
if (fields.defaulted("mmbOperations")) {
throw new NullPointerException("mmbOperations");
}
} else {
// Read an object serialized in the new serial form
//
in.defaultReadObject();
}
}
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));
}