Cisco Systems Inc. Confidential

SM API version 5.1.0

 

See:
          Description

Packages
com.pcube.management.api  
com.pcube.management.framework.rpc  

 

 

Cisco SCMS SM Java API

Preface

The SCMS SM Java API Programmer Guide is used for updating, querying, and configuring the Subscriber Manager (SM). It consists of two parts, which may be used separately or together without limitation.

·      SM Non-blocking Java API: A high-performance API with low visibility to errors and other operation results. Supports automatic integrations with OSS/AAA systems.

·      SM Blocking Java API: A more user-friendly API. Supports user interface applications for accessing and managing the SM.

 

 

 

A set of APIs with exactly the same functionality is also available for the C/C++ environment.

 

Chapter 1 - Getting Started

This section describes the platforms on which the Java API can be used and how to install, compile, and start running the API.

Introduction

The Java API is used for updating, querying, and configuring the SCMS Subscriber Manager (SM). It consists of two parts, which can be used separately or together without restriction.

·      SM Non-blocking Java API—A high-performance API with low visibility to errors and other operation results. It supports automatic integrations with OSS/AAA systems.

·      SM Blocking Java API—A more user-friendly API. It supports user interface applications for accessing and managing the SM.

 

Platforms

The SM Java API was developed and tested on a Windows platform, but it is operable on any platform that supports Java version 1.4.

 

Installing the Java API

Extracting the Package

The Java API distribution is part of the SCMS SM-LEG distribution file and is located in the sm_api directory

The Java SM API is packaged in a UNIX tar file. You can extract the Java SM API using the UNIX tar utility or most Windows compression utilities.

To install the distribution on a UNIX platform:

 

Step 1    Extract the SCMS SM-LEG distribution file and locate the Java SM API distribution tar sm-java-api-dist.tar.

Step 2    Extract the Java SM API distribution tar and obtain the sm-java-api-vvv.bb.tar:

#> tar -xvf sm-java-api-dist.tar

Step 3    Extract the Java SM API package tar:

#> tar -xvf sm-java-api-vvv.bb.tar

 

To install the distribution on a Windows platform:

 

Use a zip extractor (such as WinZip).

 

 

The abbreviations vvv and bb stand for the Java SM API version and build number.

 

Package Content

For brevity, <installdir> refers to the installation directory sm-java-api-vvv.bb.

The <installdir>/javadoc folder contains the API JAVADOC documentation.

The <installdir>/lib folder contains the smapi.jar file, which is the API Executable. It also contains additional jar files necessary for the API operation.

 

Layout of Installation Directory

Path

Name

Description

<installdir>

 

 

 

README

API readme  file

<installdir>/Javadoc

 

 

 

index.html

Index of all API specifications

 

(API specification files, etc.)

API specification documents

<installdir>/Lib

 

 

 

smapi.jar

SM API executable

 

asn1rt.jar

Utility jar used by the API

 

jdmkrt.jar

Utility jar used by the API

 

log4j.jar

Utility jar used by the API

 

log4j.properties

Property file needed for the API logging functionalities

 

xerces.jar

Utility jar used by the API

 

jce-jdk13-133.jar

Utility jar used by the API

 

Compiling and Running

To compile and run a program that uses the SM Java API, smapi.jar must be in the CLASSPATH.

For example, if the program source is in SMApiProgram.java, use the following command line to compile the program:

 

#> javac -classpath smapi.jar SMApiProgram.java

After compiling the program, use the following command line to run the program:

 

#> java -cp .;<installdir>/lib/smapi.jar SMApiProgram

 

Subscriber Manager Setup

The API connects to the PRPC server on the SM. For the API to work:

·      The SM must be up and running, and reachable from the machine that hosts the API

·      The PRPC server must be started.

The PRPC server is a proprietary RPC protocol designed by Cisco. For more information about the PRPC server, see the SCMS Subscriber Manager User Guide.

 


Chapter 2 - General API Concepts

This section describes the various concepts that are used while working with the SM Java API.

 

Blocking API/Non-blocking API

This section describes the differences between the Blocking API and the Non-blocking API operations.

 

Blocking API

In a Blocking API operation, which is the most common, every method returns after its operation has been performed.

The SM Blocking Java API provides a wide range of operations. It contains most of the functionality of the Non-blocking API and many functions that the Non-blocking API does not provide. The Blocking API does not support reliability and auto-reconnect functionality.

 

Non-blocking API

