Skip Headers
Oracle® Fusion Middleware Developing Custom Management Utilities With JMX for Oracle WebLogic Server
12c Release 1 (12.1.1)

Part Number E24415-02
Go to Documentation Home
Home
Go to Table of Contents
Contents
Go to Feedback page
Contact Us

Go to previous page
Previous
Go to next page
Next
PDF · Mobi · ePub

7 Using Notifications and Monitor MBeans

This chapter describes how to use JMX to 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 run-time MBeans do.

This chapter includes the following sections:

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 Java SE 6 API Specification at http://download.oracle.com/javase/6/docs/api/javax/management/package-summary.html.)

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 Java SE 6 API Specification at http://download.oracle.com/javase/6/docs/api/javax/management/monitor/package-summary.html.) 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.

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.

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 Java SE 6 API Specification at http://download.oracle.com/javase/6/docs/api/javax/management/Notification.html. 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 (see http://download.oracle.com/javase/6/docs/api/javax/management/MBeanServerConnection.html#queryNames(javax.management.ObjectName, javax.management.QueryExp).

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 run-time statistics), register your listener in only one Runtime MBean Server. See Best Practices: Choosing an MBean Server.

See Example: Listening for The Registration of Configuration MBeans.

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 run-time statistics), register your listener in only one Runtime MBean Server. See Best Practices: Choosing an MBean Server.

The run-time state of a WebLogic Server resource changes

Some run-time 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 run-time MBean does not emit notifications, you can create a monitor MBean that polls the run-time 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 Oracle WebLogic Server Error Message Reference.

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 run-time 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.

MBean Type: ServerLifeCycleRuntimeMBean

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.

MBean Type: ThreadPoolRuntimeMBean

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.

Memory and thread use

MBean Type: ThreadPoolRuntimeMBean

Attribute Name: PendingUserRequestCount

Indicates the number of user requests waiting in a server's execute queue.

Memory and thread use

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

MBean Type: JDBCDataSourceRuntimeMBean

Attribute Name: ActiveConnectionsCurrentCount

Indicates the current number of active connections in a JDBC connection pool.

Database connections

MBean Type: JDBCDataSourceRuntimeMBean

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.

Database connections

MBean Type: JDBCDataSourceRuntimeMBean

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.

Database connections

MBean Type: JDBCDataSourceRuntimeMBean

Attribute Name: ConnectionDelayTime

Indicates the average time to connect to a connection pool.

Database connections

