Accessing Runtime Information

WebLogic Server includes a large number of MBeans that provide information about the runtime state of managed resources. If you want to create applications that view and modify this runtime data, first use the MBeanServer interface or the WebLogic Server type-safe interface to retrieve Runtime MBeans. Then you use APIs in the weblogic.management.runtime package to view or change the runtime data. For information about viewing the API documentation, refer to Documentation for Runtime MBean APIs.

The following sections provide examples for retrieving and modifying runtime information about WebLogic Server domains and server instances:

 


Example: Determining the Active Domain and Servers

The MBeanHome interface includes APIs that you can use to determine the name of the currently active domain and the name of a server instance. You can use this information in other APIs that take the domain name or a server name as arguments.

The example class in Listing 5-1 does the following:

  1. Retrieves the Administration MBeanHome interface.

    While this example uses the Administration MBeanHome, you can also use a Local MBeanHome interface. A Local MBeanHome interface can retrieve only the name of the current domain and server instance. The Administration MBeanHome interface can retrieve the names of all currently active servers in the domain.

  2. Uses MBeanHome.getActiveDomain().getName() to retrieve the name of the domain.
  3. Uses the getMBeansByType method to retrieve the set of all ServerRuntime MBeans in the domain.
  4. Iterates through the set and compares the names of the ServerRuntimeMBean instances with the name of the WebLogic Server instance.
  5. Invokes the serverRuntime.getState method to retrieve the state of each server instance.
  6. Compares the value that the getState method returns with a field name from the weblogic.management.runtime.ServerStates class. This class contains one field for each state within a server's life cycle. For more information about weblogic.management.runtime.ServerStates, refer to the WebLogic Server Javadoc.
  7. If the instance is active, it prints the name of the server.

In the following example, weblogic is the username and password for a user who has permission to view and modify MBean attributes. For information about permissions to modify MBeans, refer to "Security Roles in the Securing WebLogic Resources guide.

Listing 5-1 Determining the Active Domain and Servers

import java.util.Set;



import java.util.Iterator;
import javax.naming.Context;
import weblogic.jndi.Environment;



import weblogic.management.MBeanHome;
import weblogic.management.runtime.ServerRuntimeMBean;
import weblogic.management.runtime.ServerStates;
public class getActiveDomainAndServers {



    public static void main(String[] args) {
        MBeanHome home = null;
        //url of the Administration Server



        String url = "t3://localhost:7001";
        String username = "weblogic";
        String password = "weblogic";
        //setting the initial context



        try {
            Environment env = new Environment();
            env.setProviderUrl(url);
            env.setSecurityPrincipal(username);
            env.setSecurityCredentials(password);
            Context ctx = env.getInitialContext();
            //getting the Administration MBeanHome



            home = (MBeanHome) ctx.lookup(MBeanHome.ADMIN_JNDI_NAME);
        } catch (Exception e) {
            System.out.println("Exception caught: " + e);
        }
        //getting the name of the active domain



        try {
            System.out.println("Active Domain: " +
                    home.getActiveDomain().getName() );
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }
        //getting the names of servers in the domain



        System.out.println("Active Servers: ");
        Set mbeanSet = home.getMBeansByType("ServerRuntime");
        Iterator mbeanIterator = mbeanSet.iterator();
        while(mbeanIterator.hasNext()) {
            ServerRuntimeMBean serverRuntime =
                (ServerRuntimeMBean)mbeanIterator.next();
            //printing the names of active servers
            if(serverRuntime.getState().equals(ServerStates.RUNNING)){
                System.out.println("Name: " + serverRuntime.getName());
                System.out.println("ListenAddress: " +
                         serverRuntime.getListenAddress());
                 System.out.println("ListenPort: " +
                         serverRuntime.getListenPort());
                 //count++;
            }
        }
        System.out.println("Number of servers active in the domain: " +



                            mbeanSet.size());
     }
}

 

Using weblogic.Admin to Determine Active Domains and Servers

While you can compile and run the example code in Listing 5-1 to determine active domains and servers, you can use the weblogic.Admin utility to accomplish a similar task without having to compile Java classes.

The following command returns the name of the currently active domain, where AdminServer is the domain's Administration Server, MyHost is the Administration Server's host computer, and weblogic is the name and password of a user who has permission to view MBean attributes:

java weblogic.Admin -url MyHost:8001 -username weblogic -password weblogic GET -type DomainRuntime -property Name

The command output includes the WebLogicObjectName of the DomainRuntimeMBean and the value of its Name attribute:

{MBeanName="myDomain:Location=AdminServer,Name=myDomain,ServerRuntime=Admi
nServer,Type=DomainRuntime"{Name=myDomain}}

To see a list of all server instances that are currently active, you use ask the Administration Server to retrieve all ServerRuntime MBeans that are registered in its Administration MBeanHome interface. (Only active server instances register ServerRuntime MBeans with the Administration MBeanHome interface.)

You must specify the -adminurl argument to instruct the GET command to use the Administration Server's Administration MBeanHome interface:

java weblogic.Admin -adminurl MyHost:8001 -username weblogic -password
weblogic GET -type ServerRuntime -property State

The command output includes the WebLogicObjectName of all ServerRuntime MBeans and the value of each State attribute:

---------------------------



MBeanName: "myDomain:Location=MedRecMS2,Name=MedRecMS2,Type=ServerRuntime" State: RUNNING
---------------------------



MBeanName: "myDomain:Location=AdminServer,Name=AdminServer,Type=ServerRuntime" State: RUNNING
---------------------------



MBeanName: "myDomain:Location=MedRecMS1,Name=MedRecMS1,Type=ServerRuntime" State: RUNNING

 


Example: Viewing and Changing the Runtime State of a WebLogic Server Instance

The weblogic.management.runtime.ServerRuntimeMBean interface provides runtime information about a WebLogic Server instance. For example, it indicates which listen ports and addresses a server is using. It also includes operations that can gracefully or forcefully shut down a server.

This section provides examples of finding ServerRuntimeMBean and using it to gracefully shut down a server instance. For more information about graceful shutdowns and controlling the graceful shutdown period, refer to "Graceful Shutdown in Configuring and Managing WebLogic Server.

Each example illustrates a different way of retrieving ServerRuntimeMBean:

You cannot use the weblogic.Admin utility to change the value of Runtime MBean attributes.

 

Using a Local MBeanHome and getRuntimeMBean()

Each WebLogic Server instance hosts its own MBeanHome interface, which provides access to the Local Configuration and Runtime MBeans on the server instance. As opposed to using the Administration MBeanHome interface, using the local MBeanHome saves you the trouble of filtering MBeans to find those that apply to the current server. It also uses fewer network hops to access MBeans, because you are connecting directly to the server (instead of routing requests through the Administration Server).

The MBeanHome interface includes the getRuntimeMBean() method, which returns only Runtime MBeans that reside on the current WebLogic Server. If you invoke MBeanHome.getRuntimeMBean()on the Administration Server, it returns only the Runtime MBeans that manage and monitor the Administration Server.

The example class in Listing 5-2 does the following:

  1. Configures a javax.naming.Context object with information for connecting to a server instance that listens for requests at t3://ServerHost:7001.
  2. Uses the Context.lookup method to retrieve the local MBeanHome interface for the server instance.

    The MBeanHome.LOCAL_JNDI_NAME field returns the JNDI name of the current server's local MBeanHome.

  3. Uses the MBeanHome.getRuntimeMBean(String name,String type)method to retrieve the ServerRuntimeMBean for the current server instance.
  4. Invokes ServerRuntimeMBean methods to retrieve and modify the server state.

In the following example, weblogic is the username and password for a user who has permission to view and modify MBean attributes and Server1 is the name of the WebLogic Server instance for which you want to view and change status. For information about permissions to modify MBeans, refer to "Security Roles in the Securing WebLogic Resources guide.

Listing 5-2 Using a Local MBeanHome and getRuntimeMBean()

import javax.naming.Context;
import weblogic.jndi.Environment;



import weblogic.management.MBeanHome;
import weblogic.management.runtime.ServerRuntimeMBean;
public class serverRuntime1 {
    public static void main(String[] args) {



        MBeanHome home = null;
        //domain variables



        String url = "t3://ServerHost:7001";
        String serverName = "Server1";
        String username = "weblogic";
        String password = "weblogic";
        ServerRuntimeMBean serverRuntime = null;
        //setting the initial context



        try {
            Environment env = new Environment();
            env.setProviderUrl(url);
            env.setSecurityPrincipal(username);
            env.setSecurityCredentials(password);
            Context ctx = env.getInitialContext();
           //getting the local MBeanHome



            home = (MBeanHome) ctx.lookup(MBeanHome.LOCAL_JNDI_NAME);
            System.out.println("Got the MBeanHome: " + home + " for server: " +
                                                                  serverName);
        } catch (Exception e) {
            System.out.println("Caught exception: " + e);
        }
        // Here we use the getRuntimeMBean method to access the



       //ServerRuntimeMbean of the server instance.
        try { 



            serverRuntime =
                           (ServerRuntimeMBean)home.getRuntimeMBean
                           (serverName,"ServerRuntime");
            System.out.println("Got serverRuntimeMBean: " + serverRuntime);
            //Using ServerRuntimeMBean to retrieve and change state.



            System.out.println("Current state: " + serverRuntime.getState() );
            serverRuntime.shutdown();
            System.out.println("Current state: " + serverRuntime.getState() );
        } catch (javax.management.InstanceNotFoundException e) {
            System.out.println("Caught exception: " + e);
        }
    }
}

 

Using the Administration MBeanHome and getMBeansByType()

Like the example in Listing 5-1, the example class in this section uses the Administration MBeanHome interface to retrieve a ServerRuntime MBean. The Administration MBeanHome provides a single access point for all MBeans in the domain, but it requires you to either construct the WebLogicObjectName of the MBean you want to retrieve or to filter MBeans to find those that apply to a specific current server.

The example class in Listing 5-3 does the following:

  1. Retrieves the Administration MBeanHome interface.
  2. Uses the MBeanHome.getMBeansByType method to retrieve the set of all ServerRuntime MBeans in the domain.
  3. Assigns the list of MBeans to a Set object and uses methods of the Set and Iterator interfaces to iterate through the list.
  4. Uses the ServerRuntimeMBean.getName method to retrieve the Name component of the MBean's WebLogicObjectName. It then compares the Name value with another value.
  5. When it finds the ServerRuntimeMBean for a specific server instance, it uses the ServerRuntimeMBean.getState method to return the current server state.
  6. Then it invokes the ServerRuntimeMBean.shutdown() method, which initiates a graceful shutdown.

In the following example, weblogic is the username and password for a user who has permission to change the state of servers, and Server1 is the name of the WebLogic Server instance for which you want to view and change status. For information about permissions to modify MBeans, refer to "Security Roles in the Securing WebLogic Resources guide.

Listing 5-3 Using the Administration MBeanHome and getMBeansByType()

import java.util.Set;



import java.util.Iterator;
import javax.naming.Context;
import weblogic.jndi.Environment;



import weblogic.management.MBeanHome;
import weblogic.management.runtime.ServerRuntimeMBean;
public class serverRuntimeInfo {



    public static void main(String[] args) {
        MBeanHome home = null;
        //domain variables



        String url = "t3://localhost:7001";
        String serverName = "Server1";
        String username = "weblogic";
        String password = "weblogic";
        ServerRuntimeMBean serverRuntime = null;
        Set mbeanSet = null;
        Iterator mbeanIterator = null;
        //Setting the initial context



        try {
            Environment env = new Environment();
            env.setProviderUrl(url);
            env.setSecurityPrincipal(username);
            env.setSecurityCredentials(password);
            Context ctx = env.getInitialContext();
            // Getting the Administration MBeanHome.



            home = (MBeanHome) ctx.lookup(MBeanHome.ADMIN_JNDI_NAME);
            System.out.println("Got the Admin MBeanHome: " + home );
        } catch (Exception e) {
            System.out.println("Exception caught: " + e);
        }
        // Using the getMBeansByType method to get the set of



        //ServerRuntime mbeans.
        try {
            mbeanSet = home.getMBeansByType("ServerRuntime");
            mbeanIterator = mbeanSet.iterator();
            // Comparing the name of the server in each ServerRutime
            // MBean to the value specified by serverName
            while(mbeanIterator.hasNext()) {
                serverRuntime = (ServerRuntimeMBean)mbeanIterator.next();
                if(serverRuntime.getName().equals(serverName)) {
                    System.out.println("Found the serverRuntimembean: " +
                                      serverRuntime + " for: " + serverName);
                    System.out.println("Current state: " +
                                                  serverRuntime.getState() );
                    System.out.println("Stopping the server ...");
                    serverRuntime.shutdown();
                    System.out.println("Current state: " +
                                       serverRuntime.getState() );
                }
            }
        } catch (Exception e) {
            System.out.println("Caught exception: " + e);
        }
    }
}

 

Using the Administration MBeanHome and getMBean()

Instead of retrieving a list of all MBeans and then filtering the list to find the ServerRuntimeMBean for a specific server, this example uses the MBean naming conventions to construct the WebLogicObjectName for the ServerRuntimeMBean on a server instance named Server1. For information about constructing a WebLogicObjectName, refer to Table 3-1.

To make sure that you supply the correct object name, use the weblogic.Admin GET command. For example, the following command returns the object name and list of attributes of the ServerRuntimeMBean for a server instance that runs on a host computer named MyHost:

java weblogic.Admin -url http://MyHost:7001 -username weblogic
-password weblogic GET -pretty -type ServerRuntime

For more information about using the weblogic.Admin utility to find information about MBeans, refer to "Commands for Managing WebLogic Server MBeans in the WebLogic Server Command Line Reference.

In Listing 5-4, weblogic is the username and password for a user who has permission to view and modify MBean attributes, Server1 is the name of the WebLogic Server instance for which you want to view and change status, and mihirDomain is the name of the WebLogic Server administration domain. For information about permissions to modify MBeans, refer to "Security Roles in the Securing WebLogic Resources guide.

Listing 5-4 Using the Administration MBeanHome and getMBean()

import java.util.Set;



import java.util.Iterator;
import javax.naming.Context;
import weblogic.jndi.Environment;



import weblogic.management.MBeanHome;
import weblogic.management.runtime.ServerRuntimeMBean;
import weblogic.management.WebLogicObjectName;
public class serverRuntimeInfo2 {



    public static void main(String[] args) {
        MBeanHome home = null;
        //domain variables
        String url = "t3://localhost:7001";
        String serverName = "Server1";
        String username = "weblogic";
        String password = "weblogic";
        String domain = "medrec";
        ServerRuntimeMBean serverRuntime = null;
        //setting the initial context



        try {
            Environment env = new Environment();
            env.setProviderUrl(url);
            env.setSecurityPrincipal(username);
            env.setSecurityCredentials(password);
            Context ctx = env.getInitialContext();
            home = (MBeanHome) ctx.lookup(MBeanHome.ADMIN_JNDI_NAME);



            System.out.println("Got Admin MBeanHome from the Admin server: "
                               + home);
        } catch (Exception e) {
            System.out.println("Exception caught: " + e);
        }
        try {



            WebLogicObjectName objName = new WebLogicObjectName(serverName,
                           "ServerRuntime",home.getDomainName(),serverName);
           System.out.println("Created WebLogicObjectName: " + objName);
            serverRuntime = (ServerRuntimeMBean)home.getMBean(objName);
            System.out.println("Got the serverRuntime using the adminHome: " +
                                serverRuntime );
            System.out.println("Current state: " + serverRuntime.getState() );
            System.out.println("Stopping the server ...");
            //changing the state to SHUTDOWN



            serverRuntime.shutdown();
            System.out.println("Current state: " + serverRuntime.getState() );
        } catch(Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}

 

Using the MBeanServer Interface

The example in this section uses a standard JMX approach for interacting with MBeans. It uses the Administration MBeanHome interface to retrieve the javax.management.MBeanServer interface and then uses MBeanServer to retrieve the value of the ListenPort attribute of the ServerRuntimeMBean for a server instance named Server1.

In the following example, weblogic is the username and password for a user who has permission to view and modify MBean attributes and mihirDomain is the name of the WebLogic Server administration domain. For information about permissions to modify MBeans, refer to "Security Roles in the Securing WebLogic Resources guide.

Listing 5-5 Using the Administration MBeanHome and getMBean()

import java.util.Set;



import java.util.Iterator;
import javax.naming.Context;
import javax.management.MBeanServer;
import weblogic.jndi.Environment;



import weblogic.management.MBeanHome;
import weblogic.management.WebLogicObjectName;
public class serverRuntimeInfo2 {



    public static void main(String[] args) {
        MBeanHome home = null;
        //domain variables



        String url = "t3://localhost:7001";
        String serverName = "MedRecServer";
        String username = "weblogic";
        String password = "weblogic";
        Object attributeValue = null;
        MBeanServer homeServer = null;
        //setting the initial context



        try {
            Environment env = new Environment();
            env.setProviderUrl(url);
            env.setSecurityPrincipal(username);
            env.setSecurityCredentials(password);
            Context ctx = env.getInitialContext();
            // Getting the Administration MBeanHome.



            home = (MBeanHome) ctx.lookup(MBeanHome.ADMIN_JNDI_NAME);
            System.out.println("Got Admin MBeanHome from the Admin server: " +
                                                                      home);
        } catch (Exception e) {
            System.out.println("Exception caught: " + e);
        }
        try {
            // Creating the mbean object name.
            WebLogicObjectName objName = new WebLogicObjectName(serverName,
                           "ServerRuntime",home.getDomainName(),serverName);
            System.out.println("Created WebLogicObjectName: " + objName);
            //Retrieving the MBeanServer interface



            homeServer = home.getMBeanServer();
            //Retrieving the ListenPort attribute of ServerRuntimeMBean



            attributeValue = homeServer.getAttribute(objName, "ListenPort");
            System.out.println("ListenPort for " + serverName + " is:" +
                                                            attributeValue);
        } catch(Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}

 


Example: Viewing Runtime Information About Clusters

The example in this section retrieves the number and names of WebLogic Server instances currently running in a cluster. It uses weblogic.management.runtime.ClusterRuntimeMBean, which provides information about a single Managed Server's view of the members of a WebLogic cluster.

Only Managed Servers host instances of ClusterRuntimeMBean, and retrieve the ClusterRuntimeMBean instance from a Managed Server that is actively participating in a cluster.

To make sure that it retrieves a ClusterRuntimeMBean from an active Managed Server that is in a cluster, this example does the following:

  1. Retrieves the Administration MBeanHome, which runs on the Administration Server and can provide access to all ClusterRuntimeMBeans in the domain.
  2. Retrieves all ClusterRuntimeMBeans and determines whether they belong to a specific cluster.
  3. Finds one ClusterRuntimeMBean for a Managed Server in the cluster of interest.
  4. Uses the ClusterRuntimeMBean APIs on the Managed Server to determine the number and name of active servers in the cluster.

In the example, weblogic is the username and password for a user who has permission to view and modify MBean attributes. For information about permissions to modify MBeans, refer to "Security Roles in the Securing WebLogic Resources guide.

Listing 5-6 Retrieving a List of Servers Running in a Cluster

import java.util.Set;



import java.util.Iterator;
import java.rmi.RemoteException;
import javax.naming.Context;
import weblogic.jndi.Environment;
import weblogic.management.MBeanHome;
import javax.management.ObjectName;
import weblogic.management.WebLogicMBean;
import weblogic.management.runtime.ClusterRuntimeMBean;
import weblogic.management.WebLogicObjectName;
import weblogic.management.MBeanHome;
public class getRunningServersInCluster {



    public static void main(String[] args) {
        MBeanHome home = null;
        //domain variables



        String url = "t3://localhost:7001"; //url of the Administration Server
        /* If you have more than one cluster in your domain, define a list of
         * all the servers in the cluster. You compare the servers in the domain
         * with this list to determine which servers are in a specific cluster.
         */
        String server1 = "cs1"; // name of server in the cluster
        String server2 = "cs2"; // name of server in the cluster
        String username = "weblogic";
        String password = "weblogic";
        ClusterRuntimeMBean clusterRuntime = null;
        Set mbeanSet = null;
        Iterator mbeanIterator = null;
        String name = "";
        String[] aliveServerArray = null;
        //Setting the initial context



        try {
            Environment env = new Environment();
            env.setProviderUrl(url);
            env.setSecurityPrincipal(username);
            env.setSecurityCredentials(password);
            Context ctx = env.getInitialContext();
            // Getting the Administration MBeanHome. 



            home = (MBeanHome) ctx.lookup(MBeanHome.ADMIN_JNDI_NAME);
            // Retrieving a list of ClusterRuntime MBeans in the domain.



            mbeanSet = home.getMBeansByType("ClusterRuntime");
            mbeanIterator = mbeanSet.iterator();
            while(mbeanIterator.hasNext()) {
                // Retrieving one ClusterRuntime MBean from the list.



                clusterRuntime = (ClusterRuntimeMBean)mbeanIterator.next();
                // Getting the name of the ClusterRuntime MBean.
                name = clusterRuntime.getName();
                // Determining if the current ClusterRuntimeMBean belongs to a
                // server in the cluster of interest.
                if(name.equals(server1) || name.equals(server2) ) {
                    // Using the current ClusterRuntimeMBean to retrieve the
                    // number of servers in the cluster.
                    System.out.println("\nNumber of active servers in the
                         cluster: " + clusterRuntime.getAliveServerCount());
                    // Retrieving the names of servers in the cluster.
                    aliveServerArray = clusterRuntime.getServerNames();
                    break;
                }
            }
        } catch (Exception e) {
             System.out.println("Caught exception: " + e);
        }
        if(aliveServerArray == null) {
            System.out.println("\nThere are no running servers in the cluster");
            System.exit(1);
        }
        System.out.println("\nThe running servers in the cluster are: ");



        for (int i=0; i < aliveServerArray.length; i++) {
            System.out.println("server " + i + " : " + aliveServerArray[i]);
        }
    }
}

 


Viewing Runtime Information for EJBs

For each EJB that you deploy on a server instance, WebLogic Server instantiates MBean types from the weblogic.management.runtime package (see Table 5-1). For more information about the MBeans in the weblogic.management.runtime package, refer to the WebLogic Server Javadoc.

MBean Type

Description

EJBComponentRuntimeMBean The top level interface for all runtime information collected for an EJB module.
StatefulEJBRuntimeMBean Instantiated for stateful session beans only.Contains methods for accessing EJB runtime information collected for a Stateful Session Bean.
StatelessEJBRuntimeMBean Instantiated for stateless session beans only.Contains methods for accessing EJB runtime information collected for a Stateless Session Bean.
MessageDrivenEJBRuntimeMBean Instantiated for message driven bean only.Contains methods for accessing EJB runtime information collected for a Message Driven Bean.
EntityEJBRuntimeMBean Contains methods for accessing EJB runtime information collected for an Entity Bean.
EJBCacheRuntimeMBean Contains methods for accessing cache runtime information collected for an EJB.
EJBLockingRuntimeMBean Contains methods for accessing lock manager runtime information collected for an EJB.
EJBTransactionRuntimeMBean Contains methods for accessing transaction runtime information collected for an EJB.
EJBPoolRuntimeMBean Instantiated for stateless session beans only.Contains methods for accessing free pool runtime information collected for a stateless session EJB. WebLogic Server uses a free pool to improve performance and throughput for stateless session EJBs. The free pool stores unbound stateless session EJBs. Unbound EJB instances are instances of a stateless session EJB class that are not processing a method call.

WebLogic Server provides an additional, abstract interface, EJBRuntimeMBean, which contains methods that the other EJB runtime MBeans use.

EJB runtime MBeans are instantiated within a hierarchy. For example:

  • Each EJB jar file exposes its runtime data through an instance of EJBComponentRuntimeMBean.
  • Each entity bean within the jar exposes its runtime data through an instance of EntityEJBRuntimeMBean.
  • Each EntityEJBRuntimeMBean is the parent of up to four additional MBeans.

    EntityEJBRuntimeMBean is always the parent of the EJBCacheRuntimeMBean, EJBTransactionRuntimeMBean, and EJBPoolRuntimeMBean MBeans. The fourth child MBean, EJBLockingRuntimeMBean, is only created if the entity bean uses an exclusive concurrency strategy (which is configured in the weblogic-ejb-jar.xml deployment descriptor).

Depending on the type of runtime data that you retrieve, you typically also need to retrieve the name of any parent MBeans to provide context for the data. For example, if you retrieve the value of EJBTransactionRuntimeMBean.TransactionsRolledBackTotalCount, you also retrieve the name of the parent EJBEntityRuntimeMBean to determine which entity bean the value comes from.

Figure 5-1 illustrates the hierarchical relationships.

Figure 5-1 Hierarchy of EJB Runtime MBeans


 

Example: Retrieving Runtime Information for All Stateful and Stateless EJBs

To retrieve runtime information for all EJBs deployed in a domain, the example in Listing 5-7 does the following:

  1. Connects to the Administration Server and retrieves the Administration MBeanHome interface.

    If you want to retrieve runtime information only for the EJBs that are deployed on a specific server instance, you can connect to the specific server instance and retrieve the local MBeanHome interface. For more information, refer to Example: Retrieving a Local MBeanHome from an Internal Client.

  2. To display the percentage of times a stateless bean instance wasn't available in the free pool when an attempt was made to obtain one, the example:
    1. Invokes the MBeanHome.getMBeansByType to retrieve all StatelessEJBRuntime MBeans.
    2. For each stateless EJB, it invokes the displayEJBInfo method (which is defined later in this class). This method:

    • Invokes the StatelessEJBRuntimeMBean.getEJBName method (which all EJB runtime MBeans inherit from EJBRuntimeMBean) to retrieve the name of the MBean.
    • Walks up the MBean hierarchy to retrieve the names of the parent EJB component and application.

      All EJBs are packaged within an EJB component, which functions as a J2EE module. EJB components can be packaged with an enterprise application.

    1. Invokes the StatelessEJBRuntime.getPoolRuntime method to retrieve the EJBPoolRuntimeMBean that is associated with the stateless EJB.
    2. Invokes the EJBPoolRuntimeMBean.getMissTotalCount method to retrieve the number of failed attempts.
  3. To determine percentage of transactions that have been rolled back for each stateful EJB in the domain, the example:
    1. Invokes the MBeanHome.getMBeansByType to retrieve all StatefulEJBRuntime MBeans.
    2. Invokes the displayEJBInfo method (which is defined later in this class).
    3. Invokes the EJBRuntime.getTransactionRuntime method to retrieve the EJBTransactionRuntimeMBean that is associated with the stateful EJB.
    4. Invokes the EJBTransactionRuntimeMBean.getTransactionsRolledBackTotalCount and getTransactionsCommittedTotalCount methods.
    5. Divides the number of committed transactions by the number rolled transactions to determine the percentage of rolled back transactions.

Listing 5-7 Viewing Runtime Information for EJBs

import java.util.Iterator;



import java.util.Set;
import javax.management.InstanceNotFoundException;



import javax.naming.Context;
import javax.naming.InitialContext;
import weblogic.management.MBeanHome;



import weblogic.management.WebLogicObjectName;
import weblogic.management.configuration.ApplicationMBean;
import weblogic.management.configuration.EJBComponentMBean;
import weblogic.management.configuration.ServerMBean;
import weblogic.management.runtime.EJBComponentRuntimeMBean;
import weblogic.management.runtime.EJBPoolRuntimeMBean;
import weblogic.management.runtime.EJBRuntimeMBean;
import weblogic.management.runtime.EJBTransactionRuntimeMBean;
import weblogic.management.runtime.StatelessEJBRuntimeMBean;
import weblogic.jndi.Environment;
public final class EJBMonitor {
    private String url = "t3://localhost:7001";



    private String user = "weblogic";
    private String password = "weblogic";
    private MBeanHome   mBeanHome; // admin
    public EJBMonitor() throws Exception {



        Environment env = new Environment();
        env.setProviderUrl(url);
        env.setSecurityPrincipal(user);
        env.setSecurityCredentials(password);
        Context ctx = env.getInitialContext();
        mBeanHome = (MBeanHome)ctx.lookup(MBeanHome.ADMIN_JNDI_NAME);



    }
    public void displayStatelessEJBPoolMissPercentages()



    throws Exception
    {
        String type = "StatelessEJBRuntime";
        Set beans = mBeanHome.getMBeansByType(type);
        System.out.println("Printing Stateless Session pool miss
                            percentages:");
        for(Iterator it=beans.iterator();it.hasNext();) {
            StatelessEJBRuntimeMBean rt = (StatelessEJBRuntimeMBean)it.next();
            displayEJBInfo(rt);
            EJBPoolRuntimeMBean pool = rt.getPoolRuntime();
            String missPercentage = "0";



            long missCount = pool.getMissTotalCount();
            if(missCount > 0) {
                missPercentage =
                          ""+(float)missCount/pool.getAccessTotalCount()*100;
            }
            System.out.println("Pool Miss Percentage: "+ missPercentage +"\n");
        }
    }
    public void displayStatefulEJBTransactionRollbackPercentages()



    throws Exception
    {
        String type = "StatefulEJBRuntime";
        Set beans = mBeanHome.getMBeansByType(type);
        System.out.println("Printing Stateful transaction rollback
                          percentages:");
        for(Iterator it=beans.iterator();it.hasNext();) {
            EJBRuntimeMBean rt = (EJBRuntimeMBean)it.next();
            displayEJBInfo(rt);
            EJBTransactionRuntimeMBean trans = rt.getTransactionRuntime();
             String rollbackPercentage = "0";



            long rollbackCount = trans.getTransactionsRolledBackTotalCount();
            if(rollbackCount > 0) {
                long totalTransactions = rollbackCount +
                        trans.getTransactionsCommittedTotalCount();
                rollbackPercentage =
                        ""+(float)rollbackCount/totalTransactions*100;
            }
            System.out.println("Transaction rollback percentage: "+
                        rollbackPercentage +"\n");
        }
    }
    private void displayEJBInfo(EJBRuntimeMBean rt) throws Exception {



        System.out.println("EJB Name: "+rt.getEJBName());
        EJBComponentRuntimeMBean compRTMBean =
                        (EJBComponentRuntimeMBean)rt.getParent();
        EJBComponentMBean compMBean = compRTMBean.getEJBComponent();
        ApplicationMBean appMBean = (ApplicationMBean)compMBean.getParent();
        System.out.println("Application Name: "+appMBean.getName());
        System.out.println("Component Name: "+compMBean.getName());
        WebLogicObjectName objName = rt.getObjectName();



        System.out.println("Server Name: "+objName.getLocation());
    }
    public static void main(String[] argv) throws Exception {



        EJBMonitor m = new EJBMonitor();
        m.displayStatelessEJBPoolMissPercentages();
        m.displayStatefulEJBTransactionRollbackPercentages();
    }
}

 


Viewing Runtime Information for Servlets

Instances of ServletRuntimeMBean provide access to information about how individual servlets are performing. For example, the ServletRuntime.InvocationTotalCount attribute indicates the number of times a servlet instance has been invoked.

Because the WebLogicObjectName for instances of ServletRuntimeMBean is dynamically generated each time a servlet type is instantiated, it is not feasible to register JMX listeners or monitors with each servlet. Instead, you can look up ServletRuntime MBeans and invoke ServletRuntime methods.

The general structure for ServletRuntime object names is as follows:
domain:Location=dynamic-name,ServerRuntime=server,Type=ServletRuntime

The dynamic-name value includes the name of the server on which the servlet is deployed, the name of the application that contains the servlet, the class name of the servlet, and a number that is assigned to the specific servlet instance.

For example:
medrec:Location=MedRecServer,Name=MedRecServer_MedRecServer_MainWAR_org.
apache.struts.action.ActionServlet_549,ServerRuntime=MedRecServer,
Type=ServletRuntime

ServletRuntime MBeans are instantiated with an MBean hierarchy (see Figure 5-2):

  • Each enterprise application exposes its runtime data through an instance of ApplicationRuntimeMBean.

    If you deploy J2EE modules (such as EJBs or Web applications) without declaring them as components of an enterprise application, WebLogic Server creates a runtime wrapper enterprise application and deploys each module within its own wrapper application. The wrapper application name is the same as the module that it contains. For example, if you deploy myApp.WAR, WebLogic Server wraps the web application in an enterprise application named myApp. You do not need to interact with this wrapper application; it is an artifact of the WebLogic Server deployment implementation.

  • Each Web application exposes its runtime data through an instance of WebAppComponentRuntimeMBean.
  • Each servlet instance exposes its runtime data through an instance of ServletRuntimeMBean.

    Figure 5-2 Hierarchy of Application, Web Application, and Servlet Runtime MBeans


Although you can retrieve instances of ServletRuntimeMBean without walking the MBean hierarchy, BEA recommends that you use the hierarchical organization to retrieve only servlets within a specific Web application. (Depending on the number of servlets on a server instance, retrieving all ServletRuntime MBeans on a server instance can lead to poor performance.) After you retrieve servlets within a Web application, you can iterate through the list to retrieve monitoring data.

 

Example: Retrieving Runtime Information for Servlets

To retrieve the value of the ServletRuntime.InvocationTotalCount attribute for all instances of the action servlet within the sample Patient Web application (which is a component of the MedRec application), the sample class in Listing 5-8:

  1. Connects to the Administration Server and retrieves the Administration MBeanHome interface.

    The Administration MBeanHome interface provides access to all Web applications (and therefore all of their servlet instances) that are deployed in the domain.

    If you want to retrieve runtime information only for the servlet instances on a specific server instance, you can connect to the specific server instance and retrieve the local MBeanHome interface. For more information, refer to Example: Retrieving a Local MBeanHome from an Internal Client.

  2. To retrieve the ApplicationRuntimeMBean for the MedRec application, the class:
    1. Invokes MBeanHome.getMBeansByType to retrieve all ApplicationRuntime MBeans in the domain.
    2. For each ApplicationRuntimeMBean, it invokes ApplicationRuntimeMBean.getApplicationName and compares the returned value to the value of the appName variable.
    3. When it finds the ApplicationRuntimeMBean for the MedRec application, it returns the MBean.

      Note: Depending on the number of Web applications in your domain, this step might not be necessary. If your domain contains only a few Web applications, you can simply retrieve all WebAppComponentRuntime MBeans and iterate through this list to find a specific Web application.

  3. To retrieve the WebAppComponentRuntimeMBean for the Patient Web application, the class:
    1. Invokes ApplicationRuntimeMBean.lookupComponents to retrieve all application components.
    2. Iterates through the list to retrieve only the Web application components (which are represented by WebAppComponentRuntime MBeans.
    3. For each WebAppComponentRuntimeMBean, it invokes WebAppComponentMBean.getContextRoot and compares the returned value with the value of the ctxRoot variable.

      The context root is a convenient, unique identifier for a Web application. If you deploy a Web application as part of an enterprise application, you specify the context root in the application's application.xml deployment descriptor. If you deploy a Web application as a standalone module, you define the context root in the Web application's weblogic.xml deployment descriptor.

      For the Patient Web application, its context root is defined with the following XML elements from WL_HOME\samples\server\medrec\src\medrecEar\
      META-INF\application.xml:

      <module>
        <web>
           <web-uri>patientWebApp</web-uri>
            <context-root>/patient</context-root>
        </web>
      </module>

    4. When it finds the WebAppComponentRuntimeMBean for the Patient Web application, it returns the MBean.
  4. To find all instances of the action servlet within the Patient Web application, the code:
    1. Invokes WebAppComponentMBean.getServlets to retrieve all instances of ServletRuntimeMBean.
    2. For each ServletRuntimeMBean, it invokes ServletRuntimeMBean.getServletName and compares the returned value to the value of the servletName variable.
    3. When it finds a ServletRuntimeMBean that represents an instance of the action servlet, it returns the MBean.
  5. To return the invocation count for each instance of the action servlet, the code invokes ServletRuntimeMBean.getInvocationTotalCount and prints the returned value to standard out.

Listing 5-8 Retrieving Invocation Count from Servlets in a Web Application

import java.util.Set;



import java.util.Iterator;
import java.util.regex.Pattern;
import javax.naming.Context;
import weblogic.jndi.Environment;



import weblogic.management.MBeanHome;
import weblogic.management.runtime.ServletRuntimeMBean;
import weblogic.management.runtime.ApplicationRuntimeMBean;
import weblogic.management.runtime.WebAppComponentRuntimeMBean;
import weblogic.management.runtime.ComponentRuntimeMBean;
public class ServletRuntime {



   public static void main(String[] args) {
      //url of the Administration Server
      String url = "t3://localhost:7001";
      String username = "weblogic";
      String password = "weblogic";
      String appName = "MedRecEAR";
      String ctxRoot = "/patient";
      String servletName = "action";
      try {



         MBeanHome home = getMBeanHome(url, username, password);
         ApplicationRuntimeMBean app = getApplicationRuntimeMBean
             (home, appName);
         WebAppComponentRuntimeMBean webapp =
             getWebAppComponentRuntimeMBean(app,ctxRoot);
         ServletRuntimeMBean servlet = getServletRuntimeMBean
             (webapp,servletName);
         System.out.println("Invocation count is " +
             servlet.getInvocationTotalCount());
      } catch (Exception e) {
         System.out.println("Exception caught: " + e);
      }
   }
   /**



   * Get an initial context and lookup the Admin MBean Home
   */
   private static MBeanHome getMBeanHome(String url,
      String username, String password) throws Exception
   {
      Environment env = new Environment();
      env.setProviderUrl(url);
      env.setSecurityPrincipal(username);
      env.setSecurityCredentials(password);
      Context ctx = env.getInitialContext();
      // Retrieve the Administration MBeanHome



      return (MBeanHome) ctx.lookup(MBeanHome.ADMIN_JNDI_NAME);
   }
   /**



   * Find the RuntimeMBean for an application
   */
   private static ApplicationRuntimeMBean
      getApplicationRuntimeMBean(MBeanHome home, String appName)
      throws Exception
   {
      //
      // Get the Set of RuntimeMBeans for all applications.
      //
      Set appMBeans = home.getMBeansByType("ApplicationRuntime");
      Iterator appIterator = appMBeans.iterator();
      //
      // Iterate over the Set and find the app you are interested in
      //
      while (appIterator.hasNext()) {
         ApplicationRuntimeMBean appRuntime = (ApplicationRuntimeMBean)
            appIterator.next();
         if (appName.equals(appRuntime.getApplicationName())) {
            return appRuntime;
         }
      }
      throw new Exception("Could not find RuntimeMBean for "+appName);
   }
   /**



   * Find the RuntimeMBean for a web application within a given application
   */
   private static WebAppComponentRuntimeMBean
      getWebAppComponentRuntimeMBean(ApplicationRuntimeMBean app,
      String ctxroot) throws Exception
   {
      ComponentRuntimeMBean[] compMBeans = app.lookupComponents();
      if (compMBeans == null) {
         throw new Exception("Application has no components");
      }
      for (int i=0; i<compMBeans.length; i++) {
         if (compMBeans[i] instanceof WebAppComponentRuntimeMBean) {
            WebAppComponentRuntimeMBean webMBean =
              (WebAppComponentRuntimeMBean)compMBeans[i];
            if (ctxroot.equals(webMBean.getContextRoot())) {
               return webMBean;
            }
         }
      }
      throw new Exception("Could not find web application with context
         root "+ctxroot);
   }
   /**



   * Find the RuntimeMBean for a servlet within a given web application
   */
   private static ServletRuntimeMBean
      getServletRuntimeMBean(WebAppComponentRuntimeMBean webapp,
      String servletName) throws Exception
   {
      ServletRuntimeMBean[] svltMBeans = webapp.getServlets();
      if (svltMBeans == null) {
         throw new Exception("No servlets in "+webapp.getComponentName());
      }
      for (int j=0; j<svltMBeans.length; j++) {
         if (servletName.equals(svltMBeans[j].getServletName())) {
            return svltMBeans[j];
         }
      }
      throw new Exception("Could not find servlet named "+servletName);
   }
}

Skip navigation bar  Back to Top Previous Next