Java Dynamic Management Kit 5.0 Tutorial

Part I Instrumentation Using MBeans

Given a resource in the Java programming language—either an application, a service or an object representing a device—its instrumentation is the way that you expose its management interface. The management interface is the set of attributes and operations that are visible to managers that need to interact with that resource. Therefore, instrumenting a resource makes it manageable.

This part covers the four ways to instrument a resource:

When you write a standard MBean, you follow certain design patterns so that the method names in your object expose the attributes and operations to static introspection. Dynamic MBeans implement a generic interface and can expose a rich description of their management interface. Model MBeans are MBean templates whose management interface and resource target are defined at runtime. Open MBeans are managed objects that refer only to a limited and predefined set of data types, that can be combined into compound types such as tables.

Chapter 1 Standard MBeans

A standard MBean is the simplest and fastest way to instrument a resource from scratch: Attributes and operations are simply methods which follow certain design patterns. A standard MBean is composed of the MBean interface which lists the methods for all exposed attributes and operations, and the class which implements this interface and provides the functionality of the resource.

The code samples in this chapter are from the files in the StandardMBean example directory located in the main examplesDir (see “Directories and Classpath” in the Preface).

This chapter covers the following topics:

Exposing the MBean Interface

To expose the MBean interface, first determine the management interface of your resource, that is the information needed to manage it. This information is expressed as attributes and operations. An attribute is a value of any type that a manager can get or set remotely. An operation is a method with any signature and any return type that the manager can invoke remotely.


Note –

Attributes and operations are conceptually equivalent to properties and actions on JavaBeans objects. However, their translation into Java code is entirely different to accommodate the management functionality.


As specified by JMX instrumentation, all attributes and operations are explicitly listed in an MBean interface. This is a Java interface that defines the full management interface of an MBean. This interface must have the same name as the class that implements it, followed by the MBean suffix. Because the interface and its implementation are usually in different files, two files make up a standard MBean.

For example, the class SimpleStandard (in the file SimpleStandard.java) has its management interface defined in the interface SimpleStandardMBean (in the file SimpleStandardMBean.java).


Example 1–1 SimpleStandardMBean Interface

public interface SimpleStandardMBean {

    public String getState() ;
    
    public void setState(String s) ;
    
    public Integer getNbChanges() ;
    
    public void reset() ;
}

Only public methods in the MBean interface are taken into consideration for the management interface. When present, non-public methods should be grouped separately, to make the code clearer for human readers.

Attributes

Attributes are conceptual variables that are exposed for management through getter and setter methods in the MBean interface:

Attribute types can be arrays of objects, but individual array elements cannot be accessed individually through the getters and setters. Use operations to access the array elements, as described in the next section. The following code example demonstrates an attribute with an array type:

public String[] getMessages();
public void setMessages(String[] msgArray);

The name of the attribute is the literal part of the method name following get, is, or set. This name is case sensitive in all Java Dynamic Management Kit (DMK) objects that manipulate attribute names. Using these patterns, we can determine the attributes exposed in Example 1–1:

The specification of the design patterns for attributes implies the following rules:

Operations

Operations are methods that management applications can call remotely on a resource. They can be defined with any number of parameters of any type and can return any type.

The design patterns for operations are simple. Any public method defined in the MBean interface that is not an attribute getter or setter is an operation. For this reason, getters and setters are usually declared first in the Java code, so that all operations are grouped afterwards. The name of an operation is the name of the corresponding method.

The SimpleStandardMBean in Example 1–1 defines one operation, reset, which takes no parameters and returns nothing.

While the following methods define valid operations (and not attributes), to avoid confusion with attributes, these types of names should not be used:

public void getFoo();
public Integer getBar(Float p);
public void setFoo(Integer one, Integer two);
public String isReady();

For performance reasons, you might want to define operations for accessing individual elements of an array type attribute. In this case, use unambiguous operation names:

public String singleGetMessage(int index);
public void singleSetMessage(int index, String msg);

Note –

The Java DMK imposes no restrictions on attribute types, operation attribute types, and operation return types. However, the developer must ensure that the corresponding classes are available to all applications manipulating these objects, and that they are compatible with the type of communication used. For example, attribute and operation types must be serializable to be manipulated remotely using the RMI or HTTP protocols.


Implementing an MBean

The second part of an MBean is the class that implements the MBean interface. This class encodes the expected behavior of the manageable resource in its implementation of the attribute and operation methods. The resource does not need to reside entirely in this class. The MBean implementation can rely on other objects.

If the MBean must be instantiated remotely, it must be a concrete class and must expose at least one public constructor so that any other class can create an instance.

Otherwise, the developer is free to implement the management interface in any way, provided that the object has the expected behavior. Here is the sample code that implements our MBean interface:


Example 1–2 SimpleStandard Class

public class SimpleStandard implements SimpleStandardMBean {

     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++;
    }

    // This method is not a getter in the management sense because 
    // it is not exposed in the "SimpleStandardMBean" interface.
    public Integer getNbResets() {
        return new Integer(nbResets);
    }

    // internal variables for exposed attributes
    private String      state = "initial state";
    private int         nbChanges = 0;

    // other private variables
    private int         nbResets = 0;   
}

As in this example, attributes are usually implemented as internal variables whose value is returned or modified by the getter and setter methods. However, an MBean can implement any access and storage scheme to fit particular management needs, provided getters and setters retain their read and write semantics. Methods in the MBean implementation can have side-effects, but it is up to you to ensure that these are safe and coherent within the full management solution.

