Example: PMI client with new data structure

The following is example code using PMI (PMI) client with the new data structure


import com.ibm.websphere.pmi.*;
import com.ibm.websphere.pmi.stat.*;
import com.ibm.websphere.pmi.client.*;
import com.ibm.websphere.management.*;
import com.ibm.websphere.management.exception.*;
import java.util.*;
import javax.management.*;
import java.io.*;

/** 
 * Sample code to use PmiClient API (new JMX-based API in 5.0) and 
get Statistic/Stats objects.
 */

public class PmiClientTest implements PmiConstants {

    static PmiClient pmiClnt = null;
    static String nodeName = null;
    static String serverName = null;
    static String portNumber = null;
    static String connectorType = null;
    static boolean success = true;


    /**
     * @param args[0] host
     * @param args[1] portNumber, optional, default is 2809
     * @param args[2] connectorType, optional, default is RMI connector
     * @param args[3]serverName, optional, default is the first server found  
     */
    public static void main(String[] args) {

        try {

            if(args.length > 1) {
                System.out.println("Parameters: host [portNumber] 
[connectorType] [serverName]");
                return;
            }

            // parse arguments and create an instance of PmiClient
            nodeName = args[0];

            if (args.length > 1)
            portNumber = args[1];

            if (args.length > 2)
            connectorType = args[2];

            // create an PmiClient object
            pmiClnt = new PmiClient(nodeName, portNumber, "WAS50", false, connectorType);
            
            // Uncomment it if you want to debug any problem
            //pmiClnt.setDebug(true);

            // update nodeName to be the real host name
            // get all the node PerfDescriptor in the domain
               PerfDescriptor[] nodePds = pmiClnt.listNodes();
               if(nodePds == null) {
               System.out.println("no nodes");
               return;
                                   }
           // get the first node 
              nodeName = nodePds[0].getName();
            System.out.println("use node " + nodeName);

            if (args.length == 4)
                serverName = args[3];
            else { // find the server you want to get PMI data
                // get all servers on this node
                PerfDescriptor[] allservers = pmiClnt.listServers(nodeName);
                if (allservers == null || allservers.length == 0) {
                    System.out.println("No server is found on node " + nodeName);
                    System.exit(1);
                }

                // get the first server on the list. You may want to get a different server
                serverName = allservers[0].getName();
                System.out.println("Choose server " + serverName);
            }
            
            // get all MBeans
            ObjectName[] onames = pmiClnt.listMBeans(nodeName, serverName);

            // Cache the MBeans we are interested 
            ObjectName perfOName = null;
            ObjectName serverOName = null;
            ObjectName wlmOName = null;
            ObjectName ejbOName = null;
            ObjectName jvmOName = null;
            ArrayList myObjectNames = new ArrayList(10);

            // get the MBeans we are interested in
            if(onames != null) {
                System.out.println("Number of MBeans retrieved= " + onames.length);
                AttributeList al;
                ObjectName on;
                for(int i=0; i<onames.length; i++) {
                    on = onames[i];
                    String type = on.getKeyProperty("type");

                    // make sure PerfMBean is there.
                    // Then randomly pick up some MBeans for the test purpose
                    if(type != null && type.equals("Server"))
                        serverOName = on;
                    else if(type != null && type.equals("Perf"))
                        perfOName = on;
                    else if(type != null && type.equals("WLM")) {
                        wlmOName = on;
                    }
                    else if(type != null && type.equals("EntityBean")) {
                        ejbOName = on;

                        // add all the EntityBeans to myObjectNames
                        myObjectNames.add(ejbOName);  // add to the list
                    }
                    else if(type != null && type.equals("JVM")) {
                        jvmOName = on;
                    }
                }

                // set monitoring level for SERVER MBean
                testSetLevel(serverOName);

                // get Stats objects 
                testGetStats(myObjectNames);
                
                // if you know the ObjectName(s)
                testGetStats2(new ObjectName[]{jvmOName, ejbOName});

                // assume you are only interested in a server data in WLM MBean,
                // then you will need to use StatDescriptor and MBeanStatDescriptor
                // Note that  wlmModule is only available in ND version
                StatDescriptor sd = new StatDescriptor(new String[] {"wlmModule.server"});
                MBeanStatDescriptor msd = new MBeanStatDescriptor(wlmOName, sd);
                Stats wlmStat = pmiClnt.getStats(nodeName, serverName, msd, false);
                if (wlmStat != null)
                    System.out.println("\n\n WLM server data\n\n + " + wlmStat.toString());
                else 
                    System.out.println("\n\n No WLM server data is availalbe.");
                
                // how to find all the MBeanStatDescriptors
                testListStatMembers(serverOName);
                
                // how to use update method
                testUpdate(jvmOName, false, true);
            }
            else {
                System.out.println("No ObjectNames returned from Query" );
            }

        }
        catch Exception(e) {
            new AdminException(e).printStackTrace();
            System.out.println("Exception = " +e);
            e.printStackTrace();
            success = false;
        }


        if(success)
            System.out.println("\n\n All tests are passed");
        else
            System.out.println("\n\n Some tests are failed. Check for the exceptions");

    }

    /**
     * construct an array from the ArrayList
     */
    private static MBeanStatDescriptor[] getMBeanStatDescriptor ArrayList(msds) {
        if(msds == null || msds.size() == 0)
            return null;

        MBeanStatDescriptor[] ret = new MBeanStatDescriptor[msds.size()];
        for(int i=0; i<ret.length; i++)
            if(msds.get(i) instanceof ObjectName)
                ret[i] = new MBeanStatDescriptor((ObjectName)msds.get(i));
            else
                ret[i] = (MBeanStatDescriptor)msds.get(i);
        return ret;
    }

    /**
     * Sample code to navigate and display the data value from the Stats object.
     */
    private static void processStats(Stats stat) {
        processStats(stat, "");
    }

    /**
     * Sample code to navigate and display the data value from the Stats object.
     */
    private static void processStats(Stats stat, String indent) {
        if(stat == null)  return;

        System.out.println("\n\n");

        // get name of the Stats
        String name = stat.getName();
        System.out.println(indent + "stats name=" + name);

        // Uncomment the following lines to list all the data names
        /*
        String[] dataNames = stat.getStatisticNames();
        for (int i=0; i<dataNames.length; i++)
            System.out.println(indent + "    " + "data name=" + dataNames[i]);
        System.out.println("\n");
        */

        // list all datas
        com.ibm.websphere.management.statistics.Statistic[] allData = stat.getStatistics();

        // cast it to be PMI's Statistic type so that we can have get more
        Statistic[] dataMembers = (Statistic[])allData;
        if(dataMembers != null) {
            for(int i=0; i<dataMembers.length; i++)  {
                System.out.print(indent + "    " + "data name=" 
+ PmiClient.getNLSValue(dataMembers[i].getName())
                                 + ", description=" 
+ PmiClient.getNLSValue(dataMembers[i].getDescription())
                                 + ", unit=" + PmiClient.getNLSValue(dataMembers[i].getUnit())
                                 + ", startTime=" + dataMembers[i].getStartTime()
                                 + ", lastSampleTime=" + dataMembers[i].getLastSampleTime());
                if(dataMembers[i].getDataInfo().getType() == TYPE_LONG) {
                    System.out.println(", count=" 
+ ((CountStatisticImpl)dataMembers[i]).getCount());
                }
                else if(dataMembers[i].getDataInfo().getType() == TYPE_STAT) {
                    TimeStatisticImpl data = (TimeStatisticImpl)dataMembers[i];
                    System.out.println(", count=" + data.getCount()
                                       + ", total=" + data.getTotal()
                                       + ", mean=" + data.getMean()
                                       + ", min=" + data.getMin()
                                       + ", max=" + data.getMax());
                }
                else if(dataMembers[i].getDataInfo().getType() == TYPE_LOAD) {
                    RangeStatisticImpl data = (RangeStatisticImpl)dataMembers[i];
                    System.out.println(", current=" + data.getCurrent()
                                       + ", lowWaterMark=" + data.getLowWaterMark()
                                       + ", highWaterMark=" + data.getHighWaterMark()
                                       + ", integral=" + data.getIntegral()
                                       + ", avg=" + data.getMean());
                }
            }
        }

        // recursively for sub-stats
        Stats[] substats = (Stats[])stat.getSubStats();
        if(substats == null || substats.length == 0)
            return;
        for(int i=0; i<substats.length; i++) {
            processStats(substats[i], indent + "    ");
        }
    }

    /**
     * test set level and verify using get level
     */
    private static void testSetLevel ObjectName(mbean) {
        System.out.println("\n\n testSetLevel\n\n");
        try {
            // set instrumentation level to be high for the mbean
            MBeanLevelSpec spec = new MBeanLevelSpec(mbean, null, PmiConstants.LEVEL_HIGH);
            pmiClnt.setStatLevel(nodeName, serverName, spec, true);
            System.out.println("after setInstrumentaionLevel high on server MBean\n\n");

            // get all instrumentation levels 
            MBeanLevelSpec[] mlss = pmiClnt.getStatLevel(nodeName, serverName, mbean, true);
            
            if(mlss == null)
                System.out.println("error: null from getInstrumentationLevel");
            else {
                for(int i=0; i<mlss.length; i++)
                    if(mlss[i] != null) {
                        // get the ObjectName, StatDescriptor, 
and level out of MBeanStatDescriptor
                        int mylevel = mlss[i].getLevel();
                        ObjectName myMBean = mlss[i].getObjectName();
                        StatDescriptor mysd = mlss[i].getStatDescriptor();  // may be null
                        // Uncomment it to print all the mlss
                        //System.out.println("mlss " + i + ":, " + mlss[i].toString());
                    }
            }
        }
        catch Exception(ex) {
            new AdminException(ex).printStackTrace();
            ex.printStackTrace();
            System.out.println("Exception in testLevel");
            success = false;
        }
    }

    /**
     * Use listStatMembers method
     */
    private static void testListStatMembers ObjectName(mbean) {

        System.out.println("\n\ntestListStatMembers \n");
        // listStatMembers and getStats
        // From server MBean until the bottom layer.
        try {
            MBeanStatDescriptor[] msds = pmiClnt.listStatMembers(nodeName, serverName, mbean);
            if(msds == null) return;
            System.out.println(" listStatMembers for server MBean, num members 
(i.e. top level modules) is " + msds.length);

            
            for(int i=0; i<msds.length; i++) {
                if(msds[i] == null)  continue;
                
                // get the fields out of MBeanStatDescriptor if you need them
                ObjectName myMBean = msds[i].getObjectName();
                StatDescriptor mysd = msds[i].getStatDescriptor();      // may be null

                // uncomment if you want to print them out
                //System.out.println(msds[i].toString());
            }

            for(int i=0; i<msds.length; i++) {
                if(msds[i] == null)  continue;
                System.out.println("\n\nlistStatMembers for msd=" + msds[i].toString());
                MBeanStatDescriptor[] msds2 = 
pmiClnt.listStatMembers(nodeName, serverName, msds[i]);
                
                // you get msds2 at the second layer now and the 
listStatMembers can be called recursively 
                // until it returns now.
            }

        }
        catch Exception(ex) {
            new AdminException(ex).printStackTrace();
            ex.printStackTrace();
            System.out.println("Exception in testListStatMembers");
            success = false;
        }

    }

    /**
     * Test getStats method
     */
    private static void testGetStats ArrayList(mbeans) {
        System.out.println("\n\n testgetStats\n\n");
        try {
            Stats[] mystats = pmiClnt.getStats(nodeName, 
serverName, getMBeanStatDescriptor(mbeans), true);
            
            // navigate each of the Stats object and get/display the value 
            for(int k=0; k<mystats.length; k++) {
                processStats(mystats[k]);
            } 

        }
        catch Exception(ex) {
            new AdminException(ex).printStackTrace();
            ex.printStackTrace();
            System.out.println("exception from testGetStats");
            success = false;
        }
    }

    /**
     * Test getStats method
     */
    private static void testGetStats2(ObjectName[] mbeans) {
        System.out.println("\n\n testGetStats2\n\n");
        try {
            Stats[] statsArray = pmiClnt.getStats(nodeName, serverName, mbeans, true);

            // You can call toString to simply display all the data
            if(statsArray != null) {
                for(int k=0; k<statsArray.length; k++)
                    System.out.println(statsArray[k].toString());
            }
            else
                System.out.println("null stat");
        }
        catch Exception(ex) {
            new AdminException(ex).printStackTrace();
            ex.printStackTrace();
            System.out.println("exception from testGetStats2");
            success = false;
        }
    }

    /**
     * test update method
     */
    private static void testUpdate ObjectName(oName, boolean keepOld, 
boolean recursiveUpdate) {
        System.out.println("\n\n testUpdate\n\n");
        try {
            // set level to be NONE
            MBeanLevelSpec spec = new MBeanLevelSpec(oName, null, PmiConstants.LEVEL_NONE);
            pmiClnt.setStatLevel(nodeName, serverName, spec, true);


            // get data now - one is non-recursive and the other is recursive
            Stats stats1 = pmiClnt.getStats(nodeName, serverName, oName, false);
            Stats stats2 = pmiClnt.getStats(nodeName, serverName, oName, true);

            // set level to be HIGH
            spec = new MBeanLevelSpec(oName, null, PmiConstants.LEVEL_HIGH);
            pmiClnt.setStatLevel(nodeName, serverName, spec, true);

            Stats stats3 = pmiClnt.getStats(nodeName, serverName, oName, true);
            System.out.println("\n\n stats3 is");
            processStats(stats3);

            stats1.update(stats3, keepOld, recursiveUpdate);
            System.out.println("\n\n update stats1");
            processStats(stats1);

            stats2.update(stats3, keepOld, recursiveUpdate);
            System.out.println("\n\n update stats2");
            processStats(stats2);

        }
        catch Exception(ex) {
            System.out.println("\n\n Exception in testUpdate");
            ex.printStackTrace();
            success = false;
        }

    }


}


 

See Also

Developing your own monitoring application using PMI client