JMX--Dynamic MBean


直接或间接实现DynamicMBean接口的类就是Dynamic MBean,动态MBean中的属性和操作只在运行时暴露出来,所以动态MBean适合于管理非静态的信息。

优势:
1.不用定义你自己的接口
2.属性和操作只在运行期暴露,可被动态控制
3.可以提供对MBean和他的属性和操作的描述

DynamicMBean interface定义了如下6个方法:
getMBeanInfo
getAttribute
setAttribute
getAttributes
setAttributes
invoke

getMBeanInfo方法返回一个MBeanInfo 对象,其中包括了可以获得的信息 attributes operations constructors notification,管理信息通过MBeanInfo获得,这是强于Standard MBeans的优势之一,Standard MBeans中管理信息通过Standard MBeans内省方式得到,所以实现类必须遵循方法的标准命名规范,动态MBean就没有这个限制,如果实现类中定义了一个printName()方法,他没有遵循命名规范,但他仍可以成为某属性的getter or setter 方法。

getAttribute and setAttribute 取得/设置某属性。
getAttributes and setAttributes 取得/设置某些属性。

Invoke 可以触发某方法。

下面创建一个简单的动态mbean,然后用agent调用它。

//实现动态MBean接口
//

package jmx.test;

import java.lang.reflect.Constructor;
import java.util.Iterator;

import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.
    AttributeNotFoundException;
import javax.management.DynamicMBean;
import javax.management.
    InvalidAttributeValueException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanParameterInfo;
import javax.management.ReflectionException;
import javax.management.
    RuntimeOperationsException;

