Chapter 18 |
Client API |
This chapter covers the following topics:
Refer to the javadocs, included in the Developer Environment CD, for details on the Client classes, their methods and descriptions, including examples. Once the product image is installed, the most up-to-date information on where the javadocs reside will be available in the following HTML file:
/opt/SUNWsymon/sdk/docs/index.html
The Sun Management Center Client Application Programming Interface (API) contains a set of public Java classes. The Sun Management Center console developers or Java applications can use these classes to retrieve data from the Sun Management Center server or the Sun Management Center agent.
The client API is packaged as a Java jar file, esclt.jar. This file is located in the following directories depending on the operating system or platform:
Client API classes are all part of com.sun.symon.base.client package.
Note - The audience for this document is programmers who have knowledge of object-oriented language and Java. This document does not explain object-oriented fundamentals.
This chapter includes many examples that can help developers get started with the Client API. These samples introduce the concepts of Request, Response, and Data classes. This section also contains information on how synchronous and asynchronous methods are programmed. Once the concepts are explained for a particular request class, the same principle applies for the various request class categories. An explanation of the functionality of the request and response classes and interfaces follow. For more information and other details on the Client API classes, refer to "Java Language Object Class Examples".
External Interface Requirements
The Client API is built on pure Java code. The JRE version is bundled with the Sun Management Center console packages. This is available on Solaris software as well as Windows versions. The Client API does not have any other external interface requirements besides the Java 1.2 package.
This section includes the following:
The Sun Management Center server stands between the Sun Management Center console on one end and the Sun Management Center agents on the other. FIGURE 18-1 illustrates this configuration:
The Sun Management Center Client API is built on top of these interfaces to provide a higher level of management functionality for the Sun Management Center console. Using this API, the console applications fetch live or historic data to configure the system dynamically.
The API supports both synchronous and asynchronous data models. The data provided by the Sun Management Center server can be instantaneous, historic data values retrieved from the Sun Management Center agents.
The following illustration represents the relationship of the Client API to the product. This illustration is followed by another which represents the Sun Management Center architecture and the Client API's relationship to the Sun Management Center software.
FIGURE 18-1 Client API Request Classes in Relationship With the Console and Server
The following figure shows:
FIGURE 18-2 The Client API and the Sun Management Center Architecture
This section covers the API Class usage for Sun Management Center Developer Environment. It includes samples to help users use the Client API:
The Sun Management Center console components have certain shared resources, like images for various hardware platforms that are stored on the Sun Management Center server. The console components download these resources using the Client API. The Client API is the only source of data for the Console components.
For the Sun Management Center software, the transport protocol between the Client API and the Sun Management Center server is based on RMI (Remote Method Invocation). According to Sun Management Center architecture standards, this could also be based on TCP or some other transport mechanism.
This package contains various classes each catering to a particular category of information being retrieved. There are classes to retrieve alarms, view log files, initiate discovery requests, create domains and so forth. These classes are bundled with the rest of the console-related classes in the form of a jar file.
The API provides support for both synchronous and asynchronous requests.
Based on the above, the API defines the following types of classes for each category of information:
There are data classes that represent the Request status or Error status. The API classes and interfaces are preceded with the prefix "SM," which distinguishes them as Sun Management Center classes.
This chapter includes examples of client API classes. Each client API class example is presented within the context of its category.
Refer to the javadocs, included in the Developer Environment CD, for details on the client classes, their methods and descriptions, including examples. Once the product image is installed, the most up-to-date information on where the javadocs reside will be available in the following HTML file:
/opt/SUNWsymon/sdk/docs/index.html
Note - All of the classes have the same format. They are all preceded by:
com.sun.symon.base.client.SM<Class or Interface Name>.
The following table contains a list of the category of classes and their examples:
TABLE 18-1 Category of Classes and Examples Category
Example
"Example: SMRawDataRequest" "Example: getURLValue Method" "Example: setURLValue Method" "Example: createURL Method" "Example: getUserId Method" "Example: SMProbeTest" "Example: SMRawDataTest" "Example: SMRawDataAsyncTest" "Example: SMAlarmObjectRequest Class" "Example: SMAlarmAsyncTest" "Example: SMAlarmSyncTest" There are no examples for this API.
![]() |
To Run the Client API Examples: |
1. | Build the examples: |
To build the examples, you need to do the following: |
a. | Create a directory where you can copy all examples:
|
b. | Copy all the DE examples from their parent directory to the directory that you
created.
|
c. | Go to the location where the examples reside and run make:
|
2. | Run each client API example using the runTest command.
|
Examples include the commands used for respective commands. For a brief example on how to run a few of the examples included in this chapter, see the section, "How to Run Examples". |
This section contains the following example:
This is the first operation that the Client API programmer must perform, before using any other category of the API. The example below illustrates the usage of SMLogin class for connection establishment with the server. Subsequently, you can log in as a valid Sun Management Center user.
The user must supply the correct arguments which are server name, server port, user name and user password in order to run the program. After running this program, once the process is started, the Client API has a live connection with the server and is ready for providing other data services:
This section includes a pointer to an example that includes the usage of SMRequestStatus. See below:
For an example of this usage of SMRequestStatus Class, see the example for "Example: SMModuleTest".
This section includes the following examples:
The SMRawDataRequest class object handle that is obtained in the login process above provides some basic type independent data operation. That is, no distinction is made whether the data is an alarm-related data or CPU data, and so forth.
This class has many overloaded methods essentially catering to various Java types. They are provided for convenience and performance-related reasons. For example, an array of objects is compared to a vector, when high performance is desired. Whereas vectors score over arrays when the amount of data being requested is dynamic.
The following are a few samples for the various functionalities for this class:
This method is a data type independent primitive to read the data for a property or a set of properties (scalar and/or vector type) from the agent or the server. The data type dependent APIs are built using this method.
TABLE 18-2 getURLValue Method url = "snmp://gurudev:161/mod/solaris-standard?managedobjects"; Vector urlvect = new Vector(); urlvect.addElement(url); data=req.getURLValue(urlvect); for (int j = 0; j < data.size(); j++) { row = (Vector) data.elementAt(j); for(int i = 0; i < row.size(); i++) { System.out.println(row.elementAt(i)); } }
The data.size() corresponds to the number of URLs being added to the urlvect variable or the number of data properties being queried. In this example, since only one URL is requested, the data.size() will return 1.
If the property is a vector or scalar, the software will return row.size().
This method is a data type independent primitive to set the data value for a property or a set of properties (scalar and/or vector type) on the agent or the server. The data type dependent APIs are built using this method.
CODE EXAMPLE 18-2 setURLValue Method String[] reqURL = new String[ 3]; StObject[][] reqdata = new StObject[ 3][1]; for(int i = 0; i < dataURL.size(); i++) { String dataurl = dataURL.elementAt(i).toString(); reqURL[i*3] = dataurl + "?historychannel"; reqdata[i*3][0] = new StString(logURL); reqURL[(i*3)+1] = dataurl + "?historyinterval"; reqdata[(i*3)+1][0] = new StString(logInterval); reqURL[(i*3)+2] = dataurl + "?historystatus"; reqdata[(i*3)+2][0] = new StString("on"); } handle.setURLValue(reqURL, reqdata);
This example illustrates how the three different attributes are set in one call. Refer to the HTML files for StObject class definition from the Sun Management Center web site.
But as indicated in the above section, both the variants are available for these methods.
Some of the samples of the above overloaded method are listed below. This method is a helper function to create a Sun Management Center URL.
Note - The Sun Management Center URL is not the same as the URL class defined in the JDK. Hence these utility method are needed. You can, however, compose their Sun Management Center URLs once you are familiar with URL structure without using these methods. The Sun Management Center agent section discusses the various types of URLs and their format. These helper methods are static methods in the SMRawDataRequest class.
CODE EXAMPLE 18-3 createURL Method System.out.println(" *Complete URL*"); try { url = SMRawDataRequest.createURL("gurudev", 0, "modules.operatingSystem.solaris.standard" , "", "user", "primaryUser" ,"mapping", "/jiten"); System.out.println(url); } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); } System.out.println(" **Testing overloaded createURL with baseURL **"); url = SMRawDataRequest.createURL( "snmp://gurudev:161/mod//modules.operatingSystem.solaris.standard", "user", "primaryUser", "mapping", "/jiten"); System.out.println(url); System.out.println(" **Testing probe create URL**"); System.out.println(" *Complete probe create URL*"); url = SMRawDataRequest.createURL("gurudev", 0, "modules.operatingSystem.solaris.standard", "", "netstat","-a"); System.out.println(url);
The SMRawDataRequest class object handle, as explained before, represents the user authenticated connection between the console and the server. This method allows the API to get the userId for this connection.
CODE EXAMPLE 18-4 getUserId Method System.out.println(" **Testing getUserId interface**"); System.out.println("Current Login session user : " + req.getUserId());
The SMProbeTest demonstrates that the console can perform an ad-hoc like query on the agent. This example assumes that the Mib2-Instrumentation module is loaded on the Sun Management Center Agent on the server host and is currently enabled. The example will either execute a 'netstat -i' or 'ifconfig -a', based on the selection in the example, and prints the output.
CODE EXAMPLE 18-5 SMProbeTest /* * @(#)SMProbeTest.java 1.2 99/11/03 * * Copyright (c) 11/03/99 Sun Microsystems, Inc. All Rights Reserved. */ import com.sun.symon.base.client.*; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.SocketException; /** * This class gives an example of the usage of probeConnect method in * SMRawDataRequest class. This method returns only one TCP socket handle, * established with the probe application. This is to be used for read/write * application data. The probeConnectWithStderr is a variant of this method. * It returns two socket handles. One for data as above and the other for * errors passed from the probe application. */ public class SMProbeTest { private Socket sock; public SMProbeTest( String server_name, int server_port, int agent_port, String user, String password ) throws SMAPIException { sock = null; try { String publicKey = "687a8398ad4a85077d33b72a94e16ffde0c4ba023e" + "9c9ba77b247cc25bd3cd0015bc24b7429916751e68" + "1fd02e5ad6eb5345eb7c75b39a1c304e0f000846aa" + "470b755b0640af974e7fc70daa6191dff6efa31a09" + "431bb5e9848b7dc4cf4b97e1dbca31792d2860ca5a" + "5990dfb369e1bcf296274a4e4984c8089329679dd3" + "04cd"; System.out.println("\n...Testing Connect...\n"); SMLogin obj = new SMLogin(); obj.connect(server_name, server_port, user, password, publicKey); System.out.println("Successfully Connected and Authenticated"); SMRawDataRequest req = obj.getRawDataRequest(); System.out.println( "This example assumes that the Mib2-Instrumentation module "+ "is loaded on the Sun Management Center Agent on the server "+ "host and is currently enabled.\n" + "This probe command will either execute a 'netstat -i' or "+ "'ifconfig -a', based on the selection in this program, and "+ "prints the output."); String probeURL = "snmp://" + server_name + ":" + agent_port + "/mod/mib2-instr/interfaces?runadhoccommand."; // set to true if you want 'ifconfig -a' to be executed. boolean useIfconfig = true; if (useIfconfig) probeURL += "ifconfig_a"; else probeURL += "netstat_i"; System.out.println("url: " + probeURL); sock = req.probeConnect(probeURL, null); System.out.println(getData()); } catch (Exception e) { System.out.println(e.toString()); } finally { closeConnection(); } } public Object getData() throws SMAPIException { // The following timeout is added as InputStream fails to return // -1 on end of stream. Without this timeout the sock.read blocks // forever even though the probe application is done, sending all of // its response data. Alternate implementations are also possible. // This is only an example. try { sock.setSoTimeout(2000); } catch (SocketException e) { throw new SMAPIException(e.getMessage()); } OutputStream op; InputStream ip; try { op = sock.getOutputStream(); ip = sock.getInputStream(); // If your application requires data to be written, // use op.write() and op.flush(). } catch(Exception e) { throw new SMAPIException(e.getMessage()); } StringBuffer tmp = new StringBuffer(); byte buff[] = new byte[4096]; int len = -1; while (true) { try { len = ip.read(buff); } catch ( Exception e ) { break; } if (len == -1) break; tmp.append(new String(buff, 0, len)); } if (tmp.length() == 0) // no data return null; return tmp; } public void closeConnection() throws SMAPIException { try { if (sock != null) { sock.close(); sock = null; } } catch(Exception e) { throw new SMAPIException(e.getMessage()); } } private static void usage() { System.out.println( "usage: java SMProbeTest " + "server_name server_port agent_port user password"); } public static void main(String[] args) throws Exception { if ( args.length != 5) { usage(); System.exit(1); } else { new SMProbeTest (args[0], new Integer(args[1]).intValue(), new Integer(args[2]).intValue(), args[3], args[4]); System.exit(0); } } }
The SMRawDataTest demonstrates the usage of methods from the class SMRawDataRequest. At the later part of the example, it will retrieve the CPU Idle time and the CPU User time from the kernel reader module.
CODE EXAMPLE 18-6 SMRawDataTest /* * @(#)SMRawDataTest.java 1.1 99/09/13 * * Copyright (c) 09/13/99 Sun Microsystems, Inc. All Rights Reserved. */ import com.sun.symon.base.client.*; import java.util.Vector; public class SMRawDataTest { public SMRawDataTest( String server_name, int server_port, int agent_port, String user, String password ) throws Exception { try { String publicKey = "687a8398ad4a85077d33b72a94e16ffde0c4ba023e" + "9c9ba77b247cc25bd3cd0015bc24b7429916751e68" + "1fd02e5ad6eb5345eb7c75b39a1c304e0f000846aa" + "470b755b0640af974e7fc70daa6191dff6efa31a09" + "431bb5e9848b7dc4cf4b97e1dbca31792d2860ca5a" + "5990dfb369e1bcf296274a4e4984c8089329679dd3" + "04cd"; System.out.println("*** Testing Connect ****"); SMLogin obj = new SMLogin(); obj.connect(server_name, server_port, user, password, publicKey); System.out.println("Successfully Connected and Authenticated "); SMRawDataRequest req = obj.getRawDataRequest(); System.out.println("*** Testing the SMRawDataRequest ***"); // This method is used by the client application to know // location of the topology server System.out.println("** Testing getTopologyBaseURL**"); System.out.println("Topology Base URL = " + req.getTopologyBaseURL()); // This method is used by the client application to know // location of the Event manager server System.out.println("** Testing getEventBaseURL**"); System.out.println("Event Base URL = " + req.getEventBaseURL()); // This method is used by the client application to know // position of the Configuration manager server System.out.println("** Testing getConfigurationBaseURL**"); System.out.println("Config Base URL = " + req.getConfigurationBaseURL()); // This method enables the Client API // to get the userid of the current server session System.out.println("**Testing getUserId interface**"); System.out.println("Current Login session user : " + req.getUserId()); System.out.println("**Testing getURLValue **"); String[] urlarr = new String[2]; urlarr[0] = "snmp://" + server_name + ":" + agent_port + "/mod/kernel-reader/cpu-detail/cpu-util/cpuUtilTable/" + "cpuUtilEntry/cpu_idle"; urlarr[1] = "snmp://" + server_name + ":" + agent_port + "/mod/kernel-reader/cpu-detail/cpu-util/cpuUtilTable/" + "cpuUtilEntry/cpu_user"; Vector urlvect = new Vector(); urlvect.addElement(urlarr[0]); urlvect.addElement(urlarr[1]); Vector dat = req.getURLValue(urlvect); if (dat.size() != 2) throw new SMAPIException("Incorrect data returned"); for (int i = 0; i < dat.size(); i++) { Vector row = (Vector) dat.elementAt(i); for (int j = 0; j < row.size() ; j++) { if (i == 0) System.out.println("% CPU Idle time for cpu(s): " + row.elementAt(j)); else System.out.println("% CPU User time for cpu(s): " + row.elementAt(j)); } } } catch ( Exception e) { System.out.println(e.getMessage()); } } private static void usage() { System.out.println( "usage: java SMRawDataTest " + "server_name server_port agent_port user password"); } public static void main(String[] args) throws Exception { if ( args.length != 5) { usage(); System.exit(1); } else { new SMRawDataTest (args[0], new Integer(args[1]).intValue(), new Integer(args[2]).intValue(), args[3], args[4]); System.exit(0); } } }
The SMRawDataAsyncTest is basically doing the same test as SMRawDataTest. This example makes use of an asynchrous request in a periodic cycle of 60 seconds. Every periodic time-out will cause the server to call back and the getURLresponse method will be invoked.
CODE EXAMPLE 18-7 SMRawDataAsyncTest /* * @(#)SMRawDataAsyncTest.java 1.1 99/09/13 * * Copyright (c) 09/13/99 Sun Microsystems, Inc. All Rights Reserved. */ import com.sun.symon.base.client.*; import java.util.Vector; public class SMRawDataAsyncTest extends SMRawDataResponseAdapter { public SMRawDataAsyncTest( String server_name, int server_port, int agent_port, String user, String password ) throws Exception { try { String publicKey = "687a8398ad4a85077d33b72a94e16ffde0c4ba023e" + "9c9ba77b247cc25bd3cd0015bc24b7429916751e68" + "1fd02e5ad6eb5345eb7c75b39a1c304e0f000846aa" + "470b755b0640af974e7fc70daa6191dff6efa31a09" + "431bb5e9848b7dc4cf4b97e1dbca31792d2860ca5a" + "5990dfb369e1bcf296274a4e4984c8089329679dd3" + "04cd"; System.out.println("*** Testing Connect ****"); SMLogin obj = new SMLogin(); obj.connect(server_name, server_port, user, password, publicKey); System.out.println("Successfully Connected and Authenticated"); SMRawDataRequest req = obj.getRawDataRequest(); System.out.println("***Testing the Async. SMRawDataRequest ***"); System.out.println("**Testing getURLValue **"); // This is an example of how an async. cyclic URL request can be // placed. This request will cause a server callback every 60 // seconds for the following URLs. If period is null then there // will be only a one time callback with the values for the URL. String[] urlarr = new String[2]; urlarr[0] = "snmp://" + server_name + ":" + agent_port + "/mod/kernel-reader/cpu-detail/cpu-util/cpuUtilTable" + "/cpuUtilEntry/cpu_idle"; urlarr[1] = "snmp://" + server_name + ":" + agent_port + "/mod/kernel-reader/cpu-detail/cpu-util/cpuUtilTable/" + "cpuUtilEntry/cpu_user"; Vector urlvect = new Vector(); urlvect.addElement(urlarr[0]); urlvect.addElement(urlarr[1]); req.getURLValue(urlvect, "60", this, this); System.out.println("sleeping..."); Thread.sleep(200 * 1000); } catch (Exception e) { System.out.println(e.getMessage()); } } public void getURLResponse( SMRequestStatus status, Vector dat, Object identifier) { int error = status.getReturnCode(); if (error == SMErrorCode.SUCCESS) { if (dat.size() != 2) { System.out.println("Incorrect data returned. size =" + dat.size()); } else { for (int i = 0; i < dat.size(); i++) { Vector row = (Vector) dat.elementAt(i); for (int j = 0; j < row.size() ; j++) { if (i == 0) System.out.println("% CPU Idle time for cpu(s): " + row.elementAt(j)); else System.out.println("% CPU User time for cpu(s): " + row.elementAt(j)); } } } } else { // Failure // The various error codes as in SMErrorCode may be reported here System.out.println("Error code = " + error + " " + "Msg Text = " + status.getMessageText() + " " + "Exception = " + (status.getException()).getMessage()); } } private static void usage() { System.out.println( "usage: java SMRawDataAsyncTest " + "server_name server_port agent_port user password"); } public static void main(String[] args) throws Exception { if ( args.length != 5) { usage(); System.exit(1); } else { new SMRawDataAsyncTest (args[0], new Integer(args[1]).intValue(), new Integer(args[2]).intValue(), args[3], args[4]); System.exit(0); } } }
This section includes the following example:
The following are examples related to the SMAlarmObjectRequest class:
The following examples illustrate both the synchronous and asynchronous usage of the API.
The SMAlarmAsyncTest demonstrates the usage of the client.alarm API to query the alarm information from the server. Notice the example is doing the request asynchronously. The program will go into a sleep mode for a certain period of time and then wake up to response the callback from the server.
SMAlarmAsyncTest
*/ * @(#)SMAlarmAsyncTest.java 1.2 00/08/11 * * Copyright (c) 08/11/00 Sun Microsystems, Inc. All Rights Reserved. */ import com.sun.symon.base.client.*; import com.sun.symon.base.client.alarm.*; import java.util.Vector; /** * This class is for testing the Client API. **/ public class SMAlarmAsyncTest implements SMAlarmObjectResponse { private SMAlarmObjectRequest alreq = null; public SMAlarmAsyncTest( String server_name, int server_port, int agent_port, String user, String password ) throws Exception { try { String publicKey = "687a8398ad4a85077d33b72a94e16ffde0c4ba023e" + "9c9ba77b247cc25bd3cd0015bc24b7429916751e68" + "1fd02e5ad6eb5345eb7c75b39a1c304e0f000846aa" + "470b755b0640af974e7fc70daa6191dff6efa31a09" + "431bb5e9848b7dc4cf4b97e1dbca31792d2860ca5a" + "5990dfb369e1bcf296274a4e4984c8089329679dd3" + "04cd"; System.out.println("*** Testing Connection ****"); SMLogin obj = new SMLogin(); System.out.println("Before Connection Establishment"); obj.connect(server_name, server_port, user, password, publicKey); System.out.println("Successfully Connected and Authenticated"); SMRawDataRequest req = obj.getRawDataRequest(); System.out.println(" ***Testing SMAlarmObjectRequest class ***"); alreq = new SMAlarmObjectRequest(req, null); Vector allist = null; System.out.println("** Initiating a fresh request to get alarms**"); // get alarms on host alreq.getAlarms("1", server_name, null , "{ERR} {WRN}", "{O} {C} {F}", null, null, null, null, this, new Object()); System.out.println("sleeping..."); Thread.sleep(60 * 1000); } catch ( Exception e) { System.out.println(e.getMessage()); } } public void getAlarmResponse(SMRequestStatus status, Vector data, Object identifier, SMAlarmIteratorAsync iter) { if (data == null) return; SMAlarmObjectData aldata=null; System.out.println("Callback:size " + data.size()); for(int i = 0; i < data.size(); i++) { aldata = (SMAlarmObjectData)data.elementAt(i); String host = aldata.getHost(); System.out.println("Alarm Id: "+ aldata.getAlarmId()); System.out.println("Rule Id: "+ aldata.getAlarmRuleId()); System.out.println("Open Time stamp: "+ aldata.getOpenTimestamp()); System.out.println("Alarm text: " + aldata.getAlarmShortText()); System.out.println("Alarm Long Key : "+ aldata.getAlarmLongKey()); System.out.println("Target host: " + aldata.getHost()); System.out.println("Agent Port: " + aldata.getAgentPort()); System.out.println("Module: " + aldata.getModule()); System.out.println("Module Instance: " + aldata.getModuleInstance()); System.out.println("Managed Object: " + aldata.getManagedObject()); System.out.println("Attribute: " + aldata.getAttribute()); System.out.println("Property: " + aldata.getProperty()); System.out.println("Property Instance: " + aldata.getPropertyInstance()); System.out.println("Property Type: " + aldata.getPropertyType()); System.out.println("Alarm State: " + aldata.getAlarmState()); System.out.println("Alarm Severity: " + aldata.getSeverity()); System.out.println("Upd Time stamp: " + aldata.getUpdateTimestamp()); System.out.println("Upd Reason: "+ aldata.getUpdateReason()); System.out.println("Machine Type: "+ aldata.getMachineType()); System.out.println("Rule Group: "+ aldata.getRuleGroup()); System.out.println("Clo Time stamp: " + aldata.getCloseTimestamp()); System.out.println("Ack Time stamp: " + aldata.getAckTimestamp()); System.out.println("Ack operator: " + aldata.getAckOperator()); System.out.println("Fix Time stamp: " + aldata.getFixTimestamp()); System.out.println("Fix operator: " + aldata.getFixOperator()); } try { if (data.size() > 0) iter.getNextAlarms(); } catch(Exception e){ e.printStackTrace(); } } public void setAlarmResponse(SMRequestStatus status, Object identifier) {} private static void usage() { System.out.println("usage: java SMAlarmAsyncTest " + "server_name server_port agent_port name password"); } public static void main(String[] args) throws Exception { if ( args.length != 5) { usage(); System.exit(1); } else { new SMAlarmAsyncTest (args[0], new Integer(args[1]).intValue(), new Integer(args[2]).intValue(), args[3], args[4]); System.exit(0); } } } /*
SMAlarmSyncTest basically performs the same test as SMAlarmAsyncTest except that the program does not go into any sleep mode.
SMAlarmSyncTest
/* * @(#)SMAlarmSyncTest.java 1.2 00/08/11 * * Copyright (c) 08/11/00 Sun Microsystems, Inc. All Rights Reserved. */ import com.sun.symon.base.client.*; import com.sun.symon.base.client.alarm.*; import java.util.Vector; /** * This class is for testing the Client API. **/ public class SMAlarmSyncTest { private SMAlarmObjectRequest alreq = null; public SMAlarmSyncTest( String server_name, int server_port, int agent_port, String user, String password ) throws Exception { try { String publicKey = "687a8398ad4a85077d33b72a94e16ffde0c4ba023e" + "9c9ba77b247cc25bd3cd0015bc24b7429916751e68" + "1fd02e5ad6eb5345eb7c75b39a1c304e0f000846aa" + "470b755b0640af974e7fc70daa6191dff6efa31a09" + "431bb5e9848b7dc4cf4b97e1dbca31792d2860ca5a" + "5990dfb369e1bcf296274a4e4984c8089329679dd3" + "04cd"; System.out.println("*** Testing Connection ****"); SMLogin obj = new SMLogin(); System.out.println("Before Connection Establishment"); obj.connect(server_name, server_port, user, password, publicKey); System.out.println("Successfully Connected and Authenticated"); SMRawDataRequest req = obj.getRawDataRequest(); System.out.println(" ***Testing SMAlarmObjectRequest class ***"); alreq = new SMAlarmObjectRequest(req, null); System.out.println(" ** Testing Sync. getAlarms with moURL **"); SMAlarmIteratorSync iter = alreq.getAlarms("1", null, null, "{ERR} {WRN}", "{O} {C} {F}", null, null, null, null); Vector allist = iter.getData(); SMAlarmObjectData aldata=null; while (allist.size() > 0) { System.out.println(allist.size()); for(int i = 0; i < allist.size(); i++) { aldata = (SMAlarmObjectData)allist.elementAt(i); System.out.println("Alarm Id : " + aldata.getAlarmId()); System.out.println("Rule Id : " + aldata.getAlarmRuleId()); System.out.println("Open Time stamp : " + aldata.getOpenTimestamp()); System.out.println("Alarm text : " + aldata.getAlarmShortText()); System.out.println("Alarm Long Key : " + aldata.getAlarmLongKey()); System.out.println("Target host : " + aldata.getHost()); System.out.println("Agent Port : " + aldata.getAgentPort()); System.out.println("Module : " + aldata.getModule()); System.out.println("Module Instance : " + aldata.getModuleInstance()); System.out.println("Managed Object : " + aldata.getManagedObject()); System.out.println("Attribute : " + aldata.getAttribute()); System.out.println("Property : " + aldata.getProperty()); System.out.println("Property Instance: " + aldata.getPropertyInstance()); System.out.println("Property Type : " + aldata.getPropertyType()); System.out.println("Alarm State : " + aldata.getAlarmState()); System.out.println("Alarm Severity : " + aldata.getSeverity()); System.out.println("Upd Time stamp : " + aldata.getUpdateTimestamp()); System.out.println("Upd Reason : " + aldata.getUpdateReason()); System.out.println("Machine Type : " + aldata.getMachineType()); System.out.println("Rule Group : " + aldata.getRuleGroup()); System.out.println("Clo Time stamp : " + aldata.getCloseTimestamp()); System.out.println("Ack Time stamp : " + aldata.getAckTimestamp()); System.out.println("Ack operator : " + aldata.getAckOperator()); System.out.println("Fix Time stamp : " + aldata.getFixTimestamp()); System.out.println("Fix operator : " + aldata.getFixOperator()); Vector ret = null; String[] id = new String[1]; // set the following to true if you actually want // to modify the alarms. boolean modifyAlarms = false; if (modifyAlarms) { // Note the following test code for // ack/fix/delete is just an // example of its usage if (!aldata.isFixed()) { System.out.println("** Testing ack alarms **"); if (aldata != null) { id[0] = aldata.getAlarmId(); ret = alreq.ackAlarms(id, "just for" + " the heck of it"); } else { System.out.println("No alarm to be acked"); } if (ret == null) { System.out.println("Ack Success"); } else { System.out.println("Ack Failed"); } if (aldata.isOpen()) { System.out.println("** Testing fix alarms **"); ret = null; if (aldata != null) { id[0] = aldata.getAlarmId(); ret = alreq.fixAlarms(id, "just for the heck of it"); } else { System.out.println("No alarm to be fixed"); } if (ret == null) { System.out.println("Fix Success"); } else { System.out.println("Fix Failed"); } } } System.out.println("** Testing delete alarms **"); ret= null; if (aldata != null) { id[0] = aldata.getAlarmId(); ret = alreq.deleteAlarms(id, "just for the heck of it"); } else { System.out.println("No alarm to be deleted"); } if (ret == null) { System.out.println("Success"); } else { System.out.println("Failed"); } } } System.out.println("** Requesting the next batch**"); iter = iter.getNextAlarms(); allist = iter.getData(); } } catch (Exception e) { System.out.println(e.getMessage()); } } private static void usage() { System.out.println("usage: java SMAlarmSyncTest " + "server_name server_port agent_port user password"); } public static void main(String[] args) throws Exception { if ( args.length != 5) { usage(); System.exit(1); } else { new SMAlarmSyncTest (args[0], new Integer(args[1]).intValue(), new Integer(args[2]).intValue(), args[3], args[4]); System.exit(0); } } }
This section includes the following example:
This is a class that uses the services of the SMRawDataRequest class in order to get data type dependent information.
This class is used to programmatically query the schema of the properties defined in the agent. This section provides the organization of the schema on the agent.
The agent contains one or more modules. A module is made up of one or more managed objects. Each managed object contains one or more properties. And each property has qualifiers. For a detailed explanation of these terms, refer to the Sun Management Center architecture document and the agent section.
The examples in this section include a few examples of how this class is used for the purpose of obtaining the values for the above entities.
The constructor of this class takes the SMRawDataRequest object handle, which encapsulates the authenticated RMI connection handle with the server, in order to be capable of sending requests over the RMI to the server. This concept is used for every other API request class instantiation in Sun Management Center.
CODE EXAMPLE 18-8 SMManagedEntityTest /* * @(#)SMManagedEntityTest.java 1.2 99/10/15 * * Copyright (c) 10/15/99 Sun Microsystems, Inc. All Rights Reserved. */ import com.sun.symon.base.client.*; import com.sun.symon.base.client.attribute.*; import java.util.Vector; /** * This class is for testing the Client API. **/ public class SMManagedEntityTest { public SMManagedEntityTest( String server_name, int server_port, int agent_port, String user, String password ) throws Exception { try { /*Checkout SMLogin.java for Login/Authentication Test */ String publicKey = "687a8398ad4a85077d33b72a94e16ffde0c4ba023e" + "9c9ba77b247cc25bd3cd0015bc24b7429916751e68" + "1fd02e5ad6eb5345eb7c75b39a1c304e0f000846aa" + "470b755b0640af974e7fc70daa6191dff6efa31a09" + "431bb5e9848b7dc4cf4b97e1dbca31792d2860ca5a" + "5990dfb369e1bcf296274a4e4984c8089329679dd3" + "04cd"; System.out.println("*** Testing Connection ****"); SMLogin obj = new SMLogin(); obj.connect(server_name, server_port, user, password, publicKey); System.out.println("Successfully Connected and Authenticated."); SMRawDataRequest req = obj.getRawDataRequest(); // This file lists the usage of the various methods supported by // the SMManagedEntityRequest class. // The basic usage of this class is to request // the schema of the MIB supported on the agent. System.out.println("**Testing ManagedEntityRequest **"); SMManagedEntityRequest mreq = new SMManagedEntityRequest(req); System.out.println("**Testing getManagedObjectList method**"); // The following method is used to list all the Managed // objects associated with a module. // The following call lists all the managed objects instrumented // on the "kernel-reader" module. String[] urlarr = new String[1]; urlarr[0] = "snmp://" + server_name + ":" + agent_port + "/mod/kernel-reader"; Vector molist = mreq.getManagedObjectList(urlarr[0]); for (int i = 0; i < molist.size(); i++) { System.out.println(molist.elementAt(i).toString()); } // The SyMON agent supports managed object properties // which are internal to the agent/console // usage and should not be exposed to the SyMON console // browser in the form of tables etc. // The following call lists the visible properties // (can be displayed in the SyMON browser), // for a managed object based on a module. // Eg. The call below lists the visible properties for a // Managed object "filesystem" on a "kernel-reader" module. // ------------------------------------------------------------------------ System.out.println("**Testing getVisiblePropertyList method**"); urlarr[0] = "snmp://" + server_name + ":" + agent_port + "/mod/kernel-reader"; Vector plist =mreq.getVisiblePropertyList(urlarr[0], "filesystem"); System.out.println("The visible property data for URL " + urlarr[0] + "/filesystem"); for (int i = 0; i < plist.size(); i++) { System.out.println("Visible Property Name : " + plist.elementAt(i).toString()); } // ------------------------------------------------------------------------ System.out.println( "**Testing getVisiblePropertyDataList method**"); // This method is similar to the method above, // but in addition to the name of the property, it also returns // the type of the property eg. Vector , Scalar etc. urlarr[0] = "snmp://" + server_name + ":" + agent_port + "/mod/kernel-reader"; Vector pdlist = mreq.getVisiblePropertyDataList(urlarr[0], "filesystem"); System.out.println("The visible property data for URL " + urlarr[0] + "/filesystem"); for (int i = 0; i < pdlist.size(); i++) { SMPropertyData pd = (SMPropertyData)pdlist.elementAt(i); System.out.println("Visible Property Name : " + pd.getPropertyName() + " " + "Property Type : " + ((pd.getPropertyType()) ? "scalar" : "vector")); } // The following method is used to list all the // properties supported by a managed object on a // particular module. This includes the visible/hidden // properties supported by the managed object. // ------------------------------------------------------------------------ System.out.println("**Testing getPropertyList method**"); urlarr[0] = "snmp://" + server_name + ":" + agent_port + "/mod/kernel-reader"; Vector vplist = mreq.getPropertyList(urlarr[0], "filesystem"); System.out.println("The property data for URL "+ urlarr[0]+ "/filesystem"); for (int i = 0; i < vplist.size(); i++) { System.out.println("Property Name : " + vplist.elementAt(i).toString()); } // This method is similar to the above, // but in addition lists the type of the property, as a // Vector or a scalar. // ------------------------------------------------------------------------ System.out.println("**Testing getPropertyDataList method**"); urlarr[0] = "snmp://" + server_name + ":" + agent_port + "/mod/kernel-reader"; Vector vpdlist =mreq.getPropertyDataList(urlarr[0], "filesystem"); System.out.println("The property data for URL " + urlarr[0] + "/filesystem"); for (int i = 0; i < vpdlist.size(); i++) { SMPropertyData vpd = (SMPropertyData)vpdlist.elementAt(i); System.out.println("Property Name : " + vpd.getPropertyName() + " " + "Property Type : " + ((vpd.getPropertyType()) ? "scalar" : "vector")); } // This method is used to list all // the tables associated with a managed object. // ------------------------------------------------------------------------ System.out.println("**Testing getTableList method**"); urlarr[0] = "snmp://" + server_name + ":" + agent_port + "/mod/kernel-reader"; Vector tlist = mreq.getTableList(urlarr[0], "filesystem"); System.out.println("The tables for URL "+ urlarr[0]+"/filesystem"); for (int i = 0; i < tlist.size(); i++) { System.out.println("Table Name : " + tlist.elementAt(i).toString()); } // ------------------------------------------------------------------------ System.out.println("**Testing getTableSchema method**"); for (int i = 0; i < tlist.size(); i++) { Vector ts = mreq.getTableSchema(urlarr[0], "filesystem", tlist.elementAt(i).toString()); System.out.println("Table Schema for filesystem"); for( int x = 0 ; x < ts.size() ; x++) { System.out.println("Column("+x+") = " + ts.elementAt(x).toString()); } } // ------------------------------------------------------------------------ // Read the contents of the table. System.out.println("**Testing getTableValue method**"); for (int i = 0; i < tlist.size(); i++) { Vector v = mreq.getTableValue(urlarr[0], "filesystem", tlist.elementAt(i).toString()); for(int j = 0; j < v.size() ; j++ ) { Vector rowd = (Vector)v.elementAt(j); System.out.println(rowd.size()); System.out.print("Row Data : "); for(int k = 0; k < rowd.size() ; k++ ) { System.out.print(rowd.elementAt(k).toString()+ " "); System.out.print(""); } } } // For SyMON agents every Managed object property // has a list of attributes called Qualifiers. // The following method lists the qualifiers for // a managed object property. // ------------------------------------------------------------------------ System.out.println("**Testing getQualifierList method**"); urlarr[0] = "snmp://" + server_name + ":" + agent_port + "/mod/kernel-reader"; Vector qlist = mreq.getQualifierList(urlarr[0], "user", "primaryUser"); System.out.println("The qualifier data for URL " + urlarr[0]+"/user/primaryUser"); for (int i = 0; i < qlist.size(); i++) { System.out.println("Qualifier Name : " + qlist.elementAt(i).toString()); } } catch ( Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); } } private static void usage() { System.out.println( "usage: java SMManagedEntityTest " + "server_name server_port agent_port user password"); } public static void main(String[] args) throws Exception { if ( args.length != 5) { usage(); System.exit(1); } else { new SMManagedEntityTest(args[0], new Integer(args[1]).intValue(), new Integer(args[2]).intValue(), args[3], args[4]); System.exit(0); } } }
This section includes information on the following:
This example also has the usage for SMRequestStatus class, which is used for reporting errors in asynchronous methods.
The SMModuleTest demonstrates the dumping of modules information from the agents. In this example, the program will list modules and loaded modules, get the Health Monitor module's information as specified in the corresponding configuration file. It will also load, disable, enable, and unload the Health Monitor module. Finally, it demonstrates getting the module information in asynchronous mode.
CODE EXAMPLE 18-9 SMModuleTest /* * @(#)SMModuleTest.java 1.6 99/10/15 * * Copyright (c) 10/15/99 Sun Microsystems, Inc. All Rights Reserved. */ import com.sun.symon.base.client.*; import com.sun.symon.base.client.module.*; import java.util.StringTokenizer; import java.util.Vector; public class SMModuleTest implements SMModuleResponse { public SMModuleTest( String server_name, int server_port, int agent_port, String user, String password ) throws Exception { try { String publicKey = "687a8398ad4a85077d33b72a94e16ffde0c4ba023e" + "9c9ba77b247cc25bd3cd0015bc24b7429916751e68" + "1fd02e5ad6eb5345eb7c75b39a1c304e0f000846aa" + "470b755b0640af974e7fc70daa6191dff6efa31a09" + "431bb5e9848b7dc4cf4b97e1dbca31792d2860ca5a" + "5990dfb369e1bcf296274a4e4984c8089329679dd3" + "04cd"; // Connection establish System.out.println("\n...Testing Connection ...\n"); SMLogin obj = new SMLogin(); System.out.println("Before Connection Establishment"); obj.connect(server_name, server_port, user, password, publicKey); System.out.println("Successfully Connected and Authenticated"); SMRawDataRequest req = obj.getRawDataRequest(); // SMModuleRequest System.out.println("\n... Testing the SMModuleRequest ...\n"); SMModuleRequest modreq = new SMModuleRequest(req); System.out.println("\n...... List All the Modules ......\n"); Vector allmodlist = modreq.listModules(server_name, agent_port); for(int i = 0; i < allmodlist.size(); i++){ System.out.println(allmodlist.elementAt(i)); } // List Loaded Modules System.out.println("\n...... List Loaded Modules ......\n"); Vector loadmodlist = modreq.listLoadedModules(server_name, agent_port); for(int i = 0; i < loadmodlist.size(); i++){ System.out.println(loadmodlist.elementAt(i)); } // Get Loaded Module Info System.out.println("\n......Get Loaded Module Info......\n"); String[][] loadmodinfo = modreq.getLoadedModuleInfo(server_name, agent_port); for(int i = 0; i < loadmodinfo.length ; i++) { // This will display the localized description for the module System.out.println("Module Name = " + loadmodinfo[i][0]); System.out.println("Module URL = " + loadmodinfo[i][1]); } // Use the health monitor module String module = "health-monitor"; String modinst = null; String moduleName = "Health Monitor"; String modUrl = "snmp://" + server_name + ":" + agent_port + "/mod/" + module; System.out.println("\n....... Get the " + moduleName + "Module's loading info. as specified in X-file ......\n"); String moduleX = modreq.getModuleXfile(server_name, agent_port, module); System.out.println("Module X-file info = " + moduleX); System.out.println("\n......Load Health Monitor Module......\n"); String modparam = getModuleParamFromX(moduleX); System.out.println(modparam); modparam = "moduleName = \"Health Monitor\"; version = \"2.0\";" + " console = \"health-monitor\"; enterprise = \"sun\"; " + " i18nModuleName = \"base.modules.health-monitor:moduleName\";"+ " i18nModuleType = \"base.modules.health-monitor:moduleType\";"+ " i18nModuleDesc = \"base.modules.health-monitor:moduleDesc\";"+ " location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.healthMonitor\";"; if (!modreq.loadModule(server_name, agent_port, module, modinst, modparam)) System.out.println(moduleName + " module is already loaded"); else System.out.println(moduleName + " module is successfully loaded"); System.out.println("\n......Check Module Loaded/Unloaded.....\n"); if ( modreq.isModuleLoaded(server_name, agent_port, module) ) System.out.println(moduleName+ " is loaded !"); else System.out.println(moduleName+ " is unloaded !"); System.out.println("\n......Get Module Data.....\n"); Vector modV = modreq.getModuleData(server_name, agent_port, module); SMModuleData modData; if ( modV == null ) { System.out.println("no module data is available"); } else { for ( int i=0; i<modV.size(); i++ ) { modData = (SMModuleData)modV.elementAt(i); System.out.println(modData.getModule()+", "+ modData.getModuleName()+", "+ modData.getModuleInstance()+", "+ modData.getModuleLocation()); } } // Get Module Parameters System.out.println("\n **Get Module Parameters** \n"); String mParams = modreq.getModuleParams(server_name, agent_port, module, modinst); System.out.println(mParams); // Disable Module System.out.println("**Disable Module **"); if (modreq.disableModule(server_name,agent_port,module,modinst)) { System.out.println(moduleName + " module is successfully disabled"); } else { System.out.println(moduleName + " module is already disabled"); } // Enable Module System.out.println("**Enable Module **"); if (modreq.enableModule(server_name,agent_port,module,modinst)) { System.out.println(moduleName + " module is successfully enabled"); } else { System.out.println(moduleName + " module is already enabled"); } System.out.println("**Unload Module **"); modreq.unloadModule(server_name, agent_port, module, modinst); System.out.println(moduleName + " module is successfully unloaded"); // Get info of all modules System.out.println("\n...... " + "Get module loading/select info. async. ......\n"); // The following method submits the callback // interface implementation to receive the info. // This interface is also implemented by this class modreq.getModuleInfoRequest(server_name, agent_port, "20", this); System.out.println("Sleeping..."); Thread.sleep(60 *1000); } catch ( Exception e) { System.out.println(e.toString()); e.printStackTrace(); } } public void getModuleInfoResponse(SMRequestStatus status, SMModuleInfo[] data){ // The callback may also be reporting an error condition, // hence this check is essential. int error = status.getReturnCode(); if (error == SMErrorCode.SUCCESS) { /*Success */ System.out.println("\n*************"); for(int i = 0; i < data.length; i++) { // Number of modules System.out.println("Module Name = " + data[i].getModuleName() + " Module Id = " + data[i].getModuleId() + " Module inst. Loaded = " + data[i].getCurrentLoadCount() + " Can more inst. be loaded ? = " + data[i].canLoadAnother()); } } else { /* Failure */ //The various error codes as in SMErrorCode may be reported here */ System.out.println("Error code = " + error + " " + "Msg Text = " + status.getMessageText() + " " +"Exception = " + (status.getException()).getMessage()); } } /* The following methods have empty implementations.*/ public void getLoadedModulesResponse(SMRequestStatus status, Vector data, Object identifier) {} /** * Gets the module parameters (suitable for use with loadModule) * from the return value of getModuleXfile() as input. * Strip out all param:name = value and concatenate them. For example: * <pre> * param:module = health-monitor * param:moduleName = Health Monitor * * will return: module = health-monitor; moduleName = Health Monitor; **/ private String getModuleParamFromX(String x) { StringTokenizer tok = new StringTokenizer(x, "\n"); StringBuffer s = new StringBuffer(); String t; while (tok.hasMoreTokens()) { t = tok.nextToken(); if (t.startsWith("param:")) { s.append(t.substring(6)); // skip over "param:" s.append("; "); } } return s.toString(); } private static void usage() { System.out.println("usage: java SMModuleTest" + " server_name server_port agent_port user password"); } public static void main(String[] args) throws Exception { // args[0] is server_name // args[1] is server_port // args[2] is agent_port // args[3] is user // args[4] is password if (args.length != 5) usage(); else new SMModuleTest( args[0], new Integer(args[1]).intValue(), new Integer(args[2]).intValue(), args[3], args[4] ); System.exit(0); } }
This section includes information on the following:
The SMLogViewerTest dumps the syslog from the specified URL in the program and then it will go into sleep mode. During the sleeping time frame, if there is a wrong password supplied to the `su', the method logSearchResponse will be invoked from the server callback.
CODE EXAMPLE 18-10 SMLogViewerTest /* * @(#)SMLogViewerTest.java 1.2 99/09/15 * * Copyright (c) 09/15/99 Sun Microsystems, Inc. All Rights Reserved. */ import com.sun.symon.base.client.*; import com.sun.symon.base.client.log.*; /* The following class implements the SMLogViewerResponse interface to receive a callback from the SMLogViewerrequest.logSearch async. request method. */ public class SMLogViewerTest implements SMLogViewerResponse { public SMLogViewerTest( String server_name, int server_port, int agent_port, String user, String password ) throws Exception { try { String publicKey = "687a8398ad4a85077d33b72a94e16ffde0c4ba023e" + "9c9ba77b247cc25bd3cd0015bc24b7429916751e68" + "1fd02e5ad6eb5345eb7c75b39a1c304e0f000846aa" + "470b755b0640af974e7fc70daa6191dff6efa31a09" + "431bb5e9848b7dc4cf4b97e1dbca31792d2860ca5a" + "5990dfb369e1bcf296274a4e4984c8089329679dd3" + "04cd"; System.out.println("*** Testing Connection ****"); SMLogin obj = new SMLogin(); obj.connect(server_name, new Integer(server_port).intValue(), user, password, publicKey); System.out.println("Successfully Connected"); SMRawDataRequest req = obj.getRawDataRequest(); System.out.println("Successfully Authenticated"); System.out.println(" **Testing SMLogViewerTest **"); System.out.println(" **Testing logSearch**"); // The SMLogViewerRequest constructor creates a connection with the // backend logscanner process on an agent machine. SMLogViewerRequest lvreq = new SMLogViewerRequest(req, server_name, agent_port); // The following synchronous method returns matched lines for the // query. This query is set for Syslog file(s), a max. of 20 // matches are to be reported. The query is also set for the search // to begin from the latest message. The pattern to be matched is // server_name. Here the user can pass any regular expression // pattern. StringBuffer matchdata = lvreq.logSearch("Syslog", "", 20, 0, 0, 0, true, server_name, 0); if (matchdata == null) System.out.println("No match for the query"); else System.out.println("Match data: \n" + matchdata); // The following asynchronous method requests Syslog file(s) to be // searched for pattern server_name. This method also accepts the // SMLogViewerTest class object that has the callback method // logSearchResponse. This method will not block as the sync. // method above before returning the data. The last parameter // for this method could be used for corelating the request // response ids in case there are multiple async. logSearch requests. // The async. call is for getting incremental changes. // To cause something to change, try 'su' to root // with a wrong password. This should trigger the callback. System.out.println("**Testing logSearch Async. call**"); lvreq.logSearch("Syslog", "", null, this, new Object()); System.out.println("sleeping..."); System.out.println("Waiting for additions to Syslog."); System.out.println("Try 'su' to root with a wrong password."); Thread.sleep(120 *1000); } catch ( Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } public void logSearchResponse(SMRequestStatus status, StringBuffer data, Object identifier) { System.out.println("Async. data = " + data.toString()); } private static void usage() { System.out.println("usage: java SMLogViewerTest " + "server_name server_port agent_port name password"); } public static void main(String[] args) throws Exception { if ( args.length != 5) { usage(); System.exit(1); } else { new SMLogViewerTest (args[0], new Integer(args[1]).intValue(), new Integer(args[2]).intValue(), args[3], args[4]); System.exit(0); } } }
This section describes:
The SMResourceAccessTest demonstrates the retrieval of generic resources from the server. It will ask the server to verify the existence of the ConsoleMain.class and domain-config.x files, output the content of the file version-j.x and load the image file cpu16x16.gif.
CODE EXAMPLE 18-11 SMResrouceAccessTest /* * @(#)SMResourceAccessTest.java 1.1 99/09/13 * * Copyright (c) 09/13/99 Sun Microsystems, Inc. All Rights Reserved. */ import com.sun.symon.base.client.*; import java.awt.Image; public class SMResourceAccessTest { public SMResourceAccessTest( String server_name, int server_port, int agent_port, String user, String password ) throws Exception { try { String publicKey = "687a8398ad4a85077d33b72a94e16ffde0c4ba023e" + "9c9ba77b247cc25bd3cd0015bc24b7429916751e68" + "1fd02e5ad6eb5345eb7c75b39a1c304e0f000846aa" + "470b755b0640af974e7fc70daa6191dff6efa31a09" + "431bb5e9848b7dc4cf4b97e1dbca31792d2860ca5a" + "5990dfb369e1bcf296274a4e4984c8089329679dd3" + "04cd"; System.out.println("*** Testing Connect ****"); SMLogin obj = new SMLogin(); System.out.println("Before Connection Establishment"); obj.connect(server_name, server_port, user, password, publicKey); System.out.println("Successfully Connected and Authenticated"); SMRawDataRequest req = obj.getRawDataRequest(); // The SMResourceAccess class is used to retrieve generic // resources from the server. Currently only image data/text // files retrieval is supported. System.out.println("***Testing the SMResourceAccessRequest ***"); SMResourceAccess resacc = new SMResourceAccess(req); // The following method is used to verify the existence of the // file on the server. Depending on the URL scheme, the server // will use different paths to lookup for the presence of the file. // eg. for a file xfile:/domain-config.x the server will use // INTERFACE_PATH env. var. for a file // cfile:/com/sun/symon/base/console/main/ConsoleMain.class, // CLASSPATH var. is used. String file = "xfile:/domain-config.x"; if (resacc.fileExists(file)) System.out.println(file + " exists"); else System.out.println(file + " does not exist"); file = "cfile:/com/sun/symon/base/console/main/ConsoleMain.class"; if (resacc.fileExists(file)) System.out.println(file + " file exists"); else System.out.println(file + " file does not exist"); // The following method could be used to get a listing of all the // files in a particular directory. The directory path specified // in this call will be relative to the INTERFACE_PATH env. var. // in the server startup shell script. The following example will // get resolved under $ESROOT/classes/base/console/cfg dir. // This dir. is part of the INTERFACE_PATH env. var. String[] listfiles = null; listfiles = resacc.listFiles("stdimages"); if (listfiles != null) { for(int i=0; i < listfiles.length; i++) System.out.println("Filename = " + listfiles[i]); } else { System.out.println("Either directory is empty " + "or no files under the directory"); } // The following method could be used to read any config. file // from the server. The server will use the INTERFACE_PATH env. // var. to resolve the file. The pathname/filename should be // relative to the dirs. listed in the INTERFACE_PATH env. var. file = "version-j.x"; String filecontents = resacc.getConfigFile(file); System.out.println("Contents of the Config. file " + file + " = \n" + filecontents); // The following method could be used for reading an image file // from the server. The console applications can share such a // resouce loaded on the server. The pathname of the file is // resolved using the INTERFACE_PATH env. var. file = "stdimages/cpu16x16-j.gif"; Image img = resacc.getImage(file); if (img == null) System.out.println( file + " could not be loaded from the server"); else System.out.println(file + " was loaded"); } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); } } private static void usage() { System.out.println( "usage: java SMResourceAccessTest " + "server_name server_port agent_port user password"); } public static void main(String[] args) throws Exception { if ( args.length != 5) { usage(); System.exit(1); } else { new SMResourceAccessTest (args[0], new Integer(args[1]).intValue(), new Integer(args[2]).intValue(), args[3], args[4]); System.exit(0); } } }
This example demonstrates how to create a domain, how to show all domains created in the topology agent and how to get all children information under a domain.
SMTopologyTest
/* * @(#)SMTopologyTest.java 1.17 98/09/11 * * Copyright (c) 09/11/98 Sun Microsystems, Inc. All Rights Reserved. */ import java.io.InputStream; import java.io.InterruptedIOException; import java.io.OutputStream; import java.lang.String; import java.lang.System; import java.net.Socket; import java.util.StringTokenizer; import java.util.Vector; import com.sun.symon.base.client.*; import com.sun.symon.base.client.topology.*; /** * This class is for testing the Topology Client API. * It shows how to create an domain, how to get all domains created in the * topology agent and how to get children information under each domain. **/ public class SMTopologyTest { public SMTopologyTest(String serverHost, String serverPort, String userName, String passwd) throws Exception { try { String publicKey = "687a8398ad4a85077d33b72a94e16ffde0c4ba023e9c9ba77b247cc25bd3cd0015bc24b7429916751 e681fd02e5ad6eb5345eb7c75b39a1c304e0f000846aa470b755b0640af974e7fc70daa6191dff6efa 31a09431bb5e9848b7dc4cf4b97e1dbca31792d2860ca5a5990dfb369e1bcf296274a4e4984c808932 9679dd304cd"; System.out.println("*** Testing Connect establishment and Auth ****"); System.out.println("Before Connection Establishment"); SMLogin obj = new SMLogin(); obj.connect(serverHost, Integer.parseInt(serverPort), userName, passwd, publicKey); System.out.println("Successfully Authenticated"); SMRawDataRequest req = obj.getRawDataRequest(); SMUserDomainRequest domReq = new SMUserDomainRequest(req); System.out.println("******** Create a Domain *******"); String domName = "test_domain"; SMUserDomainData domDt = domReq.createDomain(domName); if ( domDt == null ) { System.out.println("Domain "+domName+" exists"); } else { System.out.println(domDt.getDomainName()+", URL="+ domDt.getDomainRootUrl()); } System.out.println("******** Get All Domains *******"); SMUserDomainData domData [] = domReq.getAllConfiguredDomains(); SMTopologyRequest topoReq = new SMTopologyRequest(req); SMTopologyEntityData topoData[] = null; SMTopologyEntityData data = null; int j=0; String name = null; String baseURL = null; String str = null; Vector dataV = null; String children [] = new String[2]; for ( int i=0; i<domData.length; i++ ) { name = domData[i].getDomainName(); baseURL = domData[i].getDomainRootUrl(); System.out.println("Domain: "+name+", URL="+ baseURL); topoData = topoReq.getTopologyInfo(baseURL, null); for ( j=0; j<topoData.length; j++ ) { data = topoData[j]; System.out.println("\t"+data.getDesc()+", "+ data.getPollType()); } } System.out.println("******** Get Children under the Domains *******"); for ( int i=0; i<domData.length; i++ ) { name = domData[i].getDomainName(); baseURL = domData[i].getDomainRootUrl(); topoReq.getHierarchyChildRequest(baseURL, "1000", true, new TopoHierTest(name), null); } }catch ( Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } // System.exit(-1); } public static void main(String[] args) throws Exception { if ( args.length != 4 ) { System.out.println("usage: java" + " SMTopologyTest server_name server_port user password."); System.exit(1); } else { new SMTopologyTest(args[0], args[1], args[2], args[3]); } } } class TopoHierTest implements SMHierarchyResponse { private String rootName; public TopoHierTest(String name) { rootName = name; } public void getHierarchyRootResponse(SMRequestStatus status, SMHierarchyViewData data, Object identifier) { if (status.getReturnCode() != SMErrorCode.SUCCESS) { System.out.println("Error getting hierarchy root " + status.getMessageText()); } else { System.out.println("Root data"); } } public void getHierarchyChildResponse(SMRequestStatus status, SMHierarchyViewData[] data, Object identifier) { if (status.getReturnCode() != SMErrorCode.SUCCESS) { System.out.println("Error getting hierarchy children " + status.getMessageText()); } else { System.out.println("Domain: "+ rootName); for ( int i=0; i<data.length; i++ ) { System.out.println("\t"+data[i].getName()+", "+ data[i].getTargetUrl()); } } }
Note - Exception classes do not need separate examples since they are covered within the context of the examples for each class or interface. These class and interface descriptions are presented in the javadocs included as part your install of the Sun Management Center Developer Environment.
Listed below are a few examples on how to run specific examples.
The SMAlarmAsyncTest demonstrates the usage of the client.alarm API to query the alarm information from the server. Notice the example is doing the request asynchronously. The program will go into a sleep mode for a certain period of time and then wake up to response the callback from the server.
runTest SMAlarmAsyncTest <server_name> <server_port> <agent_port> <user> <password>
SMAlarmSyncTest basically performs the same test as SMAlarmAsyncTest except that the program does not go into any sleep mode.
runTest SMAlarmSyncTest <server_name> <server_port> <agent_port> <user> <password>
The SMLogViewerTest dumps the syslog from the specified URL in the program and then it will go into sleep mode. During the sleeping time frame, if there is a wrong password supplied to the \Qsu', the method logSearchResponse will be invoked from the server callback.
runTest SMLogViewerTest <server_name> <server_port> <agent_port> <user> <password>
This example illustrates the usage of SMLogin class for connection establishment with the server. You must supply the correct arguments which are server name, server port, user name and user password in order to run the program. After running this program, once the process is started, the Client API has a live connection with the server and is ready for providing other data services.
runTest SMLoginTest <server_name> <server_port> <user> <password>
This is a class that uses the services of the SMRawDataRequest class in order to get data type dependent information. This class is used to programmatically query the schema of the properties defined in the agent. This example assumes that the kernel reader module is loaded on the Sun Management Center Agent on the server host and is currently enabled.
runTest SMManagedEntityTest <server_name> <server_port> <agent_port> <user> <password>
This example has the usage for SMRequestStatus class, which is used for reporting errors in asynchronous methods. The SMModuleTest demonstrates the dumping of modules information from the agents. In this example, the program will list modules and loaded modules, get the Health Monitor module's information as specified in the corresponding configuration file. It will also load, disable, enable, and unload the Health Monitor module. Finally, it demonstrates getting the module information in asynchronous mode.
runTest SMModuleTest <server_name> <server_port> <agent_port> <user> <password>
The SMProbeTest demonstrates that the console can perform an ad-hoc like query on the agent. This example assumes that the Mib2-Instrumentation module is loaded on the Sun Management Center Agent on the server host and is currently enabled. The example will either execute a 'netstat -i' or 'ifconfig -a', based on the selection in the example, and prints the output.
runTest SMProbeTest <server_name> <server_port> <agent_port> <user> <password>
The SMRawDataTest demonstrates the usage of methods from the class SMRawDataRequest. At the later part of the example, it will retrieve the CPU Idle time and the CPU User time from the kernel reader module. This example assumes that the kernel reader module is loaded on the Sun Management Center Agent on the server host and is currently enabled.
runTest SMRawDataTest <server_name> <server_port> <agent_port> <user> <password>
The SMRawDataAsyncTest is basically doing the same test as SMRawDataTest. This example makes use of an asynchrous request in a periodic cycle of 60 seconds. Every periodic time-out will cause the server to call back and the getURLresponse method will be invoked. This example assumes that the kernel reader module is loaded on the Sun Management Center Agent on the server host and is currently enabled.
runTest SMRawDataAsyncTest <server_name> <server_port> <agent_port> <user> <password>
The SMResourceAccessTest demonstrates the retrieval of generic resources from the server. It will ask the server to verify the existence of the ConsoleMain.class and domain-config.x files, output the content of the file version-j.x and load the image file cpu16x16.gif.
runTest SMResourceAccessTest <server_name> <server_port> <agent_port> <user> <password>
This example demonstrates how to create a domain, how to show all domains created in the topology agent and how to get all children information under a domain. The SMTopologyTest example loops waiting for topology events in Sun Management Center and needs to be explicitly stopped.
runTest SMTopologyTest <server_name> <server_port> <user> <password>