As we will see later, management applications never have a direct handle on an MBean. They only have an identification of an instance and the knowledge of the management interface. In this case, the mechanism for exposing attributes through methods in the MBean interface makes it impossible for an application to access the MBean directly. Internal variables and methods, and even public ones, are totally encapsulated and their access is controlled by the programmer through the implementation of the MBean interface.

Running the Standard MBean Example

The examplesDir/StandardMBean directory contains the SimpleStandard.java and SimpleStandardMBean.java files which make up the MBean. This directory also contains a simple agent application which instantiates this MBean, introspects its management interface, and manipulates its attributes and operations.

To Run the Standard MBean Example
  1. Compile all files in this directory with the javac command.

    For example, on the Solaris platform with the Korn shell, type:


    $ cd examplesDir/StandardMBean/
    $ javac -classpath classpath *.java
    
  2. To run the example, start the agent class which will interact with the SimpleStandard MBean:


    $ java -classpath classpath StandardAgent
    
  3. Press Enter when the application pauses, to step through the example. The agent application handles all input and output in this example and gives a view of the MBean at runtime.

We will examine how agents work in Chapter 2, Dynamic MBeans, but this example demonstrates how the MBean interface limits the view of what the MBean exposes for management. Roughly, the agent introspects the MBean interface at runtime to determine what attributes and operations are available. You then see the result of calling the getters, setters, and operations.

Part II also covers the topics of object names and exceptions which you see when running this example.

Chapter 2 Dynamic MBeans

A dynamic MBean implements its management interface programmatically, instead of through static method names. To do this, it relies on metadata classes that represent the attributes and operations exposed for management. Management applications then call generic getters and setters whose implementation must resolve the attribute or operation name to its intended behavior.

One advantage of this instrumentation is that you can use it to make an existing resource manageable quickly. The implementation of the DynamicMBean interface provides an instrumentation wrapper for an existing resource.

Another advantage is that the metadata classes for the management interface can provide human-readable descriptions of the attributes, operations, and the MBean itself. This information could be displayed to a user on a management console to describe how to interact with this particular resource.

The code samples in this chapter are from the files in the DynamicMBean example directory located in the main examplesDir (see “Directories and Classpath” in the Preface).

This chapter covers the following topics:

Exposing the Management Interface

In the standard MBean, attributes and operations are exposed statically in the names of methods in the MBean interface. Dynamic MBeans all share the same interface that defines generic methods to access attributes and operations. Because the management interface is no longer visible through introspection, dynamic MBeans must also provide a description of their attributes and operations explicitly.

DynamicMBean Interface

The DynamicMBean class is a Java interface defined by the JMX specification. It specifies the methods that a resource implemented as a dynamic MBean must provide to expose its management interface. Example 2–1 shows the uncommented code for the DynamicMBean interface:


Example 2–1 The DynamicMBean Interface

public interface DynamicMBean {

    public Object getAttribute(String attribute) throws
        AttributeNotFoundException, MBeanException, ReflectionException; 

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

    public AttributeList getAttributes(String[] attributes);

    public AttributeList setAttributes(AttributeList attributes);

    public Object invoke(
        String actionName, Object params[], String signature[])
        throws MBeanException, ReflectionException ;

    public MBeanInfo getMBeanInfo();
 }

The getMBeanInfo method provides a description of the MBean's management interface. This method returns an MBeanInfo object that contains the metadata information about attributes and operations.

The attribute getters and setters are generic, since they take the name of the attribute that needs to be read or written. For convenience, dynamic MBeans must also define bulk getters and setters to operate on any number of attributes at once. These methods use the Attribute and AttributeList classes to represent attribute name-value pairs and lists of name-value pairs, respectively.

Because the names of the attributes are not revealed until runtime, the getters and setters are necessarily generic. In the same way, the invoke method takes the name of an operation and its signature, in order to invoke any method that might be exposed.

As a consequence of implementing generic getters, setters, and invokers, the code for a dynamic MBean is more complex than for a standard MBean. For example, instead of calling a specific getter by name, the generic getter must verify the attribute name and then encode the functionality to read each of the possible attributes.

MBean Metadata Classes

A dynamic MBean has the burden of building the description of its own management interface. The JMX specification defines the Java objects used to completely describe the management interface of an MBean. Dynamic MBeans use these objects to provide a complete self description as returned by the getMBeanInfo method. Agents also use these classes to describe a standard MBean after it has been introspected.

As a group, these classes are referred to as the MBean metadata classes because they provide information about the MBean. This information includes the attributes and operations of the management interface, also the list of constructors for the MBean class, and the notifications that the MBean might send. Notifications are event messages that are defined by the JMX architecture. See Chapter 9, Notification Mechanism.

Each element is described by its metadata object containing its name, a description string, and its characteristics. For example, an attribute has a type and is readable and/or writable. Table 2–1 lists all MBean metadata classes:

Table 2–1 MBean Metadata Classes

Class Name 

Purpose 

MBeanInfo

Top-level object containing arrays of metadata objects for all MBean elements; also includes the name of the MBean's Java class and a description string 

MBeanFeatureInfo

Parent class from which all other metadata objects inherit a name and a description string 

MBeanOperationInfo

Describes an operation: the return type, the signature as an array of parameters, and the impact (whether the operation just returns information or modifies the resource) 

MBeanConstructorInfo

Describes a constructor by its signature 

MBeanParameterInfo

Gives the type of a parameter in an operation or constructor signature 

MBeanAttributeInfo

Describes an attribute: its type, whether it is readable, and whether it is writable 

MBeanNotificationInfo

Contains an array of notification type strings 

Implementing a Dynamic MBean