MBean Type: JDBCDataSourceRuntimeMBean

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.

    See NotificationListener in the Java SE 6 API Specification at http://download.oracle.com/javase/6/docs/api/javax/management/NotificationListener.html.

  2. Within the class, add a NotificationListener.handleNotification(Notification notification, java.lang.Object handback) method.

    Note:

    Your implementation of this method should return as soon as possible to avoid blocking its notification broadcaster.

  3. (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.

    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 Java SE 6 API Specification at http://download.oracle.com/javase/6/docs/api/javax/management/Notification.html.

    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.

Example 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.

Example 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, 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:

  • Unless you use a notification filter, your listener receives all notifications (of all notification types) from the MBeans with which it is registered.

    Instead of using one listener for all possible notifications that an MBean emits, the best practice is to use a combination of filters and listeners. While having multiple listeners adds to the amount of time for initializing the JVM, the trade-off is ease of code maintenance.

  • If your WebLogic Server environment contains multiple instances of MBean types that you want to monitor, you can create one notification listener and then create as many registration classes as MBean instances that you want to monitor.

    For example, if your WebLogic Server domain contains three JDBC data sources, you can create one listener class that listens for AttributeChangeNotifications. Then, you create three registration classes. Each registration class registers the listener with a specific instance of JDBCDataSourceRuntimeMBean.

  • While the handleNotification method signature includes an argument for a handback object, your listener does not need to retrieve data from or otherwise manipulate the handback object. It is an opaque object that helps the listener to associate information regarding the MBean emitter.

  • Your implementation of the handleNotification method should return as soon as possible to avoid blocking its notification broadcaster.

  • If you invoke a method from a specialized notification type, wrap the method calls in an if statement to prevent your listener from invoking the method on notification objects of all types.

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.

    See NotificationFilterSupport (http://download.oracle.com/javase/6/docs/api/javax/management/NotificationFilterSupport.html) or AttributeChangeNotificationFilter (http://download.oracle.com/javase/6/docs/api/javax/management/AttributeChangeNotificationFilter.html) in the Java SE 6 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 Java SE 6 API Specification at http://download.oracle.com/javase/6/docs/api/javax/management/NotificationFilter.html.) 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.

    See Make Remote Connections to an MBean Server.

  2. 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 Make Remote Connections to an MBean Server.

    To register with a custom MBean, create an ObjectName that contains the MBean's JMX object name. See javax.management.ObjectName in the Java SE 6 API Specification at http://download.oracle.com/javase/6/docs/api/javax/management/ObjectName.html.

  3. Instantiate the listener class that you created.

  4. (Optional) Instantiate and configure one of the JDK's filter classes or instantiate a custom class.

  5. 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 Example 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 Resources Using Roles and Policies for Oracle WebLogic Server.

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.

Example 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 for Oracle WebLogic Server.

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 for Oracle WebLogic Server.

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 Java SE 6 API Specification (http://download.oracle.com/javase/6/docs/api/javax/management/MBeanServerDelegateMBean.html)

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

  • To provide information about which type of WebLogic Server MBean has been registered, the listener looks at the object name of the registered MBean. All WebLogic Server MBean object names contain a key property whose name is "Type" and whose value indicates the type of MBean. For example, instances of ServerRuntimeMBean contain the Type=ServerRuntime key property in their object names.

  • All JMX notifications contain a Type attribute, whose value offers a way to categorize and filter notifications. The Type attribute in MBeanServerNotification contains only one of two possible strings: "JMX.mbean.registered" or "JMX.mbean.unregistered". JMX notifications also contain a getType method that returns the value of the Type attribute.

    The listener in Example 7-3 invokes different lines of code depending on the value of the Type attribute.

  • If a JDBCDataSourceRuntimeMBean has been registered, the listener passes the MBeans' object name to a custom method. The custom method registers a listener and configures a filter for the JDBCDataSourceRuntimeMBean; this MBean listener emits messages when the MBean's Enabled attribute changes.

    The implementation of the custom method is located in the registration class (not the filter class) so that the method can reuse registration class's connection to the MBean server. Such reuse is an efficient use of resources and eliminates the need to store credentials and URLs in multiple classes.

Example 7-3 Example: Listening for MBeans Being Registered and Unregistered

import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.MBeanServerNotification;
import javax.management.ObjectName;

public class DelegateListener implements NotificationListener {
   public void handleNotification(Notification notification, Object obj) {
      if (notification instanceof MBeanServerNotification) {
         MBeanServerNotification msnotification = 
         (MBeanServerNotification) notification;

         // Get the value of the MBeanServerNotification
         // Type attribute, which contains either
         // "JMX.mbean.registered" or "JMX.mbean.unregistered"
         String nType = msnotification.getType();

         // Get the object name of the MBean that was registered or
         // unregistered
         ObjectName mbn = msnotification.getMBeanName();

         // Object names for WebLogic Server MBeans always contain
         // a "Type" key property, which indicates the
         // MBean's type (such as ServerRuntime or Log)
         String key = mbn.getKeyProperty("Type");

        if (nType.equals("JMX.mbean.registered")) {
            System.out.println("A " + key + " has been created.");

            System.out.println("Full MBean name: " + mbn);
            System.out.println("Time: " + msnotification.getTimeStamp());
               if (key.equals("JDBCDataSourceRuntime")) {
               // Registers a listener with a ServerRuntimeMBean.
               // By defining the "registerwithServerRuntime" method
               // in the "ListenToDelegate" class, you can reuse the
               // connection that "ListenToDelegate" established;
               // in addition to being an efficient way to use resources,
               // it eliminates the need to store credentials and URLs in
               // multiple classes.
               ListenToDelegate.registerwithJDBCDataSourceRuntime(mbn);
            }
         }
         if (nType.equals("JMX.mbean.unregistered")) {
            System.out.println("An MBean has been unregistered");
            System.out.println("Server name: " +
               mbn.getKeyProperty("Name"));
            System.out.println("Time: " + msnotification.getTimeStamp());
            System.out.println("Full MBean name: "
               + msnotification.getMBeanName());
         }
      }
   }
}

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

  • The JMX object name for MBeanServerDelegate is always "JMImplementation:type=MBeanServerDelegate".

  • The main method configures an instance of javax.management.NotificationFilterSupport to forward notifications only if value of the notification's Type attribute starts with "JMX.mbean.registered" or "JMX.mbean.unregistered".

  • The registerwithJDBCDataSourceRuntime method registers the listener in Example 7-1 with the specified JDBCDataSourceRuntimeMBean instance. The method also configures a javax.management.AttributeChangeNotificationFilter, which forwards only AttributeChangeNotifications that describe changes to an attribute named Enabled.

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

Example 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. See 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:

  • StringMonitorMBean observes attributes whose value is a String.

    Use this monitor to periodically observe attributes such as ServerLifeCycleRuntimeMBean State.

    See javax.management.monitor.StringMonitor in the Java SE 6 API Specification at http://download.oracle.com/javase/6/docs/api/javax/management/monitor/StringMonitor.html, which implements StringMonitorMBean.

  • GaugeMonitorMBean observes attributes whose value is a Number.

    Use this monitor to observe an attribute whose value fluctuates as a result of normal operations. Configure the gauge monitor to emit a notification if the value of the attribute fluctuates outside a specific range. For example, you can use it to monitor the ThreadPoolRuntimeMBean StandbyThreadCount attribute to verify that the number of unused but available threads in a server falls within an acceptable range.

    See javax.management.monitor.GaugeMonitor in the Java SE 6 API Specification (see http://download.oracle.com/javase/6/docs/api/javax/management/monitor/GaugeMonitor.html), which implements GaugeMonitorMBean.

  • CounterMonitorMBean observes attributes whose value is a Number.

    Use this monitor to observe an attribute whose value only increases as a result of normal operation. Configure the counter monitor to emit a notification if the value of the attribute crosses an upper threshold. You can also configure the counter monitor to increase the threshold and then reset the threshold at a specified point.

    For example, to track the overall number of hits on a server and to be notified each time 100 additional hits have accumulated, use a counter monitor that observes the ServerRuntimeMBean SocketsOpenedTotalCount attribute.

    See javax.management.monitor.CounterMonitor in the Java SE 6 API Specification (see http://download.oracle.com/javase/6/docs/api/javax/management/monitor/CounterMonitor.html), which implements CounterMonitorMBean.

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:

  • jmx.monitor.error.mbean, which indicates that the observed MBean is not registered in the MBean Server. The observed object name is provided in the notification.

  • jmx.monitor.error.attribute, which indicates that the observed attribute does not exist in the observed object. The observed object name and observed attribute name are provided in the notification.

  • jmx.monitor.error.type, which indicates that the object instance of the observed attribute value is null or not of the appropriate type for the given monitor. The observed object name and observed attribute name are provided in the notification.

  • jmx.monitor.error.runtime, which contains exceptions that are thrown while trying to get the value of the observed attribute (for reasons other than the cases described above).

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

  • For a counter monitor, when the threshold, the offset, or the modulus is not of the same type as the observed counter attribute.

  • For a gauge monitor, when the low threshold or high threshold is not of the same type as the observed gauge attribute.

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:

  • You listen for notifications of type MonitorNotification.

  • Optionally, you can import the javax.management.monitor.MonitorNotification class and invoke its methods to retrieve additional information about the event that generated the notification.

See Example 7-5.

Example 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.

    See Make Remote Connections to an MBean Server.

  2. Create an ObjectName for your monitor MBean instance.

    See javax.management.ObjectName in the Java SE 6 API Specification at http://download.oracle.com/javase/6/docs/api/javax/management/ObjectName.html.

    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

  3. Create and register one of the monitor MBeans.

    Use javax.management.MBeanServerConnection.createMBean(String classname ObjectName name) method, where:

    • classname represents one of the following values:

      • javax.management.monitor.CounterMonitor

      • javax.management.monitor.GaugeMonitor

      • javax.management.monitor.StringMonitor

    • name represents the object name that you created for the monitor MBean instance.

  4. Configure the monitor MBean by setting the value of its attributes.

    For guidelines on which attributes to set, see the javax.management.monitoring package in the Java SE 6 API Specification at http://download.oracle.com/javase/6/docs/api/javax/management/monitor/package-summary.html.

  5. 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.

  6. Instantiate the listener object that you created in Creating a Notification Listener for a Monitor MBean.

  7. Optionally instantiate and configure a filter.

  8. Register the listener and optional filter with the monitor MBean. Do not register the listener with the observed MBean.

    Invoke the monitor MBean's addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) method.

  9. Start the monitor by invoking the monitor MBean's start() operation.

Example: Registering a CounterMonitorMBean and Its Listener

Example 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 Oracle 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:

  • Only one instance of CounterMonitorMBean monitors all instances of ServerRuntimeMBean. The Domain Runtime MBean Server gives the CounterMonitorMBean federated access to instances of ServerRuntimeMBean that are running in a different JVM.

  • Only one instance of your listener class and the filter class listens and filters notifications from the CounterMonitorMBean.

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

Example 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();
   }
}