Developing Custom Management Utilities with JMX

     Previous  Next    Open TOC in new window    View as PDF - New Window  Get Adobe Reader - New Window
Content starts here

Using Notifications and Monitor MBeans

JMX provides two ways to monitor MBeans: MBeans can emit notifications when specific events occur (such as a change in an attribute value), or a special type of MBean called a monitor MBean can poll another MBean and periodically emit notifications to describe an attribute value. You create Java classes called listeners that listen for these notifications and respond appropriately. For example, your management utility can include a listener that receives notifications when applications are deployed, undeployed, or redeployed.

All WebLogic Server configuration MBeans emit notifications when attribute values change, and some runtime MBeans do.

The following sections describe working with notifications and listeners:

 


Best Practices: Listening Directly Compared to Monitoring

If the MBean that you want to monitor emits notifications, you can choose whether to create a listener object that listens for changes in the MBean or a monitor MBean that periodically polls the MBean and emits notifications only when its attributes change in specific ways. The technique that you choose depends mostly on the complexity of the situations in which you want to receive notifications.

If your requirements are simple, registering a listener directly with an MBean is the preferred technique because the MBean pushes its notifications to your listener and you are notified of a change almost immediately. However, the base classes that you implement for a listener and optional filter (javax.management.NotificationListener and NotificationFilter) provide few facilities for comparing values with thresholds and other values. (See the javax.management package in the J2SE 5.0 API Specification.)

If your notification requirements are sufficiently complex, or if you want to monitor a group of changes that are not directly associated with a single change in the value of an MBean attribute, use a monitor MBean. (See the javax.management.monitor package in the J2SE 5.0 API Specification.) The monitor MBeans provide a rich set of tools for comparing data and sending notifications only under specific circumstances. However, the monitor periodically polls the observed MBean for changes in attribute value and you are notified of a change only as frequently as the polling interval that you specify.

 


Best Practices: Listening for WebLogic Server Events

The WebLogic Server JMX agent and WebLogic Server MBeans emit different types of notification objects for different types of events. Many event types trigger multiple MBeans to emit notifications at different points within the event process. Table 7-1 describes common event types and recommends the MBean with which a JMX monitoring application should register to listen for notifications.

Note: Each JMX notification object contains an attribute named Type, which contains a dot-delimited string. Do not confuse discussions of this Type attribute with a notification’s object type.
Note: The Type attribute offers a way to categorize and filter notifications. For example, if your custom MBeans emit notifications, JMX conventions suggest that you set your notification object’s Type attribute to a string that starts with your company name: mycompany.myapp.valueIncreased.
Note: All JMX notification objects extend the javax.management.Notification object type. JMX and WebLogic Server define additional notification object types, such as javax.management.AttributeChangeNotification. The additional object types contain specialized sets of information that are appropriate for different types of events. (See the list of Notification subclasses for javax.management.Notification in the J2SE 5.0 API Specification. Also see weblogic.management.logging.WebLogicLogNotification in the WebLogic Server API Reference.)

Table 7-1 Events and Notification Objects
Event
Listening Recommendation
A WebLogic Server instance starts or stops
To receive a notification when a server starts or stops, register a listener with each server’s ServerLifeCycleRuntimeMBean in the Domain Runtime MBean Server and configure an AttributeChangeNotificationFilter.
Each server in a domain provides its own ServerLifeCycleRuntimeMBean, which is available through the Domain Runtime MBean Server even if the server itself is not active. When you start a server instance, the server’s ServerLifeCycleRuntimeMBean updates the value of its State attribute and emits an AttributeChangeNotification.
For an example of such a listener and filter, see Listening for Notifications from WebLogic Server MBeans: Main Steps.

Note: This recommendation assumes that you start a domain’s Administration Server before starting Managed Servers. If a Managed Server starts before the Administration Server, a listener in the Domain Runtime MBean Server (which runs only on the Administration Server) will not be initialized at the time the Managed Server’s ServerLifeCycleRuntimeMBean changes its state to RUNNING. If you cannot guarantee that the Administration Server starts first, use the JMX timer service to periodically query the Domain Runtime MBean Server for MBeans whose object name contains the Type=ServerRuntime key property. An MBean that matches this query is a ServerRuntimeMBean, which each server instance creates as part of its startup process. If the query finds a newly created ServerRuntimeMBean, you know that a new server instance has been started. See MBeanServerConnection queryNames.