A dynamic MBean consists of a class that implements the DynamicMBean interface coherently. By this, we mean a class that exposes a management interface whose description matches the attributes and operations that are accessible through the generic getters, setters and invokers.

A dynamic MBean class can declare any number of public or private methods and variables. None of these are visible to management applications. Only the methods implementing the DynamicMBean interface are exposed for management. A dynamic MBean can also rely on other classes that might be a part of the manageable resource.

Dynamic Programming Issues

An MBean is a manageable resource that exposes a specific management interface. The name dynamic MBean refers to the fact that the interface is revealed at runtime, instead of through the introspection of static class names. The term dynamic is not meant to imply that the MBean can dynamically change its management interface.

getMBeanInfo Method

Because the MBean description should never change, it is usually created one time only at instantiation, and the getMBeanInfo method simply returns its reference at every call. The MBean constructor should therefore build the MBeanInfo object from the MBean metadata classes such that it accurately describes the management interface. And since most dynamic MBeans will always be instantiated with the same management interface, building the MBeanInfo object is fairly straightforward.

Example 2–2 shows how the SimpleDynamic MBean defines its management interface, as built at instantiation and returned by its getMBeanInfo method:


Example 2–2 Implementation of the getMBeanInfo Method

// class constructor
public SimpleDynamic() {

    buildDynamicMBeanInfo();
}

// internal variables describing the MBean
private String dClassName = this.getClass().getName();
private String dDescription = "Simple implementation of a dynamic MBean.";

// internal variables for describing MBean elements
private MBeanAttributeInfo[] dAttributes = new MBeanAttributeInfo[2];
private MBeanConstructorInfo[] dConstructors = new MBeanConstructorInfo[1];
private MBeanOperationInfo[] dOperations = new MBeanOperationInfo[1];
private MBeanInfo dMBeanInfo = null;

// internal method
private void buildDynamicMBeanInfo() {

    dAttributes[0] = new MBeanAttributeInfo(
        "State",                 // name
        "java.lang.String",      // type
        "State: state string.",  // description
        true,                    // readable
        true);                   // writable
    dAttributes[1] = new MBeanAttributeInfo(
        "NbChanges",
        "java.lang.Integer",
        "NbChanges: number of times the State string has been changed.",
        true,
        false);

    // use reflection to get constructor signatures
    Constructor[] constructors = this.getClass().getConstructors();
    dConstructors[0] = new MBeanConstructorInfo(
        "SimpleDynamic(): No-parameter constructor",  //description
        constructors[0]);                  // the contructor object

    MBeanParameterInfo[] params = null;
    dOperations[0] = new MBeanOperationInfo(
        "reset",                     // name
        "Resets State and NbChanges attributes to their initial values",
                                     // description
        params,                      // parameter types
        "void",                      // return type
        MBeanOperationInfo.ACTION);  // impact

    dMBeanInfo = new MBeanInfo(dClassName,
                               dDescription,
                               dAttributes,
                               dConstructors,
                               dOperations,
                               new MBeanNotificationInfo[0]);
}

// exposed method implementing the DynamicMBean.getMBeanInfo interface
public MBeanInfo getMBeanInfo() {

    // return the information we want to expose for management:
    // the dMBeanInfo private field has been built at instantiation time,
    return(dMBeanInfo);
}

Generic Attribute Getters and Setters

Generic getters and setters take a parameter that indicates the name of the attribute to read or write. There are two issues to keep in mind when implementing these methods:

The getAttribute method is the simplest, since only the attribute name must be verified:


Example 2–3 Implementation of the getAttribute Method

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

    // Check attribute_name to avoid NullPointerException later on
    if (attribute_name == null) {
        throw new RuntimeOperationsException(
            new IllegalArgumentException("Attribute name cannot be null"), 
            "Cannot invoke a getter of " + dClassName +
                " with null attribute name");
    }

    // Call the corresponding getter for a recognized attribute_name
    if (attribute_name.equals("State")) {
        return getState();
    } 
    if (attribute_name.equals("NbChanges")) {
        return getNbChanges();
    }

    // If attribute_name has not been recognized
    throw(new AttributeNotFoundException(
        "Cannot find " + attribute_name + " attribute in " + dClassName));
}

// internal methods for getting attributes
public String getState() {
    return state;
}

public Integer getNbChanges() {
    return new Integer(nbChanges);
}

// internal variables representing attributes
private String      state = "initial state";
private int         nbChanges = 0;

The setAttribute method is more complicated, since you must also ensure that the given type can be assigned to the attribute and handle the special case for a null value:


Example 2–4 Implementation of the setAttribute Method

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

    // Check attribute to avoid NullPointerException later on
    if (attribute == null) {
        throw new RuntimeOperationsException(
            new IllegalArgumentException("Attribute cannot be null"),
            "Cannot invoke a setter of " + dClassName +
                " with null attribute");
    }
    // Note: Attribute class constructor ensures the name not null
    String name = attribute.getName();
    Object value = attribute.getValue();

    // Call the corresponding setter for a recognized attribute name
    if (name.equals("State")) {
        // if null value, try and see if the setter returns any exception
        if (value == null) {
            try {
                setState( null );
            } catch (Exception e) {
                throw(new InvalidAttributeValueException(
                    "Cannot set attribute "+ name +" to null")); 
            }
        }
        // if non null value, make sure it is assignable to the attribute
        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();
            }
        }
    }

    // optional: recognize an attempt to set a read-only attribute
    else if (name.equals("NbChanges")) {
        throw(new AttributeNotFoundException(
            "Cannot set attribute "+ name +
                " because it is read-only"));
    }

    // unrecognized attribute name
    else {
        throw(new AttributeNotFoundException(
            "Attribute " + name + " not found in " +
                this.getClass().getName()));
    }
}