In a Non-blocking Java API operation, every method returns immediately, even before the completion of its operation. The operation results are either returned to an Observer object (Listener) or not returned at all.

The Non-blocking API method is advantageous when the operation is lengthy and involves I/O. Performing the operation in a separate thread allows the calling program to continue doing other tasks and it improves overall system performance.

The SM Non-blocking Java API contains a small number of non-blocking operations. The API supports retrieval of operation results using a result listener.

The SM Non-blocking Java API supports two modes: reliable and non-reliable. For more information about the reliability modes, see Reliability Support (on page 4-1).

 

API Initialization

To initialize the API:

 

Step 1    Construct the API using one of its constructors.

Step 2    Perform the API-specific setup operations.

Step 3    Connect the API to the SM.

 

The following sections describe these three steps.

Initialization examples can be found within the code examples sections under each API.

 

API Construction

Blocking and Non-blocking APIs have two common constructors:

·      An empty constructor

·      A constructor that accepts a LEG name as a parameter

 

Constructor that Accepts a LEG Name

Set the LEG name if you intend to turn on the SM-LEG failure handling options in the SM. You should read about the LEG software components and SM-LEG failure handling in the Cisco SCMS Subscriber Manager User Guide.

The SM will use the LEG name when recovering from a connection failure. A constant string that identifies the API will be appended to the LEG name as follows:

·      For Blocking API: .B.SM-API.J

·      For Non-blocking API: .NB.SM-API.J

Example (Blocking API):

·      If the provided LEG name is my-leg.10.1.12.45-version-1.0, the actual LEG name will be my-leg.10.1.12.45-version-1.0.B.SM-API.J.

If no name is set, the LEG uses the hostname of the machine as the prefix of the name.

For additional information about LEG-SM failure handling, see Appendix A of the SCMS Subscriber Manager User Guide.

Additional constructors are available for the Non-blocking API. For more information, see Non-blocking API Construction (on page 4-5).

 

Setup Operations

The setup operations differ for the two APIs. Both APIs support setting a disconnect listener, described in detail in the DisconnectListener Interface (on page 2-7) section.

 

Blocking API Setup

To set up the Blocking API, you need to set an operation timeout value. For more information, see the Blocking API (on page 3-1) chapter.

 

Non-blocking API Setup

To set up the Non-blocking API you are required to set a disconnect listener. For more details, see the Non-blocking API (on page 4-1) chapter.

 

Connecting to the Subscriber Manager

To connect to the SM, use one of the following connect methods.

·      Use the following method to connect to the SM using the default RPC TCP port (14374):

 

connect(String host)

·      Use the following method to allow the caller to set the TCP port to which the API connects:

 

connect(String host, int port)

For both methods, the host parameter can be either an IP address or a reachable hostname.

At any time during the API operation, you can check if the API is connected by using the isConnected method.

 

API Finalization

To free the resources of both server and client, use the disconnect method.

It is recommended that you use a finally statement in your main class; for example:

 

public static void main(String [] args) throws Exception {

    SMNonBlockingApi smnbapi = new SMNonBlockingApi();

    try {

          …

    } finally {

          smnbapi.disconnect();

    }

}

 

Subscriber Name Format

Most methods of both APIs require the subscriber name as an input parameter. This section lists the formatting rules of a subscriber name.

The subscriber name is case-sensitive. It may contain up to 40 characters. You can use any of the following characters:

Alphanumerics

$ (dollar sign)

. (period or dot)

_ (underscore)

- (minus sign or hyphen)

% (percent sign)

/ (slash)

~ (tilde)

! (exclamation mark)

& (ampersand)

: (colon)

' (apostrophe)

# (number sign)

() (parentheses)

@ (at sign)

 

 

Network ID Mappings

A network ID mapping is a network identifier that the SCE device can relate to a specific subscriber record. A typical example of a network ID mapping (or simply mapping) is an IP address. Currently, the Cisco Service Control solution supports IP address, IP range, IPV6 address, IPV6 range and VLAN mappings.

Both Blocking and Non-blocking APIs contain operations that accept mappings as a parameter. Examples are:

·      the addSubscriber operation (Blocking API)

·      the login method (Blocking or Non-blocking API)

When passing mappings to an API method, the caller is requested to provide two parameters:

·      a java.lang.String mapping identifier or array of mapping types

·      a short mapping type or array of mapping types

When passing arrays, the mappingTypes array must contain either the same number of elements as the mappings array, or a single element. If the mappingTypes array contains a single element, all mappings have the same type, specified by this single element.