A WebLogic Server resource is created or destroyed
When you create a resource such as a server or a JDBC data source, WebLogic Server registers the resource’s configuration MBean in the MBean server. When you delete a resource, WebLogic Server unregisters the configuration MBean.
To listen for the registration and unregistration of MBeans, register a listener with javax.management.MBeanServerDelegate, which emits notifications of type javax.management.MBeanServerNotification
when MBeans are registered or unregistered.
If you register a listener with MBeanServerDelegate in the Edit MBean Server, you receive notifications when someone modifies the pending MBean hierarchy.
If you register a listener in the Runtime MBean Server or the Domain Runtime MBean Server, you receive notifications only when pending changes have been successfully activated in the domain. If you are interested solely in monitoring configuration data (and are not interested in monitoring runtime statistics), register your listener in only one Runtime MBean Server. See Best Practices: Choosing an MBean Server.
The configuration of a WebLogic Server resource is modified
All configuration MBeans emit notifications of type AttributeChangeNotification when their attribute values change.
To receive this notification, register a listener with the MBean that is in the Domain Runtime MBean Server or Runtime MBean Server (see Best Practices: Choosing an MBean Server).
If you register an MBean in the Edit MBean Server, you receive notifications when someone modifies the pending MBean hierarchy.
If you register a listener in the Runtime MBean Server or the Domain Runtime MBean Server, you receive notifications only when pending changes have been successfully activated in the domain. If you are interested solely in monitoring configuration data (and are not interested in monitoring runtime statistics), register your listener in only one Runtime MBean Server. See Best Practices: Choosing an MBean Server.
The runtime state of a WebLogic Server resource changes
Some runtime MBeans emit notifications of type AttributeChangeNotification when their attribute values change. To receive this notification, register a listener with the MBean in the Domain Runtime MBean Server.
If a runtime MBean does not emit notifications, you can create a monitor MBean that polls the runtime MBean. See Using Monitor MBeans to Observe Changes: Main Steps.
A WebLogic Server resource emits a log message
When a WebLogic Server resource generates a log message, the server’s weblogic.management.runtime.LogBroadcasterRuntimeMBean emits a notification of type weblogic.management.logging.WebLogicLogNotification, which can be cast as the standard javax.management.Notification class.
To listen for log message notifications, register a listener with LogBroadcasterRuntimeMBean. You can listen for the standard JMX notifications, or if you want to retrieve detailed information about the log messages, listen for WebLogicLogNotifications, which contains methods that you can use to retrieve detailed information. Listening for WebLogicLogNotifications requires you to import this WebLogic Server class into your listener class.
To see a list of error messages that WebLogic Server resources generate, refer to WebLogic Server Message Catalogs.
For more information, see WebLogicLogNotification in the WebLogic Server API Reference.

 


Best Practices: Listening or Monitoring WebLogic Server Runtime Statistics

WebLogic Server MBeans provide detailed statistics on the runtime state of its services and resources. The statistics in Table 7-2 provide a general overview of the performance of WebLogic Server. You can listen for changes to these statistics by creating a listener and registering it directly with the MBeans that contain the attributes or you can configure monitor MBeans to periodically poll and report only the statistics that you consider to be significant. (See Registering a Notification Listener and Filter and Registering the Monitor and Listener.)

Table 7-2 Commonly Monitored WebLogic Server Runtime Statistics
To track this statistic...
Listen or monitor this MBean attribute...
The current state of server.
Attribute Name: State
Activity on the server’s listen ports.
MBean Type: ServerRuntimeMBean
Attribute Name: OpenSocketsCurrentCount
MBean Type: ServerMBean
Attribute Name: AcceptBacklog
Use these two attributes together to compare the current activity on the server’s listen ports to the total number of requests that can be backlogged on the ports.
Memory and thread use.
Attribute Name: ExecuteThreadIdleCount
Indicates the number of threads in a server’s execute queue that are taking up memory space but are not being used to process data.
Attribute Name: PendingUserRequestCount
Indicates the number of user requests waiting in a server’s execute queue.
MBean Type: JVMRuntimeMBean
Attribute Name: HeapSizeCurrent
Indicates the amount of memory (in bytes) that is currently available in the server’s JVM heap.
Database connections.
Attribute Name: ActiveConnectionsCurrentCount
Indicates the current number of active connections in a JDBC connection pool.
Attribute Name: ActiveConnectionsHighCount
The high water mark of active connections in a JDBC connection pool. The count starts at zero each time the connection pool is instantiated.
Attribute Name: LeakedConnectionCount
Indicates the total number of leaked connections. Leaked connections are connections that have been checked out but never returned to the connection pool via a close() call; it is important to monitor the total number of leaked connections, as a leaked connection cannot be used to fulfill later connection requests.
Attribute Name: ConnectionDelayTime
Indicates the average time to connect to a connection pool.
Attribute Name: FailuresToReconnectCount
Indicates when the connection pool fails to reconnect to its data store. Applications may notify a listener when this attribute increments, or when the attribute reaches a threshold, depending on the level of acceptable downtime.

 