public class MyDynamic implements DynamicMBean{
//-----------------dynamic mbean part
private String className =
    this.getClass().getName();
private String description =
    
"Simple implementation of a dynamic MBean.";
private MBeanInfo mBeanInfo = null;
private MBeanConstructorInfo[] constructorInfo=
    null;
private MBeanAttributeInfo[] attributeInfo =
    null;
private MBeanOperationInfo[] operationInfo =
    null;

public MyDynamic(){
buildDynamicMBeanInfo();
}

public Object getAttribute(String attribute_name)
throws AttributeNotFoundException,
       MBeanException,
       ReflectionException {

    
//attribute_name == null
    if(attribute_name == null){
throw new RuntimeOperationsException(
    new IllegalArgumentException(
        
"Attribute name cannot be null"),
"Cannot invoke a getter of " +
className +
" with null attribute name");
    }
    
//attribute_name为"state"
    if(attribute_name.equals(
"state")){
return getState();
    }
    
//attribute_name为"num"
    else if(attribute_name.equals(
"num")){
return new Integer(getNum());
    }
    
//attribute_name不存在
    throw(new AttributeNotFoundException(
        
"Cannot find " + attribute_name +
" attribute in " + className));
}

public void setAttribute(Attribute attribute)
throws AttributeNotFoundException,
       InvalidAttributeValueException,
       MBeanException,
       ReflectionException {

    
//attribute == null
    if(attribute == null){
throw new RuntimeOperationsException(
    new IllegalArgumentException(
        
"Attribute cannot be null"),
"Cannot invoke a setter of " +
className +
" with null attribute");
    }

    String name = attribute.getName();
    Object value = attribute.getValue();

    
//attribute.name = state
    if(name.equals(
"state")){
//value == null
if(value == null){
setState(null);
}
//比较value与state的类型
else{
    try{
if((value.getClass())
    .isAssignableFrom(
    Class.forName(
        
"java.lang.String"))){

    setState((String)value);
}else{
  throw(new
  InvalidAttributeValueException(
      
"Cannot set attribute "+
      name +
" to a " +
      value.getClass().getName()
      +
" object, " +
          
"String expected"));
}
    }catch(Exception e){
e.printStackTrace();
    }
}
    }
    
//attribute.name = num
    else if(name.equals(
"num")){
      
//value == null
      if(value == null){
setNum(0);
      }
      
//比较value与num的类型
      else{
try{
  if(value.getClass().isAssignableFrom(
      Class.forName(
      
"java.lang.Integer"))){

    setNum(((Integer)value).intValue());
  }else{
    throw(new
    InvalidAttributeValueException(
    
"Cannot set attribute "+ name +
    
" to a " + value.getClass().getName()
    +
" object, Integer expected"));
}
}catch(Exception e){
  e.printStackTrace();
}
      }
    }
//attribute.name不存在
else{
    throw(new AttributeNotFoundException(
    
"Attribute " + name + " not found in "
    + this.getClass().getName()));
}
}

public AttributeList getAttributes(
    String[] attributeNames) {

    
//attributeNames == null
    if(attributeNames == null){
throw new RuntimeOperationsException(
  new IllegalArgumentException(
  
"attributeNames[] cannot be null"),
  
"Cannot invoke a getter of "
  + className);
    }

    AttributeList attributeList =
        new AttributeList();
    
//attributeNames.length = 0
    if(attributeNames.length == 0){
return attributeList;
    }
    
//遍历数组,进行设置
    for(int i=0; i<attributeNames.length; i++){
try{
  Object value =
    getAttribute(attributeNames<i>);
  attributeList.add(new Attribute(
    attributeNames<i>, value));
}catch(Exception e){
e.printStackTrace();
}
    }
    return attributeList;
}

public AttributeList setAttributes(
    AttributeList attributes) {

    
//attributes == null
    if(attributes == null){
      throw new RuntimeOperationsException(
      new IllegalArgumentException(
      
"AttributeList attributes cannot be null"),
      
"Cannot invoke a setter of " + className);
    }

    AttributeList attributeList =
        new AttributeList();

    
//attributes is empty
    if(attributes.isEmpty()){
return attributeList;
    }

    
//遍历,设置
    Iterator it = attributes.iterator();
    while(it.hasNext()){
Attribute attribute =
    (Attribute)it.next();
try{
  setAttribute(attribute);
  String name = attribute.getName();
  Object value = attribute.getValue();
  attributeList.add(
      new Attribute(name, value));
}catch(Exception e){
  e.printStackTrace();
}
    }

    return attributeList;
}

public Object invoke(String operationName,
    Object params[], String signature[])
throws MBeanException,
       ReflectionException {

    
//operationName == null
    if(operationName == null){
throw new RuntimeOperationsException(
new IllegalArgumentException(
    
"Operation name cannot be null"),
"Cannot invoke a null operation in " +
className);
    }
    
//operationNam is "reset"
    if(operationName.equals(
"reset")){
reset();
return null;
    }
    
//operationNam不存在
    else{
throw new ReflectionException(
new NoSuchMethodException(operationName),
  
"Cannot find the operation " +
  operationName +
" in " + className);
    }
}

public MBeanInfo getMBeanInfo() {
return mBeanInfo;
}

private void buildDynamicMBeanInfo() {
    constructorInfo = new MBeanConstructorInfo[1];
    Constructor[] constructors =
      this.getClass().getConstructors();
    constructorInfo[0] =
      new MBeanConstructorInfo(
      
"MyDynamic():Constructs a dynamic object",
      constructors[0]);

    
//Attributes
    attributeInfo = new MBeanAttributeInfo[2];
    attributeInfo[0] = new MBeanAttributeInfo(
"state",
"java.lang.String",
"state: state string",
true,
true,
false);

    attributeInfo[1] = new MBeanAttributeInfo(
"num",
"java.lang.Integer",
"num: number",
true,
true,
false);

    
//Operations
    operationInfo = new MBeanOperationInfo[1];
    MBeanParameterInfo[] params = null;
    operationInfo[0] = new MBeanOperationInfo(
"reset",
"reset state and num",
params,
"void",
MBeanOperationInfo.ACTION);

    mBeanInfo = new MBeanInfo(
className,
description,
attributeInfo,
constructorInfo,
operationInfo,
new MBeanNotificationInfo[0]);
}

//-------------------------------------self part
private String state =
"initial state";
private int num = 0;

public int getNum() {
return num;
}

public void setNum(int num) {
this.num = num;
}

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

public void reset(){
state =
"initial state";
num = 0;
}
}

//动态代理
//
//

package jmx.test;

import javax.management.Attribute;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanParameterInfo;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.
    MalformedObjectNameException;
import javax.management.ObjectName;