The API supports the following subscriber mapping types:

·      IP addresses or IP ranges

·      IPV6 addresses or IPV6 ranges

·      VLAN tags

For additional information, see the SCMS Subscriber Manager User Guide.

 

Specifying IP Address Mapping

The string format of an IP address is the commonly used decimal notation:

 

IP-Address=[0-255].[0-255].[0-255].[0-255].

Examples:

·      216.109.118.66

·      The mapping type of an IP address is provided in the interface com.pcube.management.api.SMApiConstants:

·     com.pcube.management.api.SMApiConstants.MAPPING_TYPE_IP specifies a single IP mapping that matches the mapping identifier with the same index in the mapping identifier array.

·     com.pcube.management.api.SMApiConstants.ALL_IP_MAPPINGS specifies that all the entries in the mapping identifiers array are IP mappings.

 

Specifying IP Range Mapping

The string format of an IP range is an IP address in decimal notation and a decimal specifying the number of 1s in a bit mask: IP-Range=[0-255].[0-255].[0-255].[0-255]/[0-32].

Examples:

·      10.1.1.10/32 is an IP range with a full mask, that is, a regular IP address.

·      10.1.1.0/24 is an IP range with a 24-bit mask, that is, all the addresses ranging between 10.1.1.0 and 10.1.1.255.

 

 The mapping type of an IP Range is identical to the mapping type of the IP address.

 

Specifying IPV6 Address or Range Mapping

The string format of an IPV6 address is the commonly used hexa colon notation:

 

IPV6-Address=[0000-FFFF]:[0000-FFFF]:[0000-FFFF]:[0000-FFFF]:[0000-FFFF]:[0000-FFFF]:[0000-FFFF]:[0000-FFFF]/[0-64].

Examples:

·      2001:db8:85a3::8a2e:370:7334/64 is an IPV6 range with a 64 bit mask, that is, a regular IPv6 address.

·      2001:db8:85a3::8a2e:370:7334/48 is an IPV6 range with a 48-bit mask, that is, all the addresses ranging between 2001:db8:85a3:0000:: and 2001:db8:85a3:ffff::.

 

 It is necessary for all the ipv6 address to posses a prefix value between 0 and 64. There is no default values as in ipv4 mappings(i.e mask bit 32 ).Only the first 64 bit of ipv6 address will be taken for evaluation.

 

Specifying VLAN Tag Mapping

The string format for VLAN tag mapping is VLAN-tag = 0-4095.

The value is a decimal in the specified range.

The com.pcube.management.api.SMApiConstants interface also provides the mapping type:

·      com.pcube.management.api.SMApiConstants.MAPPING_TYPE_VLAN specifies a single VLAN mapping that matches the mapping identifier with the same index in the mapping identifier array.

·      com.pcube.management.api.SMApiConstants.ALL_VLAN_MAPPINGS specifies that all the entries in the mapping identifiers array are VLAN mappings.

 

Subscriber Domains

The  Cisco SCMS Subscriber Manager User Guide explains in detail the domain concept. Briefly, a domain is an identifier that tells the SM which SCE devices to update with the subscriber record.

A domain name is of type String. During system installation, the network administration determines the system domain names, which therefore vary between installations. The APIs include methods that specify to which domain a subscriber belongs and allow queries about the system's domain names. If an API operation specifies a domain name that does not exist in the SM domain repository, it is considered an error and an RpcErrorException will be returned.

 

Subscriber Properties

Several operations manipulate subscriber properties. A subscriber property is a key-value pair that affects the way the SCE analyzes and reacts to network traffic generated by the subscriber.

More information about properties can be found in the Cisco SCMS Subscriber Manager User Guide and in the Cisco Service Control Application for Broadband User Guide. The application user guide provides application-specific information; it lists the subscriber properties that exist in the application running on your system, the allowed value set, and the significance of each property value.

To format subscriber properties for Java API operations, use the String arrays propertyKeys and propertyValues.

 

 

The arrays must be of the same length, and NULL entries are forbidden. Each key in the keys array has a matching entry in the values array; the value for propertyKeys[j] resides in propertyValues[j].The mapping type of an IP Range is identical to the mapping type of the IP address.

Example:

·      If the property keys array is {“name”,“color”,“shape”} and the property values array is {“john”,“red”,“circle”}, the properties will be name=john, color=red, shape=circle.

 

Custom Properties