Listening for Notifications from WebLogic Server MBeans: Main Steps

To listen directly for the notifications that an MBean emits:

  1. Create a listener class in your application. See Creating a Notification Listener.
  2. Create an additional class that registers your listener and an optional filter with the MBean whose notifications you want to receive. See Configuring a Notification Filter and Registering a Notification Listener and Filter.
  3. Package and deploy the listener and registration class. See Packaging and Deploying Listeners on WebLogic Server.

Creating a Notification Listener

To create a notification listener:

  1. Create a class that implements javax.management.NotificationListener.
  2. See NotificationListener in the J2SE 5.0 API Specification.

  3. Within the class, add a NotificationListener.handleNotification(Notification notification, java.lang.Object handback) method.
  4. Note: Your implementation of this method should return as soon as possible to avoid blocking its notification broadcaster.
  5. (Optional) In most listening situations, you want to know more than the simple fact that an MBean has emitted a notification object. For example, you might want to know the value of the notification object’s Type attribute, which is used to classify the type of event that caused the notification to be emitted.
  6. To retrieve information from a notification object, within your handleNotification method invoke the object’s methods. Because all notification types extend javax.management.Notification, the following Notification methods are available for all notifications:

    • getMessage()
    • getSequenceNumber()
    • getTimeStamp()
    • getType()
    • getUserData()
    • See Notification in the J2SE 5.0 API Specification.

      Most notification types provide additional methods for retrieving data that is specific to the notification. For example, javax.management.AttributeChangeNotification provides getNewValue() and getOldValue(), which you can use to determine how the attribute value has changed.

Listing 7-1 is a simple listener that uses AttributeChangeNotification methods to retrieve the name of an attribute with a changed value, and the old and new values.

Listing 7-1 Notification Listener
import javax.management.Notification;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.AttributeChangeNotification;
public class MyListener implements NotificationListener {
    public  void handleNotification(Notification notification, Object obj) {
        if(notification instanceof AttributeChangeNotification) {
            AttributeChangeNotification attributeChange =
                     (AttributeChangeNotification) notification;
            System.out.println("This notification is an
                      AttributeChangeNotification");
            System.out.println("Observed Attribute: " +
                                       attributeChange.getAttributeName() );
            System.out.println("Old Value: " + attributeChange.getOldValue() );
            System.out.println("New Value: " + attributeChange.getNewValue() );
        }
    }
}

Listening from a Remote JVM

As of JMX 1.2, there are no special requirements for programming a listener that runs in a different JVM from the MBean to which it is listening.

Once you establish a connection to the remote JMX agent (using javax.management.MBeanServerConnection), JMX takes care of sharing data between the JVMs. See Registering a Notification Listener and Filter on page 7-11 for instructions on establishing a connection from a remote JVM.

Best Practices: Creating a Notification Listener

Consider the following recommendations while creating your NotificationListener class:

Configuring a Notification Filter

As of JDK 1.5, the JDK includes two simple filter classes that you can configure to forward notifications that match criteria that you specify. To configure one of the JDK’s filter classes:

  1. In the class that registers your listener with an MBean create an instance of javax.management.NotificationFilterSupport or AttributeChangeNotificationFilter.
  2. Invoke a filter class method to specify filter criteria.
  3. See NotificationFilterSupport or AttributeChangeNotificationFilter in the J2SE 5.0 API Specification.

For example, the following lines of code configure an AttributeChangeNotificationFilter that forwards only attribute change notifications and only if there is a change in an attribute named State:

AttributeChangeNotificationFilter filter =
   new AttributeChangeNotificationFilter();
filter.enableAttribute("State");

Creating a Custom Filter

If the JDK’s filter class is too simplistic for your needs, you can create more sophisticated, custom filter classes. (See NotificationFilter in the J2SE 5.0 API Specification.) However, Oracle recommends that you use the JDK filter classes whenever possible: using a custom filter complicates the packaging and deployment of your listener and filter. See Packaging and Deploying Listeners on WebLogic Server.

Registering a Notification Listener and Filter

After you implement a notification listener class, you create an additional class that registers your listener (and optionally configures and registers a filter) with an MBean instance.

To register a notification listener and filter with an MBean:

  1. Initialize a connection to a Runtime MBean Server or the Domain Runtime MBean Server.
  2. See Make Remote Connections to an MBean Server.

  3. To register with a WebLogic Server MBean, navigate the MBean hierarchy and retrieve an object name for the MBean that you want to listen to. See Navigate MBean Hierarchies.
  4. To register with a custom MBean, create an ObjectName that contains the MBean’s JMX object name. See javax.management.ObjectName in the J2SE 5.0 API Specification.

  5. Instantiate the listener class that you created.
  6. (Optional) Instantiate and configure one of the JDK’s filter classes or instantiate a custom class.
  7. Register the listener and filter by passing the MBean’s object name, listener class, and filter class to the MBeanServerConnection.addNotificationListener (
    ObjectName
    name, ObjectName listener, NotificationFilter filter,
    Object
    handback) method.

The example class registers the listener from Listing 7-1 and the JDK’s AttributeChangeNotificationFilter with all ServerLifeCycleRuntimeMBeans in a domain. The class does not pass a handback object.

In the example, weblogic is a user who has permission to view and modify MBean attributes. For information about permissions to view and modify MBeans, refer to "Users, Groups, and Security Roles" in Securing WebLogic Resources Using Roles and Policies.

The example class also includes some code that keeps the RegisterListener class active and not exit the main program. Usually this code is not necessary because a listener class runs in the context of some larger application that is responsible for invoking the class and keeping it active. It is included here so you can easily compile and see the example working.

Listing 7-2 Registering a Listener with ServerLifeCycleRuntimeMBean
import java.util.Hashtable;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.MalformedObjectNameException;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.naming.Context;
import javax.management.AttributeChangeNotificationFilter;
public class RegisterListener {
   private static MBeanServerConnection connection;
   private static JMXConnector connector;
   private static final ObjectName service;
   // Initializing the object name for DomainRuntimeServiceMBean
   // so it can be used throughout the class.
   static {
      try {
         service = new ObjectName(
         "com.bea:Name=DomainRuntimeService,Type=weblogic.management.mbeanserv
          ers.domainruntime.DomainRuntimeServiceMBean");
      }catch (MalformedObjectNameException e) {
         throw new AssertionError(e.getMessage());
      }
   }
   /*
    * Initialize connection to the Domain Runtime MBean server
    * each server in the domain hosts its own instance.
    */
   public static void initConnection(String hostname, String portString,
      String username, String password) throws IOException,
      MalformedURLException {
      String protocol = "t3";
      Integer portInteger = Integer.valueOf(portString);
      int port = portInteger.intValue();
      String jndiroot = "/jndi/";
      String mserver = "weblogic.management.mbeanservers.domainruntime";
      JMXServiceURL serviceURL = new JMXServiceURL(protocol, hostname, port,
         jndiroot + mserver);
      Hashtable h = new Hashtable();
      h.put(Context.SECURITY_PRINCIPAL, username);
      h.put(Context.SECURITY_CREDENTIALS, password);
      h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES,
         "weblogic.management.remote");
      connector = JMXConnectorFactory.connect(serviceURL, h);
      connection = connector.getMBeanServerConnection();
   }
   /*
    * Get an array of ServerLifeCycleRuntimeMBeans
    */
   public static ObjectName[] getServerLCRuntimes() throws Exception {
      ObjectName domainRT = (ObjectName) connection.getAttribute(service,
         "DomainRuntime");
      return (ObjectName[]) connection.getAttribute(domainRT,
         "ServerLifecycleRuntimes");
   }
   public static void main(String[] args) throws Exception {
      String hostname = args[0];
      String portString = args[1];
      String username = args[2];
      String password = args[3];
      try {
         //Instantiating your listener class.
         MyListener listener = new MyListener();
         AttributeChangeNotificationFilter filter =
            new AttributeChangeNotificationFilter();
         filter.enableAttribute("State");
         initConnection(hostname, portString, username, password);
         //Passing the name of the MBeans and your listener class to the
         //addNotificationListener method of MBeanServer.
         ObjectName[] serverLCRT = getServerLCRuntimes();
         int length= (int) serverLCRT.length;
         for (int i=0; i < length; i++) {
            connection.addNotificationListener(serverLCRT[i], listener,
               filter, null);
            System.out.println("\n[myListener]: Listener registered with"
               +serverLCRT[i]);
         }
      //Keeping the remote client active.
         System.out.println("pausing...........");
         System.in.read();
      } catch(Exception e) {
         System.out.println("Exception: " + e);
      }
   }
}

Packaging and Deploying Listeners on WebLogic Server

You can package and deploy a JMX listener as a remote application, a WebLogic Server startup class (which makes the listener available as soon as a server boots), or within one of your other applications that you deploy on WebLogic Server.

If you use a filter from the JDK, you do not need to package the filter class. It is always available through the JDK.

Table 7-3 describes how to package and deploy your listeners and any custom filters.

Table 7-3 Packaging and Deploying Listeners and Custom Filters
If you deploy the listener...
Do this for the listener...
Do this for a custom filter...
As a remote application
Make the listener’s class available on the remote client’s classpath.
Make the filter’s class available on the remote client’s classpath.
Also add the filter class to the classpath of each server instance that hosts the monitored MBeans by archiving the class in a JAR file and copying the JAR in each server’s lib directory. See Domain Directory Contents in Understanding Domain Configuration.
As a WebLogic Server startup class
Add the listener class to the server’s classpath by archiving the class in a JAR file and copying the JAR in the server’s lib directory.
Add the filter class to the server’s classpath by archiving the class in a JAR file and copying the JAR in the server’s lib directory. See Domain Directory Contents in Understanding Domain Configuration.
As part of an application that you deploy on WebLogic Server
Package the listener class with the application.
Package the listener class with the application.
Also add the filter class to the classpath of each server instance that hosts the monitored MBeans by doing one of the following:

Example: Listening for The Registration of Configuration MBeans

When you create a WebLogic Server resource, such as a server or a JDBC data source, WebLogic Server creates a configuration MBean and registers it in the Domain Runtime MBean Server.

To listen for these events, register a listener with javax.management.MBeanServerDelegate, which emits a notification of type
javax.management.MBeanServerNotification each time an MBean is registered or unregistered. See MBeanServerDelegate in the J2SE 5.0 API Specification.

Note the following about the example listener in Listing 7-3:

Listing 7-4 shows methods from a registration class. Note the following:

To compile and run these methods, use the supporting custom methods from Listing 7-2 and run the resulting class as a remote JMX client.

Listing 7-4 Example: Registering a Listener with MBeanServerDelegate
public static void main(String[] args) throws Exception {
   String hostname = args[0];
   String portString = args[1];
   String username = args[2];
   String password = args[3];
   ObjectName delegate = new ObjectName(
      "JMImplementation:type=MBeanServerDelegate");
   try {
      //Instantiating your listener class.
      StartStopListener slistener = new StartStopListener();
      NotificationFilterSupport filter = new NotificationFilterSupport();
      filter.enableType("JMX.mbean.registered");
      filter.enableType("JMX.mbean.unregistered");
      /* Invoke a custom method that establishes a connection to the
       * Domain Runtime MBean Server and uses an instance of
       * MBeanServerConnection to represents the connection. The custom
       * method assigns the MBeanServerConnection to a class-wide, static
       * variable named "connection".
       */
      initConnection(hostname, portString, username, password);
      //Passing the name of the MBeans and your listener class to the
      //addNotificationListener method of MBeanServer.
      connection.addNotificationListener(delegate, slistener, filter,
         null);
      System.out.println("\n[myListener]: Listener registered ...");
      //Keeping the remote client active.
      System.out.println("pausing...........");
      System.in.read();
   } catch (Exception e) {
      System.out.println("Exception: " + e);
   }
}
// Called by the listener if it receives notification of a
// JDBCDataSourceRuntimeMBean being registered.
public static void registerwithJDBCDataSourceRuntime(ObjectName mbname) {
   try {
      MyListener mylistener = new MyListener();
      AttributeChangeNotificationFilter filter =
         new AttributeChangeNotificationFilter();
      filter.enableAttribute("Enabled");
      connection.addNotificationListener(mbname, mylistener, 
         filter, null);
   } catch (Exception e) {
      System.out.println("Exception: " + e);
   }
}

 


Using Monitor MBeans to Observe Changes: Main Steps

To configure and use monitor MBeans:

  1. Choose the type of monitor MBean type that supports your monitoring needs. Monitor MBean Types and Notification Types
  2. Create a listener class that can listen for notifications from monitor MBeans. See Creating a Notification Listener for a Monitor MBean.
  3. Create a class that creates, registers and configures a monitor MBean, registers your listener class with the monitor MBean, and then starts the monitor MBean. See Registering the Monitor and Listener

Monitor MBean Types and Notification Types

JMX provides monitor MBeans that are specialized to observe specific types of changes:

All monitor MBeans emit notifications of type javax.management.monitor.MonitorNotification. When a monitor MBean generates a notification, it describes the event that generated the notification by writing a specific value into the notification’s Type property. Table 7-4 describes the value of the Type property that the different types of monitor MBeans encode. A filter or listener can use the notification’s getType() method to retrieve the String in the Type property.

Table 7-4 Monitor MBeans and the MonitorNotification Type Property
A Monitor MBean of This Type
Encodes This String in the MonitorNotification’s Type Property
CounterMonitor
jmx.monitor.counter.threshold when the value of the counter reaches or exceeds a threshold known as the comparison level.
GaugeMonitor
  • jmx.monitor.gauge.high if the observed attribute value is increasing and becomes equal to or greater than the high threshold value. Subsequent crossings of the high threshold value do not cause further notifications unless the attribute value becomes equal to or less than the low threshold value.
  • jmx.monitor.gauge.low if the observed attribute value is decreasing and becomes equal to or less than the low threshold value. Subsequent crossings of the low threshold value do not cause further notifications unless the attribute value becomes equal to or greater than the high threshold value.
StringMonitor
  • jmx.monitor.string.matches if the observed attribute value matches the string to compare value. Subsequent matches of the string to compare values do not cause further notifications unless the attribute value differs from the string to compare value.
  • jmx.monitor.string.differs if the attribute value differs from the string to compare value. Subsequent differences from the string to compare value do not cause further notifications unless the attribute value matches the string to compare value.

Errors and the MonitorNotification Type Property

If an error occurs, all monitors encode one of the following values in the notification’s Type property:

The counter and the gauge monitors can also encode jmx.monitor.error.threshold into the Type property under the following circumstances:

Creating a Notification Listener for a Monitor MBean

When an observed attributes meets the criteria that you specify, a monitor MBean emits a notification. There are no special requirements for creating a listener for a MonitorNotification. The steps are the same as those described in Creating a Notification Listener except:

See Listing 7-5.

Listing 7-5 Listener for Monitor Notifications
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.monitor.MonitorNotification;
public class MonitorListener implements NotificationListener {
   public void handleNotification(Notification notification, Object obj) {
      if(notification instanceof Notification) {
         Notification notif = (Notification) notification;
         System.out.println("Notification type" + notif.getType() );
         System.out.println("Message: " + notif.getMessage() );
      }
      if (notification instanceof MonitorNotification) {
         MonitorNotification mn = (MonitorNotification) notification;
         System.out.println("Observed Attribute: " +
             mn.getObservedAttribute());
         System.out.println("Trigger: " + mn.getTrigger() );
      }
   }
}

Registering the Monitor and Listener

Recall that to use a monitor MBean, you first must create and register an instance of the monitor MBean in the MBean server. Then you register a listener with the monitor MBean that you created. You can do all of this in a single class.

To register a monitor MBean, register your listener, and start the monitor MBean:

  1. Initialize a connection to the Domain Runtime MBean Server.
  2. See Make Remote Connections to an MBean Server.

  3. Create an ObjectName for your monitor MBean instance.
  4. See javax.management.ObjectName in the J2SE 5.0 API Specification.

    Oracle recommends that your object name starts with the name of your organization and includes key properties that clearly identifies the purpose of the monitor MBean instance.

    For example, mycompany:Name=SocketMonitor,Type=CounterMonitor

  5. Create and register one of the monitor MBeans.
  6. Use javax.management.MBeanServerConnection.createMBean(String classname ObjectName name) method where:

    • classname is one of the following values:
      javax.management.monitor.CounterMonitor
      javax.management.monitor.GaugeMonitor
      javax.management.monitor.StringMonitor
    • name is the object name that you created for the monitor MBean instance.
  7. Configure the monitor MBean by setting the value of its attributes.
  8. For guidelines on which attributes to set, see the javax.management.monitoring package in the J2SE 5.0 API Specification.

  9. To specify the MBean that your monitor MBean monitors (the observed MBean), invoke the monitor MBean’s addObservedObject(ObjectName objectname) and addObservedAttribute(String attributename) operations where.
    • objectname is the ObjectName of the observed MBean
    • attributename is the name of the attribute in the observed MBean that you want to monitor
    • A single instance of a monitor MBean can monitor multiple MBeans. Invoke the addObservedObject and addObservedAttribute operation for each MBean instance that you want to monitor.