// internal method for setting attribute
public void setState(String s) {
    state = s;
    nbChanges++;
}

Notice that if a change in your management solution requires you to change your management interface, it will be harder to do with a dynamic MBean. In a standard MBean, each attribute and operation is a separate method, so unchanged attributes are unaffected. In a dynamic MBean, you must modify the generic methods that encode all attributes.

Bulk Getters and Setters

The DynamicMBean interface includes bulk getter and setter methods for reading or writing more than one attribute at once. These methods rely on the classes shown in Table 2–2.

Table 2–2 Bulk Getter and Setter Classes

Class Name 

Description 

Attribute

A simple object that contains the name string and value object of any attribute 

AttributeList

A dynamically extendable list of Attribute objects (extends java.util.ArrayList)

The AttributeList class extends the java.util.ArrayList class.

The bulk getter and setter methods usually rely on the generic getter and setter, respectively. This makes them independent of the management interface, which can simplify certain modifications. In this case, their implementation consists mostly of error checking on the list of attributes. However, all bulk getters and setters must be implemented so that an error on any one attribute does not interrupt or invalidate the bulk operation on the other attributes.

If an attribute cannot be read, then its name-value pair is not included in the list of results. If an attribute cannot be written, it will not be copied to the returned list of successful set operations. As a result, if there are any errors, the lists returned by bulk operators will not have the same length as the array or list passed to them. In any case, the bulk operators do not guarantee that their returned lists have the same ordering of attributes as the input array or list.

The SimpleDynamic MBean shows one way of implementing the bulk getter and setter methods:


Example 2–5 Implementation of the Bulk Getter and Setter Methods

public AttributeList getAttributes(String[] attributeNames) {

    // Check attributeNames to avoid NullPointerException later on
    if (attributeNames == null) {
        throw new RuntimeOperationsException(
            new IllegalArgumentException(
                "attributeNames[] cannot be null"),
            "Cannot invoke a getter of " + dClassName);
    }
    AttributeList resultList = new AttributeList();

    // if attributeNames is empty, return an empty result list
    if (attributeNames.length == 0)
            return resultList;
        
    // build the result attribute list
    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) {
            // print debug info but continue processing list
            e.printStackTrace();
        }
    }
    return(resultList);
}

public AttributeList setAttributes(AttributeList attributes) {

    // Check attributesto avoid NullPointerException later on
    if (attributes == null) {
        throw new RuntimeOperationsException(
            new IllegalArgumentException(
                "AttributeList attributes cannot be null"),
            "Cannot invoke a setter of " + dClassName);
    }
    AttributeList resultList = new AttributeList();

    // if attributeNames is empty, nothing more to do
    if (attributes.isEmpty())
        return resultList;

    // try to set each attribute and add to result list if successful
    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) {
            // print debug info but keep processing list
            e.printStackTrace();
        }
    }
    return(resultList);
}

Generic Operation Invoker

A dynamic MBean must implement the invoke method so that operations in the management interface can be called. This method requires the same considerations as the generic getter and setter:

The implementation in the SimpleDynamic MBean is relatively simple due to the one operation with no parameters:


Example 2–6 Implementation of the invoke Method

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

    // Check operationName to avoid NullPointerException later on
    if (operationName == null) {
        throw new RuntimeOperationsException(
            new IllegalArgumentException(
                "Operation name cannot be null"),
            "Cannot invoke a null operation in " + dClassName);
    }

    // Call the corresponding operation for a recognized name
    if (operationName.equals("reset")){
        // this code is specific to the internal "reset" method:
        reset();     // no parameters to check
        return null; // and no return value
    } else { 
        // unrecognized operation name:
        throw new ReflectionException(
            new NoSuchMethodException(operationName), 
            "Cannot find the operation " + operationName +
                " in " + dClassName);
    }
}

// internal variable
private int         nbResets = 0;

// internal method for implementing the reset operation
public void reset() {
    state = "initial state";
    nbChanges = 0;
    nbResets++;
}

// Method not revealed in the MBean description and not accessible
// through "invoke" therefore it is only available for internal mgmt
public Integer getNbResets() {
    return new Integer(nbResets);
}

As it is written, the SimpleDynamic MBean correctly provides a description of its management interface and implements its attributes and operations. However, this example demonstrates the need for a strict coherence between what is exposed by the getMBeanInfo method and what can be accessed through the generic getters, setters, and invoker.

A dynamic MBean whose getMBeanInfo method describes an attribute or operation that cannot be accessed is not compliant with the JMX specification and is technically not a manageable resource. Similarly, a class could make attributes or operations accessible without describing them in the returned MBeanInfo object. Since MBeans should raise an exception when an undefined attribute or operation is accessed, this would, again, technically not be a compliant resource.

Running the Dynamic MBean Example

The examplesDir/DynamicMBean directory contains the SimpleDynamic.java file that makes up the MBean. The DynamicMBean interface is defined in the javax.management package provided in the runtime JAR file (jdmkrt.jar) of the Java Dynamic Management Kit (DMK). This directory also contains a simple agent application that instantiates this MBean, calls its getMBeanInfo method to get its management interface, and manipulates its attributes and operations.

To Run the Dynamic MBean Example
  1. Compile all files in this directory with the javac command.

    For example, on the Solaris platform, type:


    $ cd examplesDir/DynamicMBean/
    $ javac -classpath classpath *.java
    
  2. To run the example, start the agent class that will interact with the SimpleDynamic MBean:


    $ java -classpath classpath DynamicAgent
    
  3. Press Enter when the application pauses, to step through the example.

    The agent application handles all input and output in this example and gives a view of the MBean at runtime.