Some operations manipulate custom properties. Custom properties are similar to subscriber properties, but do not affect how the SCE analyzes and manipulates the subscriber's traffic. The application management modules use custom properties to store additional information for each subscriber.

To format custom properties, use the String arrays customPropertyKeys and customPropertyValues, the same as in formatting Subscriber Properties (on page 2-6).

 

DisconnectListener Interface

Both APIs (Blocking and Non-blocking) allow setting a disconnect listener. The disconnect listener is an interface with a single method:

 

public interface DisconnectListener {

 

    /**

     * called when the connection with the server is down.

     */

    public void connectionIsDown();

}

Implement this interface to be notified when the API is disconnected from the SM.

To set a disconnect listener, use the setDisconnectListener method.

 

Example

The following example is a simple implementation of a disconnect listener that prints a message to stdout and exits.

 

import com.pcube.management.framework.rpc.DisconnectListener;

 

public class MyDisconnectListener implements DisconnectListener {

 

    public void connectionIsDown(){

          System.out.println(“Message: connection is down.”);

          System.exit(0);

    }

}

 

Exceptions

The same Java class, com.pcube.management.framework.rpc.RpcErrorException, provides all of the functional errors of the SM Java API. This is contrary to the normal Java usage. This approach was chosen because of the “cross-language” nature of the SM API. It allows all SM API implementations (Java, C, and C++) to look and feel the same.

Each exception provides the following information:

·      A unique error code (long)

·      An informative message (java.lang.String)

·      A server-side stack trace (java.lang.String)

The error code can be interpreted using com.pcube.management.api.SMApiConstants. See the List of Error Codes (on page A-1) for more details about error codes and their significance.

 

 

Several types of errors can occur only when the Blocking API is used. These are operational errors related to operation-timeout handling. They are described in detail in the Blocking API (on page 3-1) chapter.

 

Practical Tips

When implementing the code that integrates the API with your application, you should consider the following practical tips:

·      Connect to the SM once and maintain an open API connection to the SM at all times, using the API many times. Establishing a connection is a timely procedure, which allocates resources on the SM side and the API client side.

·      Share the API connection between your threads. It is better to have one connection per LEG. Multiple connections require more resources on the SM and client side.

·      Do not implement synchronization of the calls to the API. The client automatically synchronizes calls to the API.

·      It is recommended to place the API clients (LEGs) in the same order of the SM machine processor number.

·      If the LEG application has bursts of logon operations, enlarge the internal buffer size accordingly to hold these bursts (Non-Blocking flavor).

·      During the integration, set the SM logon_logging_enabled configuration parameter to view the API operations in the SM log to troubleshoot the integration, if any problems arise.

·      Use the debug mode for the LEG application that logs/prints the return values of the non-blocking operations.

·      Use the automatic reconnect feature to improve the resiliency of the connection to the SM.

·      In cluster setups, connect the API using the virtual IP address of the cluster and not the management IP address of one of the machines.


Chapter 3 - Blocking API

This chapter introduces the Reply Timeout, a feature unique to the Blocking API. The rest of the chapter lists all operations of the Blocking API, and provides code examples.

 

 

If you only need to develop an automatic integration, skip this chapter and go directly to the Non-blocking API (on page 4-1) chapter.

 

 

Multi-threading Support

The Blocking API supports unlimited number of threads calling its methods simultaneously.

 

 

In a multi-threaded scenario for the Blocking API, the order of invocation is not guaranteed.

Example:

Thread‑0 calls operation‑0 at time‑0, and thread‑1 calls operation‑1 at time‑1, where time‑1 is later than time‑0. In this example, it is possible that operation‑1 may be performed before operation‑0, as shown in the following diagram (the vertical scale is time):

Thread 0              Thread 1                  SM Blocking API

     |                   |         operation 0       |

     |==============================================>|

     |                   |         operation 1       |

     |                   |==========================>|

     |                   |         result 1          |

     |                   |<==========================|

     |                   |         result 0          |

     |<==============================================|

     |                   |                           |

 

The SM allocates five threads to handle each API instance. It is recommended to develop a multi-threaded application that uses the API with a number of threads in the order of the five threads. Implementing with more threads might result in longer delays for the calling threads.

 

ReplyTimeout and OperationTimeout Exception

A blocking operation returns only when the operation result has been retrieved from the SM. If a networking malfunction or other error prevents the operation result from being retrieved, the caller will wait indefinitely. The SM API provides means of working around this situation.