public class DynamicAgent {
private MBeanServer server = null;

public DynamicAgent(){
server = MBeanServerFactory.
    createMBeanServer();
}

public static void main(String[] args){

DynamicAgent agent = new DynamicAgent();

ObjectName mbeanObjectName = null;
String mbeanName =
    
"jmx.test.MyDynamic";
String domain = agent.getServer().
    getDefaultDomain();
try {
    mbeanObjectName = new ObjectName(
        domain +
":type=" + mbeanName);
} catch(MalformedObjectNameException e) {
    e.printStackTrace();
    System.exit(1);
}
agent.createSimpleBean(mbeanObjectName,
    mbeanName);
agent.printMBeanInfo(mbeanObjectName,
    mbeanName);
agent.manageSimpleBean(mbeanObjectName,
    mbeanName);
}
/**
* 创建一个动态mbean
* @param mbeanObjectName
* @param mbeanName
*/

private void createSimpleBean(
  ObjectName mbeanObjectName, String mbeanName){

String mbeanClassName = mbeanName;
try {
    server.createMBean(mbeanClassName,
        mbeanObjectName);
} catch(Exception e) {
    e.printStackTrace();
    System.exit(1);
}
}
/**
* 打印MBeanInfo信息
* @param mbeanObjectName
* @param mbeanName
*/

private void printMBeanInfo(
  ObjectName mbeanObjectName, String mbeanName) {
MBeanInfo info = null;
try {
    info = server.getMBeanInfo(
        mbeanObjectName);
} catch (Exception e) {
    e.printStackTrace();
    return;
}

echo(
"----------------" +
    
"Attribute info--------------");
MBeanAttributeInfo[] attrInfo =
    info.getAttributes();
if (attrInfo.length>0) {
    for(int i=0; i<attrInfo.length; i++){
echo(
"NAME: " +
attrInfo<i>.getName() +
"\tTYPE: \t"+
attrInfo<i>.getType() +
"\tREAD: "+
attrInfo<i>.isReadable() +
"\tWRITE: "+
attrInfo<i>.isWritable());
    }
}
echo(
"----------------" +
    
"Operation info--------------");
MBeanOperationInfo[] operationInfo =
    info.getOperations();
MBeanParameterInfo[] params = null;
if(operationInfo.length>0){
for(int i=0;
  i<operationInfo.length; i++){
String param =
"";

params =
operationInfo<i>.getSignature();
if(params.length>0){
  for(int j=0; j<params.length;
      j++){
    param +=
    params[j].getName() +
"\t";
  }
}else{
param =
"NULL";
}

echo(
"NAME: " +
operationInfo<i>.getName() +
"\t RETURN_TYPE: " +
operationInfo<i>.getReturnType()+
"\t PARAMS: " + param);
}
}
echo(
"----------------" +
    
"Construtor info--------------");
MBeanConstructorInfo[] constructorInfo =
    info.getConstructors();
if(constructorInfo.length>0){
for(int i=0;
  i<constructorInfo.length;
  i++){

    echo(
"NAME: " +
    constructorInfo<i>.getName());
}
}
}

private void manageSimpleBean(
    ObjectName mbeanObjectName,String mbeanName){
try{
    echo(
"---------------" +
      
"set state's value to 'new state'--");
    Attribute stateAttribute =
        new Attribute(
"state","new state");
    server.setAttribute(mbeanObjectName,
        stateAttribute);
    echo(
"state: "+server.getAttribute(
        mbeanObjectName,
"state").toString());

    echo(
"---after invoke reset--");
    server.invoke(mbeanObjectName,
        
"reset",null,null);
    echo(
"state: "+server.getAttribute(
        mbeanObjectName,
"state").toString());
    echo(
"num: "+server.getAttribute(
        mbeanObjectName,
"num").toString());
    }catch(Exception e){
        e.printStackTrace();
    }
}

public MBeanServer getServer() {
return server;
}

public void setServer(MBeanServer server) {
this.server = server;
}

private static void echo(String msg) {
System.out.println(msg);
}
}


irini   2007-05-14 22:54:15 评论:0   阅读:156   引用:0

发表评论>>

署名发表(评论可管理,不必输入下面的姓名)

姓名:

主题:

内容: 最少15个,最长1000个字符

验证码: (如不清楚,请刷新)

Copyright@2008 powered by YuLog