  10. Instantiate the listener object that you created in Creating a Notification Listener for a Monitor MBean.
  11. Optionally instantiate and configure a filter.
  12. Register the listener and optional filter with the monitor MBean. Do not register the listener with the observed MBean.
  13. Invoke the monitor MBean’s addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) method.

  14. Start the monitor by invoking the monitor MBean’s start() operation.

Example: Registering a CounterMonitorMBean and Its Listener

Listing 7-6 shows the main() method of a class that creates and configures a CounterMonitorMBean to observe the SocketsOpenedTotalCount attribute in each ServerRuntimeMBean instance in a domain. (See SocketsOpenedTotalCount in WebLogic Server MBean Reference.)

The code example connects to the Domain Runtime MBean Server so that it can monitor multiple instances of ServerRuntimeMBean. Note the following:

To compile and run this main method, use the supporting custom methods from Listing 7-2 and run the resulting class as a remote JMX client.

Listing 7-6 Example: Registering a CounterMonitorMBean and Its Listener
public static void main(String[] args) throws Exception {
   String hostname = args[0];
   String portString = args[1];
   String username = args[2];
   String password = args[3];
   try {
      /* Invokes a custom method that establishes a connection to the
       * Domain Runtime MBean Server and uses an instance of
       * MBeanServerConnection to represents the connection. The custom
       * method assigns the MBeanServerConnection to a class-wide, static
       * variable named "connection".
       */
      initConnection(hostname, portString, username, password);
      //Creates and registers the monitor MBean.
      ObjectName monitorON =
         new ObjectName("mycompany:Name=mySocketMonitor,Type=CounterMonitor");
      String classname = "javax.management.monitor.CounterMonitor";
      System.out.println("===> create mbean "+monitorON);
      connection.createMBean(classname, monitorON);
      //Configure the monitor MBean.
      Number initThreshold = new Long(2);
      Number offset = new Long(1);
      connection.setAttribute(monitorON,
         new Attribute("InitThreshold", initThreshold));
      connection.setAttribute(monitorON, new Attribute("Offset", offset));
      connection.setAttribute(monitorON,
         new Attribute("Notify", new Boolean(true)));
      //Gets the object names of the MBeans that you want to monitor.
      ObjectName[] serverRT = getServerRuntimes();
      int length= (int) serverRT.length;
      for (int i=0; i < length; i++) {
         //Sets each instance of ServerRuntime MBean as a monitored MBean.
         System.out.println("===> add observed mbean "+serverRT[i]);
         connection.invoke(monitorON, "addObservedObject",
            new Object[] { serverRT[i] },
            new String[] { "javax.management.ObjectName" });
         Attribute attr = new Attribute("ObservedAttribute",
            "SocketsOpenedTotalCount");
         connection.setAttribute(monitorON, attr);
      }
      // Instantiates your listener class and configures a filter to
      // forward only counter monitor messages.
      MonitorListener listener = new MonitorListener();
      NotificationFilterSupport filter = new NotificationFilterSupport();
      filter.enableType("jmx.monitor.counter");
      filter.enableType("jmx.monitor.error");
      //Uses the MBean server's addNotificationListener method to
      //register the listener and filter with the monitor MBean.
      System.out.println("===> ADD NOTIFICATION LISTENER TO "+monitorON);
      connection.addNotificationListener(monitorON, listener, filter, null);
      System.out.println("\n[myListener]: Listener registered ...");
      //Starts the monitor.
      connection.invoke(monitorON, "start", new Object[] { }, new String[] { });
      //Keeps the remote client active.
      System.out.println("pausing...........");
      System.in.read();
   } catch(Exception e) {
      System.out.println("Exception: " + e);
      e.printStackTrace();
   }
}

  Back to Top       Previous  Next