The reply timeout feature (the setReplyTimeout method) lets the caller set a timeout. It will fire a com.pcube.management.framework.rpc.OperationTimeoutException when a reply does not return within the timeout period.

Calling the setReplyTimeout method with a long value sets a reply timeout. The reply timeout is interpreted in milliseconds. A zero value indicates that the operation should wait (freeze, hang) until a result arrives - or indefinitely, if no result arrives.

There is an alternate way of releasing a method call that is blocking the caller, who is waiting for a result to arrive: Call the interrupt method of the calling thread: a java.lang.InterruptedException will then be returned to the caller.

 

Blocking API Code Examples

This section gives two code examples:

·      Getting number of subscribers

·      Adding subscriber, printing subscriber information, removing subscriber

 

Getting Number of Subscribers

The following example prints to stdout the total number of subscribers in the SM database and the number of subscribers in each subscriber domain.

 

 

package blocking;

 

import com.pcube.management.api.SMBlockingApi;

 

public class PrintInfo {

    public static void main (String args[]) throws Exception {

        SMBlockingApi bapi = new SMBlockingApi();

        try {

            //initiation

            bapi.setReplyTimeout(300000);  //set timeout for 5 minutes

            bapi.connect(args[0]);         // connect to the SM

 

            //operations

            String[] domains=bapi.getDomains();

            int totalSubscribers=bapi.getNumberOfSubscribers();

            System.out.println(

                "number of susbcribers in the database:\t\t "+

                totalSubscribers);

            for (int i=0; i<domains.length; i++) {

                int numberOfSusbcribersInDomain=

                    bapi.getNumberOfSubscribersInDomain(domains[i]);

                System.out.println(

                    "number of susbcribers domain "+domains[i]+

                    ":\t\t "+numberOfSusbcribersInDomain);

            }

        } finally {

            //finalization

            bapi.disconnect();

        }

    }

}

Adding a Subscriber, Printing Information, and Removing a Subscriber

The following program adds a subscriber to the subscriber database, then gets its information and prints it to stdout, and finally removes the subscriber from the subscriber database.

 

package blocking;

 

import com.pcube.management.api.SMBlockingApi;

import com.pcube.management.api.SMApiConstants;

 

public class AddPrintRemove {

    public static void main (String args[]) throws Exception {

        checkArguments(args);

        SMBlockingApi bapi = new SMBlockingApi();

        try {

            //initiation

            bapi.setReplyTimeout(10000);   //set timeout for 10 seconds

            bapi.connect(args[0]);         // connect to the SM

            //add subscriber

            System.out.println("+ adding subscriber to SM");

            bapi.addSubscriber(

                args[1],   //name

                new String[]{args[2]},   //mapping`

                SMApiConstants.ALL_IP_MAPPINGS,

                new String[]{args[3]}, //property key

                new String[]{args[4]}, //property value

                new String[]{"custom-key"}, //custom property key

                new String[]{"custom-value"}, //custom property value

                args[5]);              //domain

            //Print subscriber

            System.out.println("+ Printing subscriber");

            Object[] subfields = bapi.getSubscriber(args[1]);

            System.out.println("\tname:\t\t"+subfields[0]);

            System.out.println("\tmapping:\t"+

                               ((String[])subfields[1])[0]);

            System.out.println("\tdomain:\t\t"+subfields[3]);

            System.out.println("\tautologout:\t"+subfields[8]);

            //Remove subscriber

            System.out.println("+ removing subscriber from SM");

            bapi.removeSubscriber(args[1]);

        } finally {

            //finalization

            bapi.disconnect();

        }

    }

 

    static void checkArguments(String[] args)  throws Exception{

        if (args.length != 6) {

            System.err.println(

                "usage: java AddPrintRemove <SM-address>"+

                " <subscriber-name> <IP mapping> <property-key>"+

                " <property-value> <domain>");

            System.exit(1);

        }

    }

}

 


Chapter 4 - Non-blocking API

This chapter introduces features unique to the Non-blocking API. It lists all methods of the Non-blocking API and ends with code examples.

 

Reliability Support

The Non-blocking API can work in two different modes, reliable and non-reliable, as described below. When the mode is not specified, the default is reliable mode.

 

Reliable Mode

In reliable mode, the API ensures that no requests to the SM are lost. The API maintains an internal storage for all API requests that are sent to the SM. After a reply from the SM is received, the request is considered committed and the API can remove the request from its internal storage. In case of connection failure between the API and the SM, the API accumulates all requests in its internal storage until the connection to the SM is established. On reconnection, the API resends all non-committed requests to the SM, so that no requests are lost.

 

 

