`
minghaitang
  • 浏览: 129044 次
社区版块
存档分类
最新评论

JMX MBeans之四Model MBean (2)

阅读更多

-----------------------------ModelAgent.java---------------------------------------------
import java.lang.reflect.Constructor;
import javax.management.*;
import javax.management.modelmbean.*;
public class ModelAgent
{
 /*
  * 私有属性
  */
 private String dClassName = "TestBean";
 private String dDescription = "Simple implementation of a test app Bean.";
 private ModelMBeanAttributeInfo[] dAttributes = new ModelMBeanAttributeInfo[3];
 private ModelMBeanConstructorInfo[] dConstructors = new ModelMBeanConstructorInfo[1];
 private ModelMBeanOperationInfo[] dOperations = new ModelMBeanOperationInfo[6];
 private ModelMBeanNotificationInfo[] dNotifications = new ModelMBeanNotificationInfo[1];
 private Descriptor mmbDesc = null;
 
 // 这个Model MBean将会把信息放在ModelMBeanInfo对象中
 private ModelMBeanInfo dMBeanInfo = null;
 NotificationListener attrListener = null;
 
 public ModelAgent()
 {
  // 创建MBeanServer
  server = MBeanServerFactory.createMBeanServer();
     try {
   ObjectInstance html = server.createMBean(
     "com.sun.jdmk.comm.HtmlAdaptorServer", null);
   server.invoke(html.getObjectName(), "start", new Object[0],
     new String[0]);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 public static void main(String[] args)
 {
  // 创建Agent...
  ModelAgent agent = new ModelAgent();
  // 执行演示方法
  agent.doSimpleDemo();
 }
 
 // 私有方法
 private void doSimpleDemo()
 {
  // build the simple MBean ObjectName
  //
  ObjectName mbeanObjectName = null;
  String domain = server.getDefaultDomain();
  String mbeanName = "ModelSample";
  attrListener = (NotificationListener) new TestBeanAttributeChangeListener();
  try
  {
   mbeanObjectName = new ObjectName(domain + ":type=" + mbeanName);
  } catch (MalformedObjectNameException e)
  {
   echo("\t!!! Could not create the MBean ObjectName !!!");
   e.printStackTrace();
   echo("EXITING...");
   System.exit(1);
  }
  // create and register the MBean
  createMBean(mbeanObjectName, mbeanName);
  // get and display the management information exposed by the MBean
  printMBeanInfo(mbeanObjectName, mbeanName);
  // create an event listener
  createEventListeners(mbeanObjectName, attrListener);
  // manage the MBean
  manageSimpleBean(mbeanObjectName ,mbeanName);
 
  // trying to do illegal management actions...
  goTooFar(mbeanObjectName);
 
  System.out.println("\nNow, you can point your browser to http://localhost:8082/");
  System.out.println("or start your client application to connect to this agent.\n");
 }
 private void createMBean(ObjectName mbeanObjectName, String mbeanName)
 {
  echo("CREATE object name = " + mbeanObjectName );
  // set management interface in ModelMBean - attributes, operations, notifications
  buildDynamicMBeanInfo(mbeanObjectName, mbeanName);
  try
  {
      RequiredModelMBean modelmbean = new RequiredModelMBean(dMBeanInfo);
      // Set the managed resource for ModelMBean instance
      modelmbean.setManagedResource(new TestBean(), "objectReference");
      // register the ModelMBean in the MBean Server
      server.registerMBean(modelmbean,mbeanObjectName);
  } catch (Exception e)
  {
   echo("\t!!! ModelAgent: Could not create the " + mbeanName + " MBean !!!");
   e.printStackTrace();
   echo("EXITING...");
   System.exit(1);
  }     
  echo("\tModelMBean has been successfully created.");
 }
 private void createEventListeners(ObjectName mbeanObjectName, NotificationListener aListener)
 {
  try
  {
   server.invoke(mbeanObjectName, "addAttributeChangeNotificationListener",
        (new Object[] {aListener, "State", null}),
        (new String[] {"javax.management.NotificationListener",
         "java.lang.String",
         "java.lang.Object"}));
   echo("\tEvent listener created successfully");
  } catch (Exception e)
  {
   echo("Error! Creating Event listener with invoke failed with message:");
   echo(e.getMessage() + "");
   echo("EXITING...");
   e.printStackTrace();
   System.exit(1);
  }
 }
 /**
  * 通过getAttribute(), getAttributes(), setAttribute(), and setAttributes() 方法来访问属性
  * 通过invoke()方法来调用reset()操作 
  */
 private void manageSimpleBean(ObjectName mbeanObjectName, String mbeanName)
 {
  echo("MANAGING the " + mbeanName + " MBean ");
  echo("using its attributes and operations exposed for management");
  try
  {
   // Get attribute values
   sleep(1000);
   echo("Printing attributes from ModelMBean ");
   printSimpleAttributes(mbeanObjectName);
   sleep(1000);
   echo("Printing attributes from instance cache ");
   printSimpleAttributes(mbeanObjectName);
   // Change State attribute
   sleep(1000);
   echo(" Setting State attribute to value \"new state\"...");
   Attribute stateAttribute = new Attribute("State","new state");
   server.setAttribute(mbeanObjectName, stateAttribute);
  
   // Get attribute values
   sleep(1000);
   printSimpleAttributes(mbeanObjectName);
   echo("The NbChanges attribute is still \"0\" as its cached value is valid for 5 seconds (currencyTimeLimit=5s)");
   echo("Wait for 5 seconds and print new attributes values ...");
   sleep(5000);
   printSimpleAttributes(mbeanObjectName);
   // Invoking reset operation
   sleep(1000);
   echo(" Invoking reset operation...");
   server.invoke(mbeanObjectName,"reset",null,null);
   // Get attribute values          1
   echo(" Printing reset attribute values");
   sleep(1000);
   printSimpleAttributes(mbeanObjectName);
   echo("The State and NbChanges attributes are still \"1\" and \"new state\" as their cached value is valid for 5 seconds (currencyTimeLimit=5s)");
   echo("Wait for 5 seconds and print new attributes values ...");
   sleep(5000);
   printSimpleAttributes(mbeanObjectName);
   // Getting Notifications list
   echo("Printing Notifications Broadcasted");
   sleep(1000);
   MBeanNotificationInfo[] myNotifys = (MBeanNotificationInfo[]) server.invoke(mbeanObjectName,
                      "getNotificationInfo",
                      null, null);
   echo("\tSupported notifications are:");
   for (int i=0; i<myNotifys.length; i++)
   {
    echo("\t\t" + ((ModelMBeanNotificationInfo)myNotifys[i]).toString());
   }
   // Accesssing and printing Procol Map for NbChanges
   echo(" Exercising Protocol map for NbChanges");
   sleep(1000);
   ModelMBeanInfo myMMBI = (ModelMBeanInfo) server.invoke(mbeanObjectName,
                   "getMBeanInfo",
                   null, null);
   Descriptor myDesc = myMMBI.getDescriptor("NbChanges","attribute");
   echo("\tRetrieving specific protocols:");
   //          echo("Descriptor: " + myDesc.toString());
   Descriptor pm = (Descriptor) myDesc.getFieldValue("protocolMap");
   //          echo("ProtocolMap *"+pm.toString()+"*");
   echo("\tProtocolMap lookup SNMP is " + pm.getFieldValue("SNMP"));
   echo("\tProtocolMap lookup CIM is " + pm.getFieldValue("CIM"));
   echo("\tDynamically updating Protocol Map:");
   pm.setField("CIM","ManagedResource.LongVersion");
   pm.setField("CMIP","SwitchData");
   echo("\tPrinting Protocol Map");
   String[] pmKeys = pm.getFieldNames();
   Object[] pmEntries = pm.getFieldValues(null);
   for (int i=0; i < pmKeys.length; i++)
   {
    echo("\tProtocol Map Name " + i + ": Name: " + pmKeys[i] + ": Entry:" + ((String) pmEntries[i]).toString());
   }
   echo(" Testing operation caching");
   echo(" Invoking getNbResets");
   Integer numResets = (Integer) server.invoke(mbeanObjectName,"getNbResets",null,null);
   echo("\tReceived " + numResets + " from getNbResets first time");
   echo(" Invoking second reset operation...");
   server.invoke(mbeanObjectName,"reset",null,null);
   Integer numResets2 = (Integer) server.invoke(mbeanObjectName,"getNbResets",null,null);
   echo("\tReceived " + numResets2 + " from getNbResets second time (from operation cache)");
   echo(" Invoking get of attribute ONLY provided through ModelMBeanAttributeInfo (should be 99)...");
   Integer respHardValue = (Integer) server.getAttribute(mbeanObjectName,"HardValue");
   echo("\tReceived " + respHardValue + " from getAttribute of hardValue");

  } catch (Exception e)
  {
   echo("ManageSimpleBean failed with " + e.getMessage());
   e.printStackTrace();
   return;
  }
 }
 private void goTooFar(ObjectName mbeanObjectName)
 {
  echo(">>> Trying to set the NbChanges attribute (read-only)!");
  echo("... We should get an AttributeNotFoundException:");
  sleep(1000);
  // Try to set the NbChanges attribute
  Attribute nbChangesAttribute = new Attribute("NbChanges", new Integer(1));
  try
  {
   server.setAttribute(mbeanObjectName, nbChangesAttribute);
  } catch (Exception e)
  {
   e.printStackTrace();
  }
  echo(">>> Trying to access the NbResets property (not exposed for management)!");
  echo("... We should get an AttributeNotFoundException:");
  sleep(1000);
  // Try to access the NbResets property
  try
  {
   server.getAttribute(mbeanObjectName,"NbResets");
  } catch (Exception e)
  {
   e.printStackTrace();
  }
  return;
 }

 private void printMBeanInfo(ObjectName mbeanObjectName, String mbeanName)
 {
  echo(">>> Getting the management information for the "+ mbeanName + ":" + mbeanObjectName + " MBean");
  echo("    using the getMBeanInfo method of the MBeanServer");
  sleep(1000);
  ModelMBeanInfo info = null;
  try
  {
   info = (ModelMBeanInfo) (server.getMBeanInfo(mbeanObjectName));
   if (info == null)
   {
    echo("ModelMBeanInfo from JMX Agent is null!");
   }
  } catch (Exception e)
  {
   echo("\t!!! ModelAgent:printMBeanInfo: Could not get MBeanInfo object for "+ mbeanName +" exception type " + e.getClass().toString() + ":" + e.getMessage() + "!!!");
   e.printStackTrace();
   return;
  }
  echo("CLASSNAME: \t"+ info.getClassName());
  echo("DESCRIPTION: \t"+ info.getDescription());
  try
  {
   echo("MBEANDESCRIPTOR: \t" + (info.getMBeanDescriptor()).toString());
  } catch (Exception e)
  {
   echo("MBEANDESCRIPTOR: \tNone");
  }
  echo("ATTRIBUTES");
  MBeanAttributeInfo[] attrInfo = (info.getAttributes());
  if (attrInfo.length>0)
  {
   for (int i=0; i<attrInfo.length; i++)
   {
    echo(" ** NAME: \t"+ attrInfo[i].getName());
    echo("    DESCR: \t"+ attrInfo[i].getDescription());
    echo("    TYPE: \t"+ attrInfo[i].getType() +
      "\tREAD: "+ attrInfo[i].isReadable() +
      "\tWRITE: "+ attrInfo[i].isWritable());
    echo("    DESCRIPTOR: \t" + (((ModelMBeanAttributeInfo)attrInfo[i]).getDescriptor()).toString());
   }
  } else echo(" ** No attributes **");
  MBeanConstructorInfo[] constrInfo = info.getConstructors();
  echo("CONSTRUCTORS");
  if (constrInfo.length > 0)
  {
   for (int i=0; i<constrInfo.length; i++)
   {
    echo(" ** NAME: \t"+ constrInfo[i].getName());
    echo("    DESCR: \t"+ constrInfo[i].getDescription());
    echo("    PARAM: \t"+ constrInfo[i].getSignature().length +" parameter(s)");
    echo("    DESCRIPTOR: \t" + (((ModelMBeanConstructorInfo)constrInfo[i]).getDescriptor()).toString());
   }
  } else echo(" ** No Constructors **");
  echo("OPERATIONS");
  MBeanOperationInfo[] opInfo = info.getOperations();
  if (opInfo.length>0)
  {
   for (int i=0; i<opInfo.length; i++)
   {
    echo(" ** NAME: \t"+ opInfo[i].getName());
    echo("    DESCR: \t"+ opInfo[i].getDescription());
    echo("    PARAM: \t"+ opInfo[i].getSignature().length +" parameter(s)");
    echo("    DESCRIPTOR: \t" + (((ModelMBeanOperationInfo)opInfo[i]).getDescriptor()).toString());
   }
  } else echo(" ** No operations ** ");
  echo("NOTIFICATIONS");
  MBeanNotificationInfo[] notifInfo = info.getNotifications();
  if (notifInfo.length>0)
  {
   for (int i=0; i<notifInfo.length; i++)
   {
    echo(" ** NAME: \t"+ notifInfo[i].getName());
    echo("    DESCR: \t"+ notifInfo[i].getDescription());
    echo("    DESCRIPTOR: \t" + (((ModelMBeanNotificationInfo)notifInfo[i]).getDescriptor()).toString());
   }
  } else echo(" ** No notifications **");
  echo("End of MBeanInfo print");
 }
 private void printSimpleAttributes(ObjectName mbeanObjectName)
 {
  try
  {
   echo("\tGetting attribute values:");
   String State = (String) server.getAttribute(mbeanObjectName,"State");
   Integer NbChanges = (Integer) server.getAttribute(mbeanObjectName,"NbChanges");
   echo("\t\tState     = \"" + State + "\"");
   echo("\t\tNbChanges = \"" + NbChanges.toString() + "\"");
  } catch (Exception e)
  {
   echo("\tModelAgent:printSimpleAttributes: !!! Could not read attributes !!!");
   e.printStackTrace();
   return;
  }
 }
 private static void echo(String msg)
 {
  System.out.println(msg);
 }
 private static void sleep(int millis)
 {
  try
  {
   Thread.sleep(millis);
  } catch (InterruptedException e)
  {
   return;
  }
 }
 /*
  * ------------------------------------------
  *  PRIVATE VARIABLES
  * ------------------------------------------
  */
 private MBeanServer server = null;
 /*
  * -----------------------------------------------------
  * PRIVATE METHODS
  * -----------------------------------------------------
  */
 private void loadDynamicMBeanInfo(ObjectName inMbeanObjectName, String inMbeanName)
 {
  try
  {
   Class appBean = Class.forName(dClassName);

   //echo("Setting mbeanDescriptor " + mmbDesc);
   dMBeanInfo = new ModelMBeanInfoSupport(dClassName,
               dDescription,
               dAttributes,
               dConstructors,
               dOperations,
               dNotifications,
               mmbDesc);

  } catch (Exception e)
  {
   echo("Exception in loadDynamicMBeanInfo : " + e.getMessage());
   e.printStackTrace();
  }

 }
 /**
  * 创建私有的dMBeanInfo的各个字段
  * 展示可以用来被管理的属性,构造器,操作以及通知等数据
  *
  * A reference to the dMBeanInfo object is returned by the getMBeanInfo() method
  * of the DynamicMBean interface. Note that, once constructed, an MBeanInfo object is i
  */
 private void buildDynamicMBeanInfo(ObjectName inMbeanObjectName, String inMbeanName)
 {
  try
  {
   Class appBean = Class.forName(dClassName);
   // 为Model MBean设置描述符字段
   mmbDesc = new DescriptorSupport(new String[] {("name="+inMbeanObjectName),
           "descriptorType=mbean",
           ("displayName="+inMbeanName),
           "log=T",
           "logfile=jmxmain.log",
           "currencyTimeLimit=5"});
  
   // 为State属性设置描述符对象
   Descriptor stateDesc = new DescriptorSupport();
   stateDesc.setField("name","State");
   stateDesc.setField("descriptorType","attribute");
   stateDesc.setField("displayName","MyState");
   stateDesc.setField("getMethod","getState");
   stateDesc.setField("setMethod","setState");
   stateDesc.setField("currencyTimeLimit","20");
   dAttributes[0] = new ModelMBeanAttributeInfo("State",
             "java.lang.String",
             "State: state string.",
             true,
             true,
             false,
             stateDesc);
  
   // 为NbChanges属性设置描述符
   Descriptor nbChangesDesc = new DescriptorSupport();
   nbChangesDesc.setField("name","NbChanges");
   nbChangesDesc.setField("descriptorType", "attribute");
   nbChangesDesc.setField("default", "0");
   nbChangesDesc.setField("displayName","MyChangesCount");
   nbChangesDesc.setField("getMethod","getNbChanges");
   nbChangesDesc.setField("setMethod","setNbChanges");
   Descriptor nbChangesMap = new DescriptorSupport(new String[] {
       "SNMP=1.3.6.9.12.15.18.21.0",
    "CIM=ManagedResource.Version"});
 
   nbChangesDesc.setField("protocolMap",(nbChangesMap));
 
  
   dAttributes[1] = new ModelMBeanAttributeInfo("NbChanges",
             "java.lang.Integer",
             "NbChanges: number of times the State string",
             true,
             false,
             false,
             nbChangesDesc);
  
   // 为HardValue属性设置描述符
   Descriptor hardValueDesc = new DescriptorSupport();
   hardValueDesc.setField("name","HardValue");
   hardValueDesc.setField("descriptorType","attribute");
   hardValueDesc.setField("value", new Integer("99"));
   hardValueDesc.setField("displayName","HardCodedValue");
   hardValueDesc.setField("currencyTimeLimit","0");
   /* currencyTimeLimit = 0 表示缓存在描述符对象中的值是永远有效的
    * 当我们调用getAttribute方法访问这个属性的时候,会从描述符对象中读到99*/
   dAttributes[2] = new ModelMBeanAttributeInfo("HardValue",
             "java.lang.Integer",
             "HardValue: static value in ModelMBeanInfo and not in TestBean",
             true,
             false,
             false,
             hardValueDesc);
  
  
   Constructor[] constructors = appBean.getConstructors();
  
   // 定义构造器描述符信息
   Descriptor testBeanDesc = new DescriptorSupport();
   testBeanDesc.setField("name","TestBean");
   testBeanDesc.setField("descriptorType", "operation");
   testBeanDesc.setField("role","constructor");
  
   dConstructors[0] = new ModelMBeanConstructorInfo("TestBean(): Constructs a TestBean App",
          constructors[0],
          testBeanDesc);
  
   MBeanParameterInfo[] params = null;
  
   // 定义reset操作描述符信息
   Descriptor resetDesc = new DescriptorSupport();
   resetDesc.setField("name","reset");
   resetDesc.setField("descriptorType","operation");
   resetDesc.setField("class","TestBean");
   resetDesc.setField("role","operation");
  
   dOperations[0] = new ModelMBeanOperationInfo("reset",
             "reset(): reset State and NbChanges",
             params ,
             "void",
             MBeanOperationInfo.ACTION,
             resetDesc);
  
   // 定义getNbResets操作描述符信息
   Descriptor getNbResetsDesc = new DescriptorSupport(new String[] {"name=getNbResets",
                "class=TestBeanFriend",
                "descriptorType=operation",
                "role=operation"});
   TestBeanFriend tbf = new TestBeanFriend();
   getNbResetsDesc.setField("targetObject",tbf);
   getNbResetsDesc.setField("targetType","objectReference");
  
   dOperations[1] = new ModelMBeanOperationInfo("getNbResets",
             "getNbResets(): get number of resets done",
             params ,
             "java.lang.Integer",
             MBeanOperationInfo.INFO,
             getNbResetsDesc);
   // 定义getState操作描述符信息
   Descriptor getStateDesc = new DescriptorSupport(new String[] {"name=getState",
             "descriptorType=operation",
             "class=TestBean",
             "role=operation"} );
  
   dOperations[2] = new ModelMBeanOperationInfo("getState",
             "get state attribute",
             params ,
             "java.lang.String",
             MBeanOperationInfo.ACTION,
             getStateDesc);
   // 定义setState操作描述符信息
   Descriptor setStateDesc = new DescriptorSupport(new String[] {
       "name=setState",
    "descriptorType=operation",
    "class=TestBean",
    "role=operation"});
  
   MBeanParameterInfo[] setStateParms = new MBeanParameterInfo[] { (new MBeanParameterInfo("newState",
              "java.lang.String",
              "new State value") )} ;
  
   dOperations[3] = new ModelMBeanOperationInfo("setState",
             "set State attribute",
             setStateParms,
             "void",
             MBeanOperationInfo.ACTION,
             setStateDesc);
  
   // 定义getNbChanges操作描述符信息
   Descriptor getNbChangesDesc = new DescriptorSupport( new String[] {
       "name=getNbChanges",
    "descriptorType=operation",
    "class=TestBean",
    "role=operation"});
  
   dOperations[4] = new ModelMBeanOperationInfo("getNbChanges",
             "get NbChanges attribute",
             params,
             "java.lang.Integer",
             MBeanOperationInfo.INFO,
             getNbChangesDesc);
  
   // 定义参数描述符信息
   Descriptor setNbChangesDesc = new DescriptorSupport(new String[] {
       "name=setNbChanges",
    "descriptorType=operation",
    "class=TestBean",
    "role=operation"});
  
   MBeanParameterInfo[] setNbChangesParms = new MBeanParameterInfo[] { (new MBeanParameterInfo("newNbChanges",
                  "java.lang.Integer",
                  "new value for Number of Changes") )} ;
  
  
   dOperations[5] = new ModelMBeanOperationInfo("setNbChanges",
             "set NbChanges attribute",
             setNbChangesParms,
             "void",
             MBeanOperationInfo.ACTION,
             setNbChangesDesc);
  
   //dNotifications[0] = new MBeanNotificationInfo((new String[] {"jmx.attribute.change"}),
   //                        "AttributeChange","ModelMBean Attribute Change Event");
   // 定义通知描述符信息
   Descriptor genEventDesc = new DescriptorSupport(new String[] {"descriptorType=notification",
             "name=jmx.ModelMBean.General",
             "severity=4",
             "MessageId=MA001",
             "log=T",
             "logfile=jmx.log"});
   String[] genTypes = new String[1];
   genTypes[0] = "jmx.ModelMBean.General";
   dNotifications[0] = new ModelMBeanNotificationInfo(genTypes,
            "jmx.ModelMBean.General", // was Generic
            "Generic Event",
            genEventDesc); // test event
  
   // 定义了ModelBean元数据信息
   dMBeanInfo = new ModelMBeanInfoSupport(dClassName,
              dDescription,
              dAttributes,
              dConstructors,
              dOperations,
              dNotifications);
  
   dMBeanInfo.setMBeanDescriptor(mmbDesc);
  
  } catch (Exception e)
      {
   echo("Exception in buildDynamicMBeanInfo : " + e.getMessage());
   e.printStackTrace();
  }
 }
 public void printLocalMBeanInfo(MBeanInfo info)
 {
  echo("CLASSNAME: \t"+ info.getClassName());
  echo("DESCRIPTION: \t"+ info.getDescription());
  echo("ATTRIBUTES");
  MBeanAttributeInfo[] attrInfo = info.getAttributes();
  if (attrInfo.length>0)
  {
   for (int i=0; i<attrInfo.length; i++)
   {
    echo(" ** NAME: \t"+ attrInfo[i].getName());
    echo("    DESCR: \t"+ attrInfo[i].getDescription());
    echo("    TYPE: \t"+ attrInfo[i].getType() +
      "\tREAD: "+ attrInfo[i].isReadable() +
      "\tWRITE: "+ attrInfo[i].isWritable());
    echo("    DESCRIPTOR: \t" + (((ModelMBeanAttributeInfo)attrInfo[i]).getDescriptor()).toString());
   }
  } else echo(" ** No attributes **");
  echo("CONSTRUCTORS");
  MBeanConstructorInfo[] constrInfo = info.getConstructors();
  for (int i=0; i<constrInfo.length; i++)
  {
   echo(" ** NAME: \t"+ constrInfo[i].getName());
   echo("    DESCR: \t"+ constrInfo[i].getDescription());
   echo("    PARAM: \t"+ constrInfo[i].getSignature().length +" parameter(s)");
   echo("    DESCRIPTOR: \t" + (((ModelMBeanConstructorInfo)constrInfo[i]).getDescriptor()).toString());
  }
  echo("OPERATIONS");
  MBeanOperationInfo[] opInfo = info.getOperations();
  if (opInfo.length>0)
  {
   for (int i=0; i<opInfo.length; i++)
   {
    echo(" ** NAME: \t"+ opInfo[i].getName());
    echo("    DESCR: \t"+ opInfo[i].getDescription());
    echo("    PARAM: \t"+ opInfo[i].getSignature().length +" parameter(s)");
    echo("    DESCRIPTOR: \t" + (((ModelMBeanOperationInfo)opInfo[i]).getDescriptor()).toString());
   }
  } else echo(" ** No operations ** ");
  echo("NOTIFICATIONS");
  MBeanNotificationInfo[] notifInfo = info.getNotifications();
  if (notifInfo.length>0)
  {
   for (int i=0; i<notifInfo.length; i++)
   {
    echo(" ** NAME: \t"+ notifInfo[i].getName());
    echo("    DESCR: \t"+ notifInfo[i].getDescription());
    echo("    DESCRIPTOR: \t" + (((ModelMBeanNotificationInfo) notifInfo[i]).getDescriptor()).toString());
   }
  } else echo(" ** No notifications **");
 }

 public void printLocalDescriptors(MBeanInfo mbi) throws javax.management.MBeanException
 {
  echo(mbi.getDescription() + "Descriptors:");
  echo("Attribute Descriptors:");
  Descriptor[] dArray;
  dArray = ((ModelMBeanInfo) mbi).getDescriptors("attribute");
  for (int i = 0; i < dArray.length; i++)
  {
   String[] afields = ((Descriptor) dArray[i]).getFields();
   for (int j=0; j < afields.length; j++)
   {
    echo(afields[j] + "");
   }
  }
  echo("Operation Descriptors:");
  dArray = ((ModelMBeanInfo) mbi).getDescriptors("operation");
  for (int i=0; i < dArray.length; i++)
  {
   echo("*Operation****************************");
   String[] ofields = ((Descriptor) dArray[i]).getFields();
   for (int j=0; j < ofields.length; j++)
   {
    echo(ofields[j] + "");
   }
  }
  echo("Notification Descriptors:");
  dArray = ((ModelMBeanInfo) mbi).getDescriptors("notification");
  for (int i=0; i < dArray.length; i++)
  {
   System.out.println("**Notification****************************");
   String[] nfields = ((Descriptor) dArray[i]).getFields();
   for (int j=0; j < nfields.length; j++)
   {
    System.out.println(nfields[j] + "");
   }
  }
 }
 public void printModelMBeanDescriptors(ObjectName mbeanObjectName)
 {
  sleep(1000);
  Descriptor[] dArray = new DescriptorSupport[0];
  try
  {
   dArray = (Descriptor[]) (server.invoke(mbeanObjectName, "getDescriptors",
               new Object[] {},
               new String[] {}));
   if (dArray == null)
   {
    echo("Descriptor list is null!");
   }
  } catch (Exception e)
  {
   echo("\t!!! Could not get descriptors for mbeanName ");
   e.printStackTrace();
   return;
  }
  echo("Descriptors: (");
  echo(dArray.length + ")");
  for (int i=0; i < dArray.length; i++)
  {
   echo("**Descriptor***********************");
   String[] dlfields =  ((Descriptor) dArray[i]).getFields();
   for (int j=0; j < dlfields.length; j++)
   {
    echo(dlfields[j] + "");
   }
  }
 }

}

 

 


---------------------TestBeanAttributeChangeListener.java------------------------------
import javax.management.NotificationListener;
import javax.management.AttributeChangeNotification;
import javax.management.Notification;
/**
* 实现了NotificationListener接口.
* 监听和接受由ModelMBean发出的改变属性的通知
*/
public class TestBeanAttributeChangeListener implements NotificationListener {
 public void handleNotification(Notification acn, Object handback) {
  echo("\n\tTestBeanAttributeChangeListener received Attribute ChangeNotification ");
  AttributeChangeNotification myacn = (AttributeChangeNotification) acn;
  echo("\t\tEvent: " + acn.getType());
  echo("\t\tAttribute: " + myacn.getAttributeName());
  echo("\t\tAttribute type: " + myacn.getAttributeType());
  echo("\t\tOld value: " + myacn.getOldValue());
  echo("\t\tNew value: " + myacn.getNewValue());
 }
 private static void echo(String outstr) {
  System.out.println(outstr);
 }
}

 

 

 

-----------------------------TestBean.java---------------------------------------------
/**
 * 被ModelMBean管理的一个简单定义的Bean --TestBean
 * 这个Bean展示了两个属性,和一个操作
 * State属性是可读可写的,NbChanges是只读的,还有reset()操作
 */
public class TestBean
   implements java.io.Serializable
{
 // 私有变量
    private String  state = "initial state";
    private int     nbChanges = 0;
    private int     nbResets = 0;
    public TestBean() {
        echo("\tTestBean Constructor Invoked: State " + state + " nbChanges: " + nbChanges + " nbResets: " + nbResets);
    }
    /**
     * Getter
     */
    public String getState() {
        echo("\tTestBean: getState invoked: " + state);
        return state;
    }
    /**
     * Setter
     */
    public void setState(String s) {
        state = s;
        nbChanges++;
        echo("\tTestBean: setState to " + state + " nbChanges: " + nbChanges);
    }
    /**
     * Getter
     */
    public Integer getNbChanges() {
        echo("\tTestBean: getNbChanges invoked: " + nbChanges);
        return new Integer(nbChanges);
    }
    /**
     * reset操作
     */
    public void reset() {
        echo("\tTestBean: reset invoked ");
        state = "reset initial state";
        nbChanges = 0;
        nbResets++;
    }
    /**
     * 返回reset次数属性值
     * This method is not a Getter in the JMX sense because
     * it is not returned by the getMBeanInfo() method.
     */
    public Integer getNbResets() {
        echo("\tTestBean: getNbResets invoked: " + nbResets);
        return new Integer(nbResets);
    }
    private void echo(String outstr) {
        System.out.println(outstr);
    }
}

 


----------------------------------TestBeanFriend.java--------------------------------
/**
 * 被ModelMBean管理的一个简单定义的Bean --TestBeanFriend.
 * 和TestBean几乎一样.
 */
public class TestBeanFriend
   implements java.io.Serializable
{
    private String  state = "initial state";
    private int     nbChanges = 0;
    private int     nbResets = 0;
    public TestBeanFriend() {
        echo("\tTestBeanFriend Constructor invoked: State " + state + " nbChanges: " + nbChanges + " nbResets: " + nbResets);
    }
    /**
     * Getter.
     */
    public String getState() {
        echo("\tTestBeanFriend: getState invoked:" + state);
        return state;
    }
    /**
     * Setter.
     */
    public void setState(String s) {
        state = s;
        nbChanges++;
        echo("\tTestBeanFriend: setState invoked: to " + state + " nbChanges: " + nbChanges);
    }
    /**
     * Getter.
     */
    public Integer getNbChanges() {
        echo("\tTestBeanFriend:getNbChanges invoked: " + nbChanges);
        return new Integer(nbChanges);
    }
    /**
     * reset Operation.
     */
    public void reset() {
        echo("\tTestBeanFriend: reset invoked ");
        state = "reset initial state";
        nbChanges = 0;
        nbResets++;
    }
    /**
     * Return the "NbResets" property.
     * This method is not a Getter in the JMX sense because
     * it is not returned by the getMBeanInfo() method.
     */
    public Integer getNbResets() {
        echo("\tTestBeanFriend: getNbResets invoked " + nbResets);
        return new Integer(nbResets);
    }
    private void echo(String outstr) {
        System.out.println(outstr);
    }
}

 

 

 

 

 

 

--------------------------------OUTPUT------------------------------
CREATE object name = DefaultDomain:type=ModelSample
 TestBeanFriend Constructor invoked: State initial state nbChanges: 0 nbResets: 0
 TestBean Constructor Invoked: State initial state nbChanges: 0 nbResets: 0
 ModelMBean has been successfully created.
>>> Getting the management information for the ModelSample:DefaultDomain:type=ModelSample MBean
    using the getMBeanInfo method of the MBeanServer
CLASSNAME:  TestBean
DESCRIPTION:  Simple implementation of a test app Bean.
MBEANDESCRIPTOR:  logfile=jmxmain.log, log=T, visibility=1, currencytimelimit=5, descriptortype=mbean, name=DefaultDomain:type=ModelSample, displayname=ModelSample, persistpolicy=never
ATTRIBUTES
 ** NAME:  State
    DESCR:  State: state string.
    TYPE:  java.lang.String READ: true WRITE: true
    DESCRIPTOR:  setmethod=setState, getmethod=getState, currencytimelimit=20, descriptortype=attribute, displayname=MyState, name=State
 ** NAME:  NbChanges
    DESCR:  NbChanges: number of times the State string
    TYPE:  java.lang.Integer READ: true WRITE: false
    DESCRIPTOR:  setmethod=setNbChanges, getmethod=getNbChanges, protocolmap=(snmp=1.3.6.9.12.15.18.21.0, cim=ManagedResource.Version), default=0, descriptortype=attribute, displayname=MyChangesCount, name=NbChanges
 ** NAME:  HardValue
    DESCR:  HardValue: static value in ModelMBeanInfo and not in TestBean
    TYPE:  java.lang.Integer READ: true WRITE: false
    DESCRIPTOR:  value=(99), currencytimelimit=0, descriptortype=attribute, displayname=HardCodedValue, name=HardValue
CONSTRUCTORS
 ** NAME:  TestBean
    DESCR:  TestBean(): Constructs a TestBean App
    PARAM:  0 parameter(s)
    DESCRIPTOR:  role=constructor, descriptortype=operation, displayname=TestBean, name=TestBean
OPERATIONS
 ** NAME:  reset
    DESCR:  reset(): reset State and NbChanges
    PARAM:  0 parameter(s)
    DESCRIPTOR:  class=TestBean, role=operation, descriptortype=operation, displayname=reset, name=reset
 ** NAME:  getNbResets
    DESCR:  getNbResets(): get number of resets done
    PARAM:  0 parameter(s)
    DESCRIPTOR:  class=TestBeanFriend, targetobject=(TestBeanFriend@34a1fc), role=operation, targettype=objectReference, descriptortype=operation, name=getNbResets, displayname=getNbResets
 ** NAME:  getState
    DESCR:  get state attribute
    PARAM:  0 parameter(s)
    DESCRIPTOR:  class=TestBean, role=operation, descriptortype=operation, displayname=getState, name=getState
 ** NAME:  setState
    DESCR:  set State attribute
    PARAM:  1 parameter(s)
    DESCRIPTOR:  class=TestBean, role=operation, descriptortype=operation, displayname=setState, name=setState
 ** NAME:  getNbChanges
    DESCR:  get NbChanges attribute
    PARAM:  0 parameter(s)
    DESCRIPTOR:  class=TestBean, role=operation, descriptortype=operation, displayname=getNbChanges, name=getNbChanges
 ** NAME:  setNbChanges
    DESCR:  set NbChanges attribute
    PARAM:  1 parameter(s)
    DESCRIPTOR:  class=TestBean, role=operation, descriptortype=operation, displayname=setNbChanges, name=setNbChanges
NOTIFICATIONS
 ** NAME:  jmx.ModelMBean.General
    DESCR:  Generic Event
    DESCRIPTOR:  logfile=jmx.log, log=T, messageid=MA001, severity=4, descriptortype=notification, name=jmx.ModelMBean.General, displayname=jmx.ModelMBean.General
End of MBeanInfo print
 Event listener created successfully
MANAGING the ModelSample MBean
using its attributes and operations exposed for management
Printing attributes from ModelMBean
 Getting attribute values:
 TestBean: getState invoked: initial state
 TestBean: getNbChanges invoked: 0
  State     = "initial state"
  NbChanges = "0"
Printing attributes from instance cache
 Getting attribute values:
  State     = "initial state"
  NbChanges = "0"
 Setting State attribute to value "new state"...
 TestBean: setState to new state nbChanges: 1
 TestBeanAttributeChangeListener received Attribute ChangeNotification
  Event: jmx.attribute.change
  Attribute: State
  Attribute type: java.lang.String
  Old value: initial state
  New value: new state
 Getting attribute values:
  State     = "new state"
  NbChanges = "0"
The NbChanges attribute is still "0" as its cached value is valid for 5 seconds (currencyTimeLimit=5s)
Wait for 5 seconds and print new attributes values ...
 Getting attribute values:
 TestBean: getNbChanges invoked: 1
  State     = "new state"
  NbChanges = "1"
 Invoking reset operation...
 TestBean: reset invoked
 Printing reset attribute values
 Getting attribute values:
  State     = "new state"
  NbChanges = "1"
The State and NbChanges attributes are still "1" and "new state" as their cached value is valid for 5 seconds (currencyTimeLimit=5s)
Wait for 5 seconds and print new attributes values ...
 Getting attribute values:
 TestBean: getNbChanges invoked: 0
  State     = "new state"
  NbChanges = "0"
Printing Notifications Broadcasted
 Supported notifications are:
  ModelMBeanNotificationInfo: GENERIC ; Description: A text notification has been issued by the managed resource ; Descriptor: log=T, severity=6, descriptortype=notification, displayname=jmx.modelmbean.generic, name=GENERIC ; Types: jmx.modelmbean.generic
  ModelMBeanNotificationInfo: ATTRIBUTE_CHANGE ; Description: Signifies that an observed MBean attribute value has changed ; Descriptor: log=T, severity=6, descriptortype=notification, displayname=jmx.attribute.change, name=ATTRIBUTE_CHANGE ; Types: jmx.attribute.change
  ModelMBeanNotificationInfo: jmx.ModelMBean.General ; Description: Generic Event ; Descriptor: logfile=jmx.log, log=T, messageid=MA001, severity=4, descriptortype=notification, name=jmx.ModelMBean.General, displayname=jmx.ModelMBean.General ; Types: jmx.ModelMBean.General
 Exercising Protocol map for NbChanges
 Retrieving specific protocols:
 ProtocolMap lookup SNMP is 1.3.6.9.12.15.18.21.0
 ProtocolMap lookup CIM is ManagedResource.Version
 Dynamically updating Protocol Map:
 Printing Protocol Map
 Protocol Map Name 0: Name: cmip: Entry:SwitchData
 Protocol Map Name 1: Name: snmp: Entry:1.3.6.9.12.15.18.21.0
 Protocol Map Name 2: Name: cim: Entry:ManagedResource.LongVersion
 Testing operation caching
 Invoking getNbResets
 TestBeanFriend: getNbResets invoked 0
 Received 0 from getNbResets first time
 Invoking second reset operation...
 TestBean: reset invoked
 Received 0 from getNbResets second time (from operation cache)
 Invoking get of attribute ONLY provided through ModelMBeanAttributeInfo (should be 99)...
 Received 99 from getAttribute of hardValue
>>> Trying to set the NbChanges attribute (read-only)!
... We should get an AttributeNotFoundException:
javax.management.AttributeNotFoundException: setAttribute failed: NbChanges is not writable
 at javax.management.modelmbean.RequiredModelMBean.setAttribute(RequiredModelMBean.java:1675)
 at com.sun.jmx.mbeanserver.DynamicMetaDataImpl.setAttribute(DynamicMetaDataImpl.java:188)
 at com.sun.jmx.mbeanserver.MetaDataImpl.setAttribute(MetaDataImpl.java:214)
 at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.setAttribute(DefaultMBeanServerInterceptor.java:744)
 at com.sun.jmx.mbeanserver.JmxMBeanServer.setAttribute(JmxMBeanServer.java:730)
 at ModelAgent.goTooFar(ModelAgent.java:261)
 at ModelAgent.doSimpleDemo(ModelAgent.java:83)
 at ModelAgent.main(ModelAgent.java:46)
>>> Trying to access the NbResets property (not exposed for management)!
... We should get an AttributeNotFoundException:
javax.management.AttributeNotFoundException: getAttribute failed: ModelMBeanAttributeInfo not found for NbResets
 at javax.management.modelmbean.RequiredModelMBean.getAttribute(RequiredModelMBean.java:1323)
 at com.sun.jmx.mbeanserver.DynamicMetaDataImpl.getAttribute(DynamicMetaDataImpl.java:104)
 at com.sun.jmx.mbeanserver.MetaDataImpl.getAttribute(MetaDataImpl.java:189)
 at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.getAttribute(DefaultMBeanServerInterceptor.java:645)
 at com.sun.jmx.mbeanserver.JmxMBeanServer.getAttribute(JmxMBeanServer.java:667)
 at ModelAgent.goTooFar(ModelAgent.java:272)
 at ModelAgent.doSimpleDemo(ModelAgent.java:83)
 at ModelAgent.main(ModelAgent.java:46)
Now, you can point your browser to http://localhost:8082/
or start your client application to connect to this agent.

分享到:
评论

相关推荐

    JMX IN ACTION(七)

    Model MBean由`javax.management.modelmbean.RequiredModelMBean`类定义,它是JMX代理的一个必需部分。与Dynamic MBean类似,Model MBean的管理接口是在运行时定义的。`RequiredModelMBean`类实现了`ModelMBean`接口...

    jmx学习整理里1

    Model MBean通过`javax.management.modelmbean.ModelMBean`接口和一个描述符文件(如`car-mbean-descriptor.xml`)定义其行为。 描述符文件(如`car-mbean-descriptor.xml`)包含了MBean的元数据,包括属性、操作、...

    JMX、MXBean学习

    Standard MBeans是预定义了管理接口的类,Dynamic MBeans则可以在运行时动态定义其管理接口,而Model MBeans是一种抽象层,可以将任何Java对象转换为MBean。 MXBean是JMX中的一个特殊概念,它是标准MBean的扩展,...

    JMX配置与使用

    Model MBeans是最通用的,它们基于元数据来定义MBean的行为。 5. 监控与通知: 通过JMX,可以注册监听器来接收关于MBean状态变化的通知。这可以用来实现自动化的故障检测、日志记录或者性能监控。此外,JMX还可以...

    JMX 相关

    JMX是Java平台上强大的管理和监控工具,通过MBeans、MBean Server和JMX Connectors,可以轻松地监控和管理Java应用。无论是小规模的应用还是大型分布式系统,JMX都能提供灵活且强大的管理能力。结合JConsole和...

    jmx资料

    MBeans分为标准MBean、Dynamic MBean和Model MBean三种类型,以适应不同的需求。Server是运行MBeans的环境,它负责注册、管理MBeans,并提供给Clients访问接口。Clients则通过连接到Server来访问和操作MBeans,实现...

    Java Management Extensions

    实现模型MBeans通常需要使用`ModelMBean`接口,并通过`ModelMBeanInfo`类来描述MBean的行为。 #### 五、MBean服务器 MBean服务器是JMX的核心组件之一,负责注册和管理所有的MBeans。了解如何与MBean服务器交互是...

    [课堂课件讲解]Java微服务实践-Spring Boot 监管.pptx

    JMX 还提供了通知模型(Notification Model),允许 MBean 广播管理事件,这种操作称之为通知。管理应用和其他对象注册成监听器。元信息类包含描述所有 MBean 管理接口的组件接口,其中包括属性、操作、通知和构造器...

    JMX: Developer's Quick Start Guide

    - **Model MBeans**:模型MBeans是另一种形式的MBean,它利用反射机制自动创建一个MBean实例,而无需实现特定的接口。这种类型的MBean通常用于现有类的管理,而不需要修改源代码。 #### 五、通知机制 JMX支持一种...

    JMX specification 1.4

    - **MBean(Managed Bean)**:这是JMX的核心概念之一,它是一种Java对象,用于封装被管理实体的功能和属性。 - **MBean服务器(MBean Server)**:负责管理和存储MBeans的对象,它是所有JMX操作的基础。 - **对象...

    SpringJMX.pdf

    它的前身是 **JMAPI**(Java Management API),后来演变为JMX并逐渐成为业界广泛接受的标准之一。 - **历史发展**: - **JMAPI**:Java管理API的早期版本。 - **JSR-031**:1998年被纳入JCP标准。 - **JMX 1.0**...

    Java Management Extensions管理扩展原理解析

    - **Model MBean**:使用`javax.management.modelmbean.RequiredModelMBean`,无需编写MBean类,管理资源通常在外部定义。 2. **适配层**:MBean服务器是JMX架构的核心,它负责注册MBeans,执行MBean操作,以及...

    The JBoss 4 Application Server Guide

    XMBeans 是 JBoss 特有的 MBeans 实现,它们提供了对 JMX API 的扩展。这一节详细介绍了 XMBeans 的各个组成部分,如描述符、管理类、构造函数、属性、操作和通知等。 #### 连接到 JMX 服务器 连接到 JMX 服务器...

    How Tomcat Works: A Guide to Developing Your Own Java Servlet Container

    20.4.2 ModelMBean实例 161 20.5 Commons Modeler 161 20.5.1 MBean描述符 162 20.5.1.1 mbean 162 20.5.1.2 attribute 163 20.5.1.3 operation 163 20.5.1.4 parameter 163 20.5.2 mbean标签实例 164 20.5.3 自己...

Global site tag (gtag.js) - Google Analytics