This example demonstrates how the management interface encoded in the getMBeanInfo method is made visible in the agent application. We can then see the result of calling the generic getters and setters and the invoke method. Finally, the code for filtering attribute and operation errors is exercised, and we see the exceptions from the code samples as they are raised at runtime.

Comparison With the SimpleStandard Example

Now that we have implemented both types of MBeans, we can compare how they are managed. We intentionally created a dynamic MBean and a standard MBean with the same management interface so that we can do exactly the same operations on them. On the Solaris platform, we can compare the relevant code of the two agent applications with the diff utility (your output might vary):


$ cd examplesDir
$ diff ./StandardMBean/StandardAgent.java ./DynamicMBean/DynamicAgent.java
[...]
41c40
< public class StandardAgent {
---
> public class DynamicAgent {
49c48
<     public StandardAgent() {
---
>     public DynamicAgent() {
77c76
<       StandardAgent agent = new StandardAgent();
---
>       DynamicAgent agent = new DynamicAgent();
88c87
<       echo("\n>>> END of the SimpleStandard example:\n");
---
>       echo("\n>>> END of the SimpleDynamic example:\n");
113c112
<       String mbeanName = "SimpleStandard";
---
>       String mbeanName = "SimpleDynamic";

If the two agent classes had the same name, the only programmatic difference would be the following:


113c112
<       String mbeanName = "SimpleStandard";
---
>       String mbeanName = "SimpleDynamic";

We can see that the only difference between the two example agents handling different types of MBeans is the name of the MBean class that is instantiated. In other words, standard and dynamic MBeans are indistinguishable from the agent's point of view. The JMX architecture enables managers to interact with the attributes and operations of a manageable resource, and the specification of the agent hides any implementation differences between MBeans.

Because we know that the two MBeans are being managed identically, we can also compare their runtime behavior. In doing so, we can draw two conclusions:

Dynamic MBean Execution Time

In the introduction to this chapter we presented two structural advantages of dynamic MBeans, namely the ability to wrap existing code to make it manageable and the ability to provide a self-description of the MBean and its features. Another advantage is that using dynamic MBeans can lead to faster overall execution time.

The performance gain depends on the nature of the MBean and how it is managed in the agent. For example, the SimpleDynamic MBean, as it is used, is probably not measurably faster than the SimpleStandard example in Chapter 1, Standard MBeans. When seeking improved performance, there are two situations that must be considered:

Because the dynamic MBean provides its own description, the agent does not need to introspect it as it would a standard MBean. Since introspection is done only once by the agent, this is a one-time performance gain during the lifetime of the MBean. In an environment where there are many MBean creations and where MBeans have a short lifetime, a slight performance increase can be measured.

However, the largest performance gain is in the management operations, when calling the getters, setters and invoker. As we shall see in Part II, the agent makes MBeans manageable through generic getters, setters, and invokers. In the case of standard MBeans, the agent must do the computations for resolving attribute and operation names according to the design patterns. Because dynamic MBeans necessarily expose the same generic methods, these are called directly by the agent. When a dynamic MBean has a simple management interface requiring simple programming logic in its generic methods, its implementation can show a better performance than the same functionality in a standard MBean.

Chapter 3 Model MBeans

A model MBean is a generic, configurable MBean that applications can use to instrument any resource dynamically. It is a dynamic MBean that has been implemented so that its management interface and its actual resource can be set programmatically. This enables any manager connected to a Java dynamic management agent to instantiate and configure a model MBean dynamically.

Model MBeans enable management applications to make resources manageable at runtime. The managing application must provide a compliant management interface for the model MBean to expose. It must also specify the target objects that actually implement the resource. Once it is configured, the model MBean passes any management requests to the target objects and handles the result.

In addition, the model MBean provides a set of mechanisms for how management requests and their results are handled. For example, caching can be performed on attribute values. The management interface of a model MBean is augmented by descriptors that contain attributes for controlling these mechanisms.

The code samples in this chapter are taken from the files in the ModelMBean example directory in the main examplesDir (see “Directories and Classpath” in the Preface).

This chapter covers the following topics:

RequiredModelMBean Class

The required model MBean is mandated by the JMX specification for all compliant implementations. It is a dynamic MBean that lacks any predefined management interface. It contains a generic implementation that transmits management requests on its management interface to the target objects that define its managed resource.

The name of the required model MBean class is the same for all JMX-compliant implementations. Its full package and class name is javax.management.modelmbean.RequiredModelMBean. By instantiating this class, any application can use model MBeans.

In order to be useful, the instance of the required model MBean must be given a management interface and the target object of the management resource. In addition, the model MBean metadata must contain descriptors for configuring how the model MBean will respond to management requests. We will cover these steps in subsequent sections.

The MBean server does not make any special distinction for model MBeans. Internally they are treated as the dynamic MBeans that they are, and all of the model MBean's internal mechanisms and configurations are completely transparent to a management application. Like all other managed resources in the MBean server, the resources available through the model MBean can only be accessed through the attributes and operations defined in the management interface.

Model MBean Metadata

The metadata of an MBean is the description of its management interface. The metadata of the model MBean is described by an instance of the ModelMBeanInfo class, which extends the MBeanInfo class.

Like all other MBeans, the metadata of a model MBean contains the list of attributes, operations, constructors, and notifications of the management interface. Model MBeans also describe their target object and their policies for accessing the target object. This information is contained in an object called a descriptor, defined by the Descriptor interface and implemented in the DescriptorSupport class.

There is one overall descriptor for a model MBean instance and one descriptor for each element of the management interface, that is for each attribute, operation, constructor, and notification. Descriptors are stored in the metadata object. As defined by the JMX specification, all classes for describing elements are extended so that they contain a descriptor. For example, the ModelMBeanAttributeInfo class extends the MBeanAttributeInfo class and defines the methods getDescriptor and setDescriptor.

A descriptor is a set of named field and value pairs. Each type of metadata element has a defined set of fields that are mandatory, and users are free to add others. The field names reflect the policies for accessing target objects, and their values determine the behavior. For example, the descriptor of an attribute contains the fields currencyTimeLimit and lastUpdatedTimeStamp that are used by the internal caching mechanism when performing a get or set operation.

In this way, model MBeans are manageable in the same way as any other MBean, but applications that are aware of model MBeans can interact with the additional features they provide. The JMX specification defines the names of all required descriptor fields for each of the metadata elements and for the overall descriptor. The field names are also documented in the Javadoc API for the ModelMBean*Info classes.

InExample 3–1 , the application defines a subroutine to build all descriptors and metadata objects needed to define the management interface of the model MBean.


Example 3–1 Defining Descriptors and MBeanInfo Objects

private void buildModelMBeanInfo(
                 ObjectName inMbeanObjectName, String inMbeanName) {
  try {

    // Create the descriptor and ModelMBeanAttributeInfo
    // for the 1st attribute
    //
    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);

    [...] // create descriptors and ModelMBean*Info for
          // all attributes, operations, constructors
          // and notifications

    // Create the descriptor for the whole MBean
    //
    mmbDesc = new DescriptorSupport( new String[] 
                      { ("name="+inMbeanObjectName),
                        "descriptorType=mbean",
                        ("displayName="+inMbeanName),
                        "log=T",
                        "logfile=jmxmain.log",
                        "currencyTimeLimit=5"});

    // Create the ModelMBeanInfo for the whole MBean
    // 
    private String dClassName = "TestBean";
    private String dDescription =
       "Simple implementation of a test app Bean.";

    dMBeanInfo = new ModelMBeanInfoSupport(
                         dClassName,
                         dDescription,
                         dAttributes,
                         dConstructors,
                         dOperations,
                         dNotifications);

    dMBeanInfo.setMBeanDescriptor(mmbDesc);

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

Target Object(s)

The object instance that actually embodies the behavior of the managed resource is called the target object. The last step in creating a model MBean is to give the MBean skeleton and its defined management interface a reference to the target object. Thereafter, the model MBean can handle management requests, forward them to the target object, and handle the response.

Example 3–2 implements the TestBean class that is the simple managed resource in our example. Its methods provide the implementation for two attributes and one operation.


Example 3–2 Implementing the Managed Resource

public class TestBean 
   implements java.io.Serializable
{

    // Constructor
    //
    public TestBean() {
        echo("\n\tTestBean Constructor Invoked: State " + 
             state + " nbChanges: " + nbChanges +
             " nbResets: " + nbResets);

    }

    // Getter and setter for the "State" attribute
    //
    public String getState() {
        echo("\n\tTestBean: getState invoked: " + state);
        return state;
    }

    public void setState(String s) {
        state = s;
        nbChanges++;
        echo("\n\tTestBean: setState to " + state +
             " nbChanges: " + nbChanges);
    }


    // Getter for the read-only "NbChanges" attribute
    //
    public Integer getNbChanges() {
        echo("\n\tTestBean: getNbChanges invoked: " + nbChanges);
        return new Integer(nbChanges);
    }

    // Method of the "Reset" operation
    //
    public void reset() {
        echo("\n\tTestBean: reset invoked ");
        state = "reset initial state";
        nbChanges = 0;
        nbResets++;
    }

    // Other public method; looks like a getter,
    // but no NbResets attribute is defined in
    // the management interface of the model MBean
    //
    public Integer getNbResets() {
        echo("\n\tTestBean: getNbResets invoked: " + nbResets);
        return new Integer(nbResets);
    }

    // Internals
    //
    private void echo(String outstr) {
        System.out.println(outstr);
    }

    private String  state = "initial state";
    private int     nbChanges = 0;
    private int     nbResets = 0;

}

By default, the model MBean handles a managed resource that is contained in one object instance. This target is specified through the setManagedResource method defined by the ModelMBean interface. The resource can encompass several programmatic objects because individual attributes or operations can be handled by different target objects. This behavior is configured through the optional targetObject and targetType descriptor fields of each attribute or operation.

In Example 3–3, one of the operations is handled by an instance of the TestBeanFriend class. In the definition of this operation's descriptor, we set this instance as the target object. We then create the operation's ModelMBeanOperationInfo with this descriptor and add it to the list of operations in the metadata for our model MBean.


Example 3–3 Setting Other Target Objects

MBeanParameterInfo[] params = null;

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 performed",
                         params ,
                         "java.lang.Integer",
                         MBeanOperationInfo.INFO,
                         getNbResetsDesc);

Creating a Model MBean

To ensure coherence in an agent application, you should define the target object of an MBean before you expose it for management. This implies that you should call the setManagedResource method before registering the model MBean in the MBean server.

Example 3–4 shows how our application creates the model MBean. First it calls the subroutine given in Example 3–1 to build the descriptors and management interface of the model MBean. Then it instantiates the required model MBean class with this metadata. Finally, it creates and sets the managed resource object before registering the model MBean.


Example 3–4 Setting the Default Target Object

ObjectName mbeanObjectName = null;
String domain = server.getDefaultDomain();
String mbeanName = "ModelSample";

try
{
     mbeanObjectName = new ObjectName(
                               domain + ":type=" + mbeanName);
} catch (MalformedObjectNameException e) {
     e.printStackTrace();
     System.exit(1);
}

// Create the descriptors and ModelMBean*Info objects
// of the management interface
//
ModelMBeanInfo dMBeanInfo = null;
buildModelMBeanInfo( mbeanObjectName, mbeanName );

try {
    // Instantiate javax.management.modelmbean.RequiredModelMBean
    RequiredModelMBean modelmbean =
        new RequiredModelMBean( dMBeanInfo );

    // Associate it with the resource (a TestBean instance)
    modelmbean.setManagedResource( new TestBean(), "objectReference");

    // register the model MBean in the MBean server
    server.registerMBean( modelmbean, mbeanObjectName );

} catch (Exception e) {
     echo("\t!!! ModelAgent: Could not create the model MBean !!!");
     e.printStackTrace();
     System.exit(1);
}

The model MBean is now available for management operations and remote requests, just like any other registered MBean.

Running the Model MBean Example

The examplesDir/ModelMBean directory contains the TestBean.java file that is the target object of the sample model MBean. This directory also contains a simple notification listener class and the agent application, ModelAgent, which instantiates, configures, and manages a model MBean.

The model MBean itself is given by the RequiredModelMBean class defined in the javax.management.modelmbean package provided in the runtime JAR file (jdmkrt.jar) of the Java Dynamic Management Kit (DMK).

To Run the Model MBean Example
  1. Compile all files in this directory with the javac command.

    For example, on the Solaris platform, type:


    $ cd examplesDir/ModelMBean/
    $ javac -classpath classpath *.java
    
  2. To run the example, start the agent class with the following command:


    $ java -classpath classpath ModelAgent
    
  3. Press Enter when the application pauses to step through the example.

    The agent application handles all input and output in this example and gives a view of the MBean at runtime.

We can then see the result of managing the resource through its exposed attributes and operations. The agent also instantiates and registers a listener object for attribute change notifications sent by the model MBean. You can see the output of this listener whenever it receives a notification, after the application has called one of the attribute setters.

Chapter 4 Open MBeans

Open MBeans are dynamic MBeans, with specific constraints on their data types, that allow management applications and their human administrators to understand and use new managed objects as they are discovered at runtime. Open MBeans provide a flexible means of instrumenting resources which need to be open to a wide range of applications compliant with the Java Management Extensions (JMX) specification.

To provide its own description to management applications, an open MBean must be a dynamic MBean, with the same behavior and functionality as a dynamic MBean. Thus it implements the DynamicMBean interface and no corresponding open MBean interface is required. The open functionality of open MBeans is obtained by providing descriptively rich metadata and by using exclusively certain predefined data types in the management interface.

Because open MBeans build their data types from a predefined set of Java classes, a management application can manage an agent that uses open MBeans, without having to load Java classes specific to that agent. Furthermore, a JMX connector or adaptor only needs to be able to transport classes from the predefined set, not arbitrary Java classes. This means, for example, that a connector could use eXtensible Markup Language (XML) as its transport by defining an XML schema that covers the MBean server operations and the predefined open MBean data types. It also means that a management application could run in a language other than Java.

The code samples in this chapter are taken from the files in the OpenMBean and OpenMBean2 example directories located in the main examplesDir (see “Directories and Classpath” in the Preface).

This chapter covers the following topics:

Open MBean Data Types

Open MBeans refer exclusively to a limited, predefined set of data types, which can be combined into compound types.

Supported Data Types

All open MBean attributes, method return values, and method arguments must be limited to the set of open MBean data types listed in this section. This set is defined as: the wrapper objects that correspond to the Java primitive types (such as Integer, Long, Boolean), String, CompositeData, TabularData, and ObjectName.

In addition, any array of the open MBean data types may be used in open MBeans. A special class, javax.management.openmbean.ArrayType is used to represent the definition of single or multi-dimensional arrays in open MBeans.

The following list specifies all data types that are allowed as scalars or as any-dimensional arrays in open MBeans:

In addition the following type may be used, but only as the return type of an operation:

Type Descriptor Classes

Open types are descriptor classes that describe the open MBean data types. To be able to manipulate the open MBean data types, management applications must be able to identify them. While primitive types are given by their wrapper class names, and arrays can be represented in a standard way, the complex data types need more structure than a flat string to represent their contents. Therefore open MBeans rely on description classes for all the open MBean data types, including special structures for describing complex data.

The abstract OpenType class is the superclass for the following specialized open type classes:

The CompositeType, TabularType, and ArrayType classes are recursive, that is, they can contain instances of other open types.

Open Data Instances

All of the wrapper classes for the primitive types are defined and implemented in all Java virtual machines, as is java.lang.String. The ObjectName class is provided by the implementation of the JMX specification. You can use the CompositeData and TabularData interfaces to define aggregates of the open MBean data types and provide a mechanism for expressing complex data objects in a consistent manner.

All open data instances corresponding to the open MBean types defined in Supported Data Types, except CompositeData and TabularData instances, are available through the classes of the JDK or JMX specification.

CompositeData and TabularData Instances

The CompositeData and TabularData interfaces represent complex data types. The JMX specification now includes a default implementation of these interfaces, using the CompositeDataSupport and TabularDataSupport classes respectively.

The CompositeData and TabularData interfaces and implementations provide some semantic structure to build aggregates from the open MBean data types. An implementation of the CompositeData interface is equivalent to a map with a predefined list of keys: values are retrieved by giving the name of the desired data item. Other terms commonly used for this sort of data type are record or struct.

An instance of a TabularData object contains a set of CompositeData instances. Each CompositeData instance in a TabularData instance is indexed by a unique key derived from its values, as described in TabularDataSupport Class.

A CompositeData object is immutable once instantiated: you cannot add an item to it and you cannot change the value of an existing item. TabularData instances are modifiable: rows can be added or removed from existing instances.

CompositeDataSupport Class

A CompositeData object associates string keys with the values of each data item. The CompositeDataSupport class defines an immutable map with an arbitrary number of entries, called data items, which can be of any type. To comply with the design patterns for open MBeans, all data items must have a type among the set of open MBean data types, including other CompositeData types.

When instantiating the CompositeDataSupport class, you must provide the description of the composite data object in a CompositeType object (see Type Descriptor Classes). All the items provided through the constructor must match this description. Because the composite object is immutable, all items must be provided at instantiation time, and therefore the constructor can verify that the items match the description. The getOpenType method returns this description so that other objects which interact with a CompositeData object can know its structure.

TabularDataSupport Class

The TabularDataSupport class defines a table structure with an arbitrary number of rows which can be indexed by any number of columns. Each row is a CompositeData object, and all rows must have the same composite data description. The columns of the table are headed by the names of the data items which make up the uniform CompositeData rows. The constructor and the methods for adding rows verify that all rows are described by equal CompositeData instances.

The index consists of a subset of the data items in the common composite data structure. This subset must be a key which uniquely identifies each row of the table. When the table is instantiated, or when a row is added, the methods of this class ensure that the index can uniquely identify all rows. Often the index will be a single column, for instance a column containing unique strings or integers.

Both the composite data description of all rows and the list of items which form the index are given by the table description returned by the getOpenType method. This method defined in the TabularData interface returns the TabularType object which describes the table (see Type Descriptor Classes).

The access methods of the TabularData class take an array of objects representing a key value which indexes one row and returns the CompositeData instance which makes up the designated row. A row of the table can also be removed by providing its key value. All rows of the table can also be retrieved in an enumeration.

Open MBean Metadata Classes

To distinguish open MBeans from other MBeans, the JMX specification provides a set of metadata classes which are used specifically to describe open MBeans.

The following interfaces in the javax.management.openmbean package define the management interface of an open MBean:

For each of these interfaces, a support class provides an implementation. Each of these classes describes a category of components in an open MBean. However, open MBeans do not have a specific metadata object for notifications; they use the MBeanNotificationInfo class.

Open MBeans provide a universal means of exchanging management functionality and consequently their description must be explicit enough for any user to understand. All of the OpenMBean*Info metadata classes inherit the getDescription method which should return a non-empty string. Each component of an open MBean must use this method to provide descriptions that are suitable for displaying in a graphical user interface.

Only the OpenMBeanOperationInfo specifies the getImpact method. Instances of OpenMBeanOperationInfo.getImpact must return one of the following constant values:

The value UNKNOWN cannot be used.

Running the Open MBean Examples

The examples directory provides two examples that demonstrate how to implement and manage an open MBean.

Open MBean Example 1

In the first open MBean example, we implement an open MBean and manage it through a simple JMX agent application. We develop a sample open MBean that uses some of the open data types and correctly exposes its management interface at runtime through the OpenMBean*Info classes. We then develop a simple JMX agent for exercising the open MBean, which involves:

The examplesDir/OpenMBean directory contains the SampleOpenMBean.java file, which is an open MBean, and the OpenAgent.java file which is a simple JMX agent used to interact with the open MBean.

To Run Open MBean Example 1
  1. Compile all files in the examplesDir/OpenMBean directory with the javac command.

    For example, on the Solaris platform, type:


    $ cd examplesDir/OpenMBean/
    $ javac -classpath classpath *.java
    
  2. Run the agent class that interacts with the open MBean:


    $ java -classpath classpath OpenAgent
    
  3. Press Enter when the application pauses, to step through the example.

    You interact with the agent through the standard input and output in the window where it was launched. The OpenAgent displays information about each management step and waits for your input before continuing.

Open MBean Example 2

In the second open MBean example, we implement an open MBean and manage it through a simple JMX manager application. Although it is helpful to run the first open MBean example before this example, it is not obligatory.

We develop a sample open MBean that uses some of the open data types and correctly exposes its management interface at runtime through the OpenMBean*Info classes. See the README2.html file in the examplesDir/OpenMBean2/README2 directory for more detailed information on the data structure of this example.

We then develop a simple manager for exercising the open MBean, which involves:

The examplesDir/OpenMBean2 directory contains the following source files:

To Run Open MBean Example 2
  1. Compile all files in the examplesDir/OpenMBean2 directory with the javac command.

    For example, on the Solaris platform, type:


    $ cd examplesDir/OpenMBean2/
    $ javac -classpath classpath *.java
    
  2. Run the agent class that interacts with the open MBean:


    $ java -classpath classpath Agent
    
  3. Open a second terminal window and change to the OpenMBean2 example directory:

    For example, on the Solaris platform, type:


    $ cd examplesDir/OpenMBean2/
    

    You can open this second terminal window on another host.

  4. Run the manager class:

    • If you are using a second terminal window on the same host as the agent class, type:


      $ java -classpath classpath Manager
      
    • If you are using another host, type:


      $ java -classpath classpath Manager hostname
      

      where hostname is the name or IP address of the host on which the agent is running.

    Interact with the manager through the standard input and output in the window where it was started. The Manager class displays information about each management step and waits for your input before continuing.