In reliable mode, the order of resending requests is guaranteed. The API resends the requests in the same chronological order that they were called.

 

Non-reliable Mode

In non-reliable mode, the API does not ensure that requests sent to the SM are executed. In addition, all requests that are sent by the API when the connection to the SM is down will be lost unless an external reliability mechanism is implemented.

 

Auto-reconnect Support

The Non-blocking API supports auto-reconnection to the SM in case of connection failure. When this option is activated, the API can determine when the connection to the SM is lost. When the connection is lost, the API activates a reconnection task that tries to reconnect to the SM until it is successful.

 

The auto-reconnect support option can be activated regardless of the reliability mode.

 

Multi-threading Support

The Non-blocking API supports an unlimited number of threads calling its methods simultaneously.

 

 

In a multi-threaded scenario for the Non-blocking API, the order of invocation is guaranteed. The API performs operations in the same chronological order that they were called.

 

ResultHandler Interface

The Non-blocking API enables setting a result handler. A result handler is an interface with two methods, handleSuccess and handleError, as outlined in the following code:

 

public interface ResultHandler {

 

    /**

     * handle a successful result

     */

    public void handleSuccess(long handle, Object result);

 

    /**

     * handle a failure result

     */

    public void handleError(long handle, Object result);

}

You should implement this interface if you want to be informed about the success/error results of operations performed through the API.

 

 

This is the only interface for retrieving results; they cannot be returned immediately after the API method has returned to the caller.

In order to be able to receive operation results, you should set the result handler of the API before calling API methods whose results you want to receive. It is a good practice to set the result handler after the API is connected (as in the example below).

Both handleSuccess and handleError methods accept two parameters:

·      Handle—Each API operation's return-value is a handle of type long. This handle enables correlation between operation calls and their results. When a handle... operation is called with a handle of value X, the result will match the operation that returned the same handle value (X) to the caller.

·      Result—The actual result of the operation. Some operations may return a result of NULL.

 

Example

The following example is a simple implementation of a result handler that prints a message to stdout (when the result is successful) or to stderr (when the result is failure). This main method initiates the API and assigns a result handler.

For correct operation of the result handler, follow the code sequence given in this example.

 

 

This example does not demonstrate the use of callback handles.

 

 

import com.pcube.management.framework.rpc.ResultHandler;
import com.pcube.management.api.SMNonBlockingApi;

 

 

public class ResultHandlerExample implements ResultHandler{

 

    public void handleSuccess(long handle, Object result) {

        System.out.println("success: handle="+handle+", result="+result);

    }

 

    public void handleError(long handle, Object result) {

        System.err.println("error: handle="+handle+", result="+result);

    }

 

    public static void main (String args[]) throws Exception{

        if (args.length != 1) {

            System.err.println("usage: ResultHandlerExample <sm-ip>");

            System.exit(1);

        }

 

        //note the order of operations!

        SMNonBlockingApi nbapi = new SMNonBlockingApi();

        nbapi.connect(args[0]);

        nbapi.setResultHandler(new ResultHandlerExample());

        nbapi.login(...);

    }

}

 

 

Non-blocking API Construction

In addition to the constructors described in API Construction (on page 2-2), the Non-blocking API provides constructors that enable setting the reconnect period and the reliability mode.

Syntax

The syntax for the additional Non-blocking API constructors is shown in the following code block:

 

public SMNonBlockingApi(long autoReconnectInterval)

 

public SMNonBlockingApi(boolean reliable, long autoReconnectInterval)

 

public SMNonBlockingApi(String legName, long autoReconnectInterval)

 

public SMNonBlockingApi(String legName,
     boolean reliable, long autoReconnectInterval)

 

Arguments

The following is a description of the constructor arguments for the additional Non-blocking API constructors:

·      autoReconnectInterval

Defines the interval (in milliseconds) for attempting reconnection by the reconnection task, as follows:

·     If the value is 0 or less, the reconnection task is not activated (no auto-reconnect is attempted).

·     If the value is greater than 0 and if there is a connection failure, the reconnection task will be activated every autoReconnectInterval milliseconds.

The default value is -1 (no auto-reconnect is attempted).

 

 

To enable the auto-reconnect support, the connect method of the API must be activated at least once. For more information see, Non-blocking API Code Examples (on page 4-10).

