-
Standard MBean
package com.test.mbean;
public class HelloWorld implements HelloWorldMBean {
private String greeting = null;
public HelloWorld() {
this.greeting = "Hello World! I am a Standard MBean";
}
public HelloWorld(String greeting) {
this.greeting = greeting;
}
public void setGreeting(String greeting) {
this.greeting = greeting;
}
public String getGreeting() {
return greeting;
}
public void printGreeting() {
System.out.println(greeting);
}
}
package com.test.mbean;
public interface HelloWorldMBean {
public void setGreeting( String greeting );
public String getGreeting();
public void printGreeting();
}
package com.test.mbean;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import com.sun.jdmk.comm.HtmlAdaptorServer;
public class HelloAgent {
private MBeanServer mbs = null;
public HelloAgent() throws Exception{
mbs = MBeanServerFactory.createMBeanServer("HelloAgent");
HtmlAdaptorServer adapter = new HtmlAdaptorServer();
HelloWorld hw = new HelloWorld();
ObjectName adapterName = null;
ObjectName helloWorldName = null;
helloWorldName = new ObjectName("HelloAgent:name=helloWorld1");
mbs.registerMBean(hw, helloWorldName);
adapterName = new ObjectName("HelloAgent:name=htmladapter,port=9092");
adapter.setPort(9092);
mbs.registerMBean(adapter, adapterName);
adapter.start();
}
public static void main(String[] args) throws Exception{
System.out.println("Hello Agent is running");
HelloAgent agent = new HelloAgent();
}
}
-
notification
package com.test.mbean.Notification;
public interface HelloWorldMBean {
public void setGreeting( String greeting );
public String getGreeting();
public void printGreeting();
}
package com.test.mbean.Notification;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
public class HelloWorld extends NotificationBroadcasterSupport implements
HelloWorldMBean {
public HelloWorld() {
this.greeting = "Hello World! I am a Standard MBean";
}
public HelloWorld(String greeting) {
this.greeting = greeting;
}
public void setGreeting(String greeting) {
this.greeting = greeting;
Notification notification = new Notification(
"com.test.mbean.Notification", this, -1,
System.currentTimeMillis(), greeting);
sendNotification(notification);
}
public String getGreeting() {
return greeting;
}
public void printGreeting() {
System.out.println(greeting);
}
private String greeting;
}
package com.test.mbean.Notification;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import com.sun.jdmk.comm.HtmlAdaptorServer;
public class HelloAgent implements NotificationListener {
private MBeanServer mbs = null;
public HelloAgent() {
mbs = MBeanServerFactory.createMBeanServer("HelloWorld");
HtmlAdaptorServer adapter = new HtmlAdaptorServer();
HelloWorld hw = new HelloWorld();
ObjectName adapterName = null;
ObjectName helloWorldName = null;
try {
adapterName = new ObjectName(
"HelloAgent:name=htmladapter,port=9092");
mbs.registerMBean(adapter, adapterName);
adapter.setPort(9092);
adapter.start();
helloWorldName = new ObjectName("HelloAgent:name=helloWorld1");
mbs.registerMBean(hw, helloWorldName);
hw.addNotificationListener(this, null, null);
} catch (Exception e) {
e.printStackTrace();
}
}// constructor
public void handleNotification(Notification notif, Object handback) {
System.out.println("Receiving notification...");
System.out.println(notif.getType());
System.out.println(notif.getMessage());
}
public static void main(String args[]) {
HelloAgent agent = new HelloAgent();
}
}
设置Greeting时,触发Notification
-
dynamic MBean
package com.test.mbean.dynamic;
public class SimpleDynamic implements DynamicMBean {
public SimpleDynamic() {
// 建立辅助信息
//
buildDynamicMBeanInfo();
}
public Object getAttribute(String attribute_name)
throws AttributeNotFoundException, MBeanException,
ReflectionException {
// 检查属性是否为空
if (attribute_name == null) {
throw new RuntimeOperationsException(new IllegalArgumentException(
"Attribute name cannot be null"),
"Cannot invoke a getter of " + dClassName
+ " with null attribute name");
}
// 检查已知属性,调用已知方法
if (attribute_name.equals("State")) {
return getState();
}
if (attribute_name.equals("NbChanges")) {
return getNbChanges();
}
// 如果属性不可识别,抛出异常
throw (new AttributeNotFoundException("Cannot find " + attribute_name
+ " attribute in " + dClassName));
}
public void setAttribute(Attribute attribute)
throws AttributeNotFoundException, InvalidAttributeValueException,
MBeanException, ReflectionException {
if (attribute == null) {
throw new RuntimeOperationsException(new IllegalArgumentException(
"Attribute cannot be null"), "Cannot invoke a setter of "
+ dClassName + " with null attribute");
}
String name = attribute.getName();
Object value = attribute.getValue();
if (name == null) {
throw new RuntimeOperationsException(new IllegalArgumentException(
"Attribute name cannot be null"),
"Cannot invoke the setter of " + dClassName
+ " with null attribute name");
}
if (name.equals("State")) {
if (value == null) {
try {
setState(null);
} catch (Exception e) {
throw (new InvalidAttributeValueException(
"Cannot set attribute " + name + " to null"));
}
} else {
try {
if ((Class.forName("java.lang.String"))
.isAssignableFrom(value.getClass())) {
setState((String) value);
} else {
throw (new InvalidAttributeValueException(
"Cannot set attribute " + name + " to a "
+ value.getClass().getName()
+ " object, String expected"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
// 由于"NbChanges" 属性是只读的,所以抛出异常
else if (name.equals("NbChanges")) {
throw (new AttributeNotFoundException("Cannot set attribute "
+ name + " because it is read-only"));
} else {
throw (new AttributeNotFoundException("Attribute " + name
+ " not found in " + this.getClass().getName()));
}
}
public AttributeList getAttributes(String[] attributeNames) {
if (attributeNames == null) {
throw new RuntimeOperationsException(new IllegalArgumentException(
"attributeNames[] cannot be null"),
"Cannot invoke a getter of " + dClassName);
}
AttributeList resultList = new AttributeList();
if (attributeNames.length == 0)
return resultList;
for (int i = 0; i < attributeNames.length; i++) {
try {
Object value = getAttribute((String) attributeNames[i]);
resultList.add(new Attribute(attributeNames[i], value));
} catch (Exception e) {
e.printStackTrace();
}
}
return (resultList);
}
public AttributeList setAttributes(AttributeList attributes) {
if (attributes == null) {
throw new RuntimeOperationsException(new IllegalArgumentException(
"AttributeList attributes cannot be null"),
"Cannot invoke a setter of " + dClassName);
}
AttributeList resultList = new AttributeList();
if (attributes.isEmpty())
return resultList;
for (Iterator i = attributes.iterator(); i.hasNext();) {
Attribute attr = (Attribute) i.next();
try {
setAttribute(attr);
String name = attr.getName();
Object value = getAttribute(name);
resultList.add(new Attribute(name, value));
} catch (Exception e) {
e.printStackTrace();
}
}
return (resultList);
}
/**
* 设置操作
*/
public Object invoke(String operationName, Object params[],
String signature[]) throws MBeanException, ReflectionException {
// 检查方法名是否为空
if (operationName == null) {
throw new RuntimeOperationsException(new IllegalArgumentException(
"Operation name cannot be null"),
"Cannot invoke a null operation in " + dClassName);
}
if (operationName.equals("reset")) {
reset();
return null;
} else {
throw new ReflectionException(new NoSuchMethodException(
operationName), "Cannot find the operation "
+ operationName + " in " + dClassName);
}
}
public MBeanInfo getMBeanInfo() {
return (dMBeanInfo);
}
/*
* ----------------------------------------------------- 下面是公共方法
* -----------------------------------------------------
*/
public String getState() {
return state;
}
public void setState(String s) {
state = s;
nbChanges++;
}
public Integer getNbChanges() {
return new Integer(nbChanges);
}
public void reset() {
state = "initial state";
nbChanges = 0;
nbResets++;
}
public Integer getNbResets() {
return new Integer(nbResets);
}
/**
* 构造辅助信息,这里用了很多辅助类,具体看规范
*/
private void buildDynamicMBeanInfo() {
dAttributes[0] = new MBeanAttributeInfo("State", "java.lang.String",
"State: state string.", true, true, false);
dAttributes[1] = new MBeanAttributeInfo(
"NbChanges",
"java.lang.Integer",
"NbChanges: number of times the State string has been changed.",
true, false, false);
Constructor[] constructors = this.getClass().getConstructors();
dConstructors[0] = new MBeanConstructorInfo(
"SimpleDynamic(): Constructs a SimpleDynamic object",
constructors[0]);
MBeanParameterInfo[] params = null;
dOperations[0] = new MBeanOperationInfo(
"reset",
"reset(): reset State and NbChanges attributes to their initial values",
params, "void", MBeanOperationInfo.ACTION);
dMBeanInfo = new MBeanInfo(dClassName, dDescription, dAttributes,
dConstructors, dOperations, new MBeanNotificationInfo[0]);
}
/*
* ----------------------------------------------------- 私有变量
* -----------------------------------------------------
*/
private String state = "initial state";
private int nbChanges = 0;
private int nbResets = 0;
private String dClassName = this.getClass().getName();
private String dDescription = "Simple implementation of a dynamic MBean.";
private MBeanAttributeInfo[] dAttributes = new MBeanAttributeInfo[2];
private MBeanConstructorInfo[] dConstructors = new MBeanConstructorInfo[1];
private MBeanOperationInfo[] dOperations = new MBeanOperationInfo[1];
private MBeanInfo dMBeanInfo = null;
}
package com.test.mbean.dynamic;
public class SimpleAgent {
public SimpleAgent() throws Exception {
// 1:创建server,注册MBean
MBeanServer server = MBeanServerFactory.createMBeanServer();
ObjectName mbeanObjectName = null;
String domain = "com.test.mbean.dynamic";//server.getDefaultDomain();
String mbeanName = "com.test.mbean.dynamic.SimpleDynamic";
mbeanObjectName = new ObjectName(domain + ":type=" + mbeanName);
server.createMBean(mbeanName, mbeanObjectName);
// 2:得到属性
String State = (String) server.getAttribute(mbeanObjectName, "State");
Integer NbChanges = (Integer) server.getAttribute(mbeanObjectName,
"NbChanges");
// 3:设置属性
// Attribute nbChangesAttribute = new Attribute("NbChanges",
// new Integer(1));
Attribute stateAttribute = new Attribute("State", "State new");
try {
server.setAttribute(mbeanObjectName, stateAttribute);
} catch (Exception e) {
e.printStackTrace();
}
// 4:执行操作
server.invoke(mbeanObjectName, "reset", null, null);
// 5:得到辅助信息
MBeanInfo info = null;
try {
info = server.getMBeanInfo(mbeanObjectName);
} catch (Exception e) {
System.out.println("\t!!! Could not get MBeanInfo object for "
+ mbeanName + " !!!");
e.printStackTrace();
return;
}
System.out.println("\nCLASSNAME: \t" + info.getClassName());
System.out.println("\nDESCRIPTION: \t" + info.getDescription());
System.out.println("\nATTRIBUTES");
MBeanAttributeInfo[] attrInfo = info.getAttributes();
if (attrInfo.length > 0) {
for (int i = 0; i < attrInfo.length; i++) {
System.out.println(" ** NAME: \t" + attrInfo[i].getName());
System.out.println(" DESCR: \t" + attrInfo[i].getDescription());
System.out.println(" TYPE: \t" + attrInfo[i].getType()
+ "\tREAD: " + attrInfo[i].isReadable() + "\tWRITE: "
+ attrInfo[i].isWritable());
}
} else
System.out.println(" ** No attributes **");
System.out.println("\nCONSTRUCTORS");
MBeanConstructorInfo[] constrInfo = info.getConstructors();
for (int i = 0; i < constrInfo.length; i++) {
System.out.println(" ** NAME: \t" + constrInfo[i].getName());
System.out.println(" DESCR: \t" + constrInfo[i].getDescription());
System.out.println(" PARAM: \t"
+ constrInfo[i].getSignature().length + " parameter(s)");
}
System.out.println("\nOPERATIONS");
MBeanOperationInfo[] opInfo = info.getOperations();
if (opInfo.length > 0) {
for (int i = 0; i < opInfo.length; i++) {
System.out.println(" ** NAME: \t" + opInfo[i].getName());
System.out.println(" DESCR: \t" + opInfo[i].getDescription());
System.out.println(" PARAM: \t"
+ opInfo[i].getSignature().length + " parameter(s)");
}
} else
System.out.println(" ** No operations ** ");
System.out.println("\nNOTIFICATIONS");
MBeanNotificationInfo[] notifInfo = info.getNotifications();
if (notifInfo.length > 0) {
for (int i = 0; i < notifInfo.length; i++) {
System.out.println(" ** NAME: \t" + notifInfo[i].getName());
System.out
.println(" DESCR: \t" + notifInfo[i].getDescription());
}
}
}
public static void main(String[] args) throws Exception {
SimpleAgent a = new SimpleAgent();
}
}
参考:http://docs.huihoo.com/java/jmx/jmx.html