·      reliable

A flag that defines whether the API should work in reliable mode, as follows:

·     TRUE—The API works in reliable mode.

·     FALSE—The API works in non-reliable mode.

The default value is TRUE (the API works in reliable mode).

·      legName

The name of the LEG, as described in  API Construction (on page 2-2).

 

Examples

The following code constructs a reliable API with an auto-reconnection interval of 10 seconds:

 

SMNonBlockingAPI nbapi = SMNonBlockingAPI(10000);

nbapi.connect(<SM IP address>);

The following code constructs a reliable API without auto-reconnection support:

 

// API construction

SMNonBlockingAPI nbapi = SMNonBlockingAPI();

 

// Connect to the API

nbapi.connect(<SM IP address>);

The following code constructs a non-reliable API with auto-reconnection support:

 

// API construction

SMNonBlockingAPI nbapi = SMNonBlockingAPI(false,10000);

 

// Initial connection - to enable the reconnect task

nbapi.connect(<SM IP address>);

 

Non-blocking API Initialization

The Non-blocking API enables initializing certain internal properties for API customization. This initialization is performed using the API init method.

 

 

For the settings to take effect, the init method must be called before the connect method.

The following properties can be set:

·      Output queue size—The internal buffer size defining the maximum number of requests that can be accumulated by the API until they are sent to the SM. The default is 1024.

·      Operation timeout—The desired timeout (in milliseconds) on a non-responding PRPC protocol connection. The default is 45 seconds.

 

Syntax

The syntax for the Non-blocking API init method is as follows:

 

public void init(Properties properties)

 

Parameters

The following is a description of the parameters for the Non-blocking API init method:

·      properties (java.util.Properties)

Enables setting the following properties described above:

·     To set the output queue size, use prpc.client.output.machinemode.recordnum

·     To set the operation timeout, use prpc.client.operation.timeout

 

Example

The following code illustrates how to customize properties during initialization when using the Non-blocking API. Note that the init method is called before the connect method.

 

// API construction

SMNonBlockingAPI nbapi = SMNonBlockingAPI(10000);

 

// API initialization

java.util.Properties p = new java.util.Properties();

p.setProperty(“prpc.client.output.machinemode.recordnum”, 2048);

p.setProperty(“prpc.client.operation.timeout”, 60000);       // 1 minute

nbapi.init(p);

 

// initial connect to the API to enable the reconnect task

nbapi.connect(<SM API address>);

 

Non-blocking API Code Examples

This section illustrates a code example for logging in and logging out subscribers.

 

Login and Logout

The following example logs in a predefined number of subscribers to the SM and then logs them out. Note the implementation of a disconnect listener and a result handler.

 

package nonblocking;

 

import com.pcube.management.framework.rpc.DisconnectListener;

import com.pcube.management.framework.rpc.ResultHandler;

import com.pcube.management.api.SMNonBlockingApi;

import com.pcube.management.api.SMApiConstants;

 

class LoginLogoutDisconnectListener implements  DisconnectListener {

    public void connectionIsDown() {

        System.err.println("disconnect listener:: connection is down");

    }

}

 

class LoginLogoutResultHandler implements ResultHandler {

    int count = 0;

  

    //prints a success result every 100 results

    public synchronized void handleSuccess(long handle, Object result) {

        Object tmp = null;

        if (++count%100 == 0) {

            tmp = result instanceof Object[] ?

                ((Object[])result)[0] : result;

            System.out.println("\tresult "+count+":\t"+tmp);

        }

 

    }

    //prints every error that occurs

    public synchronized void handleError(long handle, Object result) {

        System.err.println("\terror: "+count+":\t"+ result);

        ++count;

    }

  

    //waits for result number 'last result' to arrive

    public synchronized void waitForLastResult(int lastResult) {

        while (count<lastResult) {

            try {

                wait(100);

            } catch (InterruptedException ie) {

                ie.printStackTrace();

            }

        }

    }

}

 

public class LoginLogout {

    public static void main (String args[]) throws Exception{

        //check arguments

        checkArguments(args);

        int numSubscribersToLogin = Integer.parseInt(args[2]);

 

        //instantiation

        SMNonBlockingApi nbapi = new SMNonBlockingApi();

        try {

            //initation

            nbapi.setDisconnectListener(

                new LoginLogoutDisconnectListener());

            nbapi.connect(args[0]);

            LoginLogoutResultHandler resultHandler =

            new LoginLogoutResultHandler();

            nbapi.setResultHandler(resultHandler);

            //login

            System.out.println("login of "+numSubscribersToLogin

                               +" subscribers");

            for (int i=0; i<numSubscribersToLogin; i++) {

                nbapi.login("subscriber"+i,    //subscriber name

                            getMappings(i),    //a single ip mapping

                            new short[]{  

                                SMApiConstants.MAPPING_TYPE_IP

                            },

                            null,          //no properties

                            null,       

                            args[1],       //domain

                            false,         //mappings are not additive

                            -1);           //disable auto-logout

            }

            resultHandler.waitForLastResult(numSubscribersToLogin);

            //logout

            System.out.println("logout of "+numSubscribersToLogin

                               +" subscribers");

            for (int i=0; i<numSubscribersToLogin; i++) {

                nbapi.logoutByMapping(getMappings(i)[0],

                                      SMApiConstants.MAPPING_TYPE_IP,

                                      args[1]);

            }

            resultHandler.waitForLastResult(numSubscribersToLogin*2);

        } finally {

            nbapi.disconnect();

        }

    }

    static void checkArguments(String[] args)  throws Exception{

        if (args.length != 3) {

            System.err.println("usage: java LoginLogout "+

                               "<SM-address> <domain> <num-susbcribers>");

            System.exit(1);

        }

    }

    //'automatic' mapping generator

    private static String[] getMappings(int i) {

        return new String[]{ "10." +((int)i/65536)%256 + "." +

            ((int)(i/256))%256 + "." + (i%256)};

    }

}

 


Error codes are used for interpreting the actual error for which an RpcErrorException was returned. Use the getErrorCode method to extract the error code.

The error code enumeration is given in the com.pcube.management.api.SMApiConstants interface. The following tables gives a list of the error codes and their descriptions.

Table ‑1      List of Error Codes

Error Code

Description

ERROR_CODE_BAD_SUBSCRIBER_MAPPING

A mapping was formatted badly or assigned to the subscriber illegally.

ERROR_CODE_DOMAIN_NOT_FOUND

The domain provided to the operation does not exist in the SM domain repository.

ERROR_CODE_ILLEGAL_ARGUMENT

One of the arguments provided to the method is illegal.

ERROR_CODE_ILLEGAL_SUBSCRIBER_NAME

The subscriber name provided has more than 40 characters or has illegal characters.

ERROR_CODE_NOT_A_SUSBCRIBER_DOMAIN

The domain provided to the operation exists in the SM domain repository but is not a subscriber domain.

ERROR_CODE_NUMBER_FORMAT

A VLAN mapping string provided to the API does not represent a decimal number.

ERROR_CODE_SUBSCRIBER_DOES_NOT_EXIST

The subscriber on which the operation is performed does not exist in the SM database.

ERROR_CODE_SUBSCRIBER_DOMAIN_ASSOCIATION

The subscriber exists in the SM database but is associated with a domain other than the one specified by the operation.

ERROR_CODE_SUBSCRIBER_MAPPING_CONGESTION

The mappings provided for the subscriber by the operation already belong to another subscriber.

ERROR_CODE_SUSBSCRIBER_ALREADY_EXISTS

The subscriber on which the operation was performed already exists in the SM database.

ERROR_CODE_DATABASE_EXCEPTION

Internal SM error – database error occurred during the operation.

ERROR_CODE_ARRAY_ACCESS

Internal SM error.

ERROR_CODE_ATTRIBUTE_NOT_FOUND

Internal SM error.

ERROR_CODE_CLASS_CAST

Internal SM error.

ERROR_CODE_CLASS_NOT_FOUND

Internal SM error.

ERROR_CODE_CLIENT_INTERNAL_ERROR

Internal error.

ERROR_CODE_CLIENT_OUT_OF_THREADS

Internal error.

ERROR_CODE_ILLEGAL_STATE

Internal SM error.

ERROR_CODE_OBJECT_NOT_FOUND

Internal SM error.

ERROR_CODE_OPERATION_NOT_FOUND

Internal SM error.

ERROR_CODE_OUT_OF_MEMORY

Internal SM error.

ERROR_CODE_RUNTIME

Internal SM error.

ERROR_CODE_NULL_POINTER

Internal SM error.

ERROR_CODE_SE_ERROR

Internal SM error. The SM could not perform the operation on the SCE device.

ERROR_CODE_UNKNOWN

Internal SM or API error.


 

 

 


Cisco Systems Inc. Confidential