SIP Service Engine© Documentations
 
  Top >   SIP Servlet Programming >    Basic Components >   Utilities
 
 

Utilities

Utilities provide various functions such as Digest authentication and provided as a package.

The utilities consist of the following classes:

Digest Authentication

AuthHeaderManager Class

This class is used to generate a Digest authentication header and manage the nOnce (challenge). You can use this class to create and check the header and nOnce.

package com.oki.sip.equips.util;

public class AuthHeaderManager {

    protected AuthHeaderManager();

    protected AuthHeaderManager(long validity);

    protected AuthHeaderManager(int times);

    protected AuthHeaderManager(long validity, int times);

    public String createHeader(String realm, String qop, String seed);

    public String createNonce(String seed);

    public boolean checkHeader(String header,
                               String entityBody, 
                               String storedHA1,
                               String method);

    public boolean checkNonce(String nonce);

    public String getUsername(String header);

    public void setValidity(long validity);

    public void setAvailableTimes(int times);

    public synchronized void startTimer();

    public synchronized void stopTimer();
}

Each constructor creates an AuthHeaderManager object with information set in arguments. You do not need to directly call the constructor. Use a getAuthHeaderManager method of the AuthheaderUtils class to generate the AuthHeaderManager object.

The createHeader and createNonce methods generate a WWW-Authenticate header/nOnce based on values specified in the arguments.

checkHeader, checkNonce methods check whether a WWW-Authenticate header/nOnce is valid. If valid, they return true. Otherwise, return false. In checkHeader, header specifies a target header, entityBody specifies an entity body (if qop is auth-int), storedHA1 specifies HA1 used for checking, and method specifies a method name. In checkNonce, nonce specifies a target nOnce.

The getUsername method gets the name of a subscriber from a WWW-Authenticate header.

The setValidity method sets the expiration time of nOnce. validity specifies the expiration time in seconds.

The setAvailableTimes method sets the allowable number of times the client sends nOnce.

The startTimer and stopTimer methods start and stop a thread that checks the expiration time of nOnce or whether nOnce is valid if the allowable number of times is set. When the setValidity and setAvailableTimes methods are invoked, startTimer is automatically started to check if nOnce is valid.

AuthHeaderUtils Class

AuthHeaderUtils is a utility class for a Digest authentication header. It defines static methods including Digest calculation.

package com.oki.sip.equips.util;
 
public class AuthHeaderUtils {

    public static final String DEFAULT_MANAGER;
    public static Map map;

    public static AuthHeaderManager getAuthHeaderManager();

    public static AuthHeaderManager getAuthHeaderManager(String name);

    public static String getHA1(String username, String realm, String passwd);

    public static String getDigest(String ha1,
                                   String nonce,
                                   String nonceCount,
                                   String clientNonce,
                                   String qop,
                                   String method,
                                   String digestUri,
                                   String entityBody);
}

getAuthHeaderManager method gets AuthHeaderManager. getAuthHeaderManager without an argument retrieves the common AuthHeaderManager in the JavaVM. getAuthHeaderManager with an argument sets the name and retrieves the AuthHeaderManager. This AuthHeaderManager is associated with this name and stored in map.

The getHA1 method returns a hash string defined in RFC2617. You must specify a user name, realm, and password.

The getDigest method calculates an HTTP digest. The following arguments must be specified:

Argument Name Description
ha1 An HA1 string.
nonce nOnce generated on the server.
nonceCount The number of times nOnce is sent (the number of times a response is calculated).
clientNonce nOnce of the client.
qop Quality of Protection. Specify auth, auth-int, or null (no authentication).
method The method name (get, etc.).
digestUri A URI string.
entityBody An entity body. Use this if auth-int is specified.

JMS

JmsPublisher Class

JmsPublisher is a utility class to register a Topic with JMS. You can register a message by specifying the JNDI name of ConnectionFactory and a target Topic name.

package com.oki.sip.equips.util;
  
public class JmsPublisher {
    public JmsPublisher(String factoryName,
			String topicName) throws NamingException;

    public void openConnection() throws JMSException;

    public void sendMessage(Message message) throws JMSException;

    public void sendText(String text) throws JMSException;

    public void sendObject(Serializable obj) throws JMSException;

    public void close();
}

Use information specified in the constructor to send a message to JMS. factoryName is the JNDI name of ConnectionFactory. topicName is the JMS topic name with which the message is registered.

openConnection() initiates a connection to JMS. This method must be invoked before the message is sent.

sendMessage() sends javax.jms.Message to the specified JMS topic.

sendText() sends the specified string to the specified JMS topic name.

sendObject() sends the specified serializable object to the specified JMS topic name.

close closes the connection to JMS. This method must be invoked when the message transmission is completed.

Linkage Provided by Load Balancer

Linkage Provided by Load Balancer provides a function to generate and set a cookie for a load balancer such as BIG-IP. If you build a system that contains multiple SIP Servlet Engines, you should introduce a networking device such as a load balancer to deliver HTTP requests. This utility class is used to make settings required to maintain HTTP sessions in this network configuration.

LoadBalancerFilter Class

LoadBalancerFilter is a utility class to set a cookie generated by LoadBalancerUtils in an HTTP response. This class is implemented as a servlet filter so that you can use it by adding settings in the deployment descriptor (web.xml) when deploying your application. You can set lbEnabled as an initialization parameter in LoadBalancerFilter. If you specify a value other than true, this filter will be invalid and can not set a cookie.

This filter sets a cookie when:

  • A cookie named APSRVID is not in the HTTP request.
  • APSRVID is in the request but does not indicate its host.

An example of web.xml with LoadBalancerFilter settings is shown below:

<web-app>

  ...

  <filter>
    <filter-name>lbFilter</filter-name>
    <filter-class>com.oki.sip.equips.util.LoadBalancerFilter</filter-class>
    <init-param>
      <param-name>lbEnable</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>

  ...

  <filter-mapping>
    <filter-name>lbFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  ...

</web-app>

LoadBalancerUtils Class

The LoadBalancerUtils class generates a cookie used by the load balancer to identify the destination server. Its APIs are as follows:

package com.oki.sip.equips.util;
 
public class LoadBalancerUtils {

    public static String getCookieName();

    public static String getCookieValue();

    public static Cookie getLBCookie();
}

The getCookieName method gets a string used as the cookie name. It returns the fixed value APSRVID.

getCookieValue method gets a string used as the cookie value. It returns the fixed value for each host. This value is generated from an IP address (a, b, c, d) according to the following rule.

Cookie value = d * 256<sup>3</sup> + c * 256<sup>2</sup> + b * 256 + a

For example, the cookie value for the host running at the address 10.2.0.15 will be:

15 * 256<sup>3</sup> + 0 * 256<sup>2</sup> + 2 * 256 + 10 = 167,772,682

under the above rule.

The getLBCookie method returns a Cookie object that stores the cookie name and value.

Web Application

BasicSipAction Class

BasicSipAction is a utility class to supports Struts. In Struts, application logic is implemented by implementing a class that inherits Action. Normally, SIP basic components including the location management is used within this application logic. CenterStage-AP provides a class (BasicSipAction) that contains methods to use basic components. BasicSipAction is implemented as shown below:

APIs of the BasicSipAction class are shown below. An Application developer can use this class to simplify access to basic components when Struts is used for a Web interface.

package com.oki.sip.equips.util;

abstract public class BasicSipAction extends Action {

    abstract public ActionForward execute(ActionMapping mapping,
                                          ActionForm form,
                                          HttpServletRequest request,
                                          HttpServletResponse response) 
        throws Exception;

    protected SipFactory getSipFactory(ServletContext context);

    protected SipURI createSipURI(ServletContext context, String user, String host);

    protected URI createURI(ServletContext context, String uri) throws ServletParseException;


    protected SubscriberEditor getSubscriberEditor();

    protected LocationEditor getLocationEditor();

    protected PresenceACLEditor getPresenceACLEditor();
    protected RoleEditor getRoleEditor();
}

All methods defined by BasciSipAction take ServletContext as the first argument. This object can be extracted from an HTTP request as shown below:

HttpSession session = request.getSession();
ServletContext context = session.getServletContext();

getSipFactory is a method that returns the SIP factory stored in the attribute of the servlet context.

createSipURI and createURI are methods that are from SipFactory and likely to be used by a Web application. These methods behave as if they are invoked from the return value of getSipFactory.

getLocationEditor, getSubscriberEditor, getPresenceACLEditor, and getRoleEditor are methods that return the corresponding basic components.

InitializerPlugin Class

This is a plug-in used to initialize a Web application in Struts. It calls InputCheck.setHostnameReqexp() and InputCheck.setUsernameRegExp() to define regular expression for checking the watcher string in the presence management component. It also stores SipFactory used via Web in a servlet context.

Here is an example settings in struts-config.xml:

        ....

<plug-in className="com.oki.sip.equips.util.InitializerPlugIn">

               <set-property property="regexp.hostname"
                             value="^[a-zA-Z0-9.]*$"/>
               <set-property property="regexp.username"
                             value="^[a-zA-Z0-9.]{3,16}$"/>

</plug-in>

        ....

InputCheck Class

InputCheck is a utility class to check arguments of the String type on basic components. Regular expression can be used to check a string. For regular expression, see "java.util.regex.Pattern Class."

package com.oki.sip.equips.util;

public class InputCheck {

    public static boolean isUsername(String username);

    public static boolean isHostname(String hostname);

    public static boolean isWatcher(String watcher);

    public static boolean isMatch(String regExp, String val);
    public static boolean isMatch(String regExp, String val, boolean isCompile);

    public static void setHostnameRegExp(String regExp);

    public static void setUsernameRegExp(String regExp);
}

isUsername, isHostname, and isWatcher are methods that check whether the SIP URI's subscriber part, host name part, and the watcher string in the presence management is valid respectively. It returns true if the string is valid. Otherwise, it returns false.

isMatch is a method that checks a string using the specified regular expression. When you compile regular expression, use the isMatch method with three arguments and specify true in the third argument isCompile.

setUsernameRegExp and setHostnameRegExp are methods that set regular expression to check the SIP URI's subscriber part and host name part with the isUsername and isHostname methods. When isUsername and isHostname are used without invoking these methods, the default regular expression is used for evaluation.

Others

SdpMessage Class

SdpMessage is a utility class for handling SDP (Session Description Protocol) defined in RFC2327. Note that this class does not fully support RFC2327, but supports only the required functions needed in SIP.

The basic syntax rule of SDP is:

Session description

v=  <protocol version>
o=  <username> <session id> <version> <network type> <address type> <address>
s=  <session name>
i=+ <session description>
u=* <URI>
e=* <email address>
p=* <phone number>
c=+ <network type> <address type> <connection address>
b=* <modifier>:<bandwidth-value>
One or more time descriptions (see below)
z=* <adjustment time> <offset> <adjustment time> <offset> ....
k=+ <method>[:<encryption key>]
a=* <attribute>[:<value>]
Zero or more media descriptions (see below)

Time description

t=  <start time> <stop time>
r=* <repeat interval> <active duration> <list of offsets from start-time>

Media description

m=  <media> <port> <transport> <fmt list>
i=+ <media description>
c=+ <network type> <address type> <connection address>
b=* <modifier>:<bandwidth-value>
k=+ <method>[:<encryption key>]
a=* <attribute>[:<value>]

=* indicates zero or more occurrence, =+ indicates zero or one occurrence.

Here is an example of the SDP message used in OKI Softphone.

v=0
o=- 1 1 IN IP4 172.21.164.248
s=-
c=IN IP4 172.21.164.248
t=0 0
m=audio 5004 RTP/AVP 0 8
c=IN IP4 172.21.164.248
a=rtpmap:0 PCMU/8000
a=rtpmap:8 PCMA/8000
m=video 35004 RTP/AVP 34
c=IN IP4 172.21.164.248
a=sendrecv
a=rtpmap:34 H263/90000
m=application 10000 tcp ec
c=IN IP4 172.21.164.248

The following example shows parsing the SDP message using the SdpMessage class.

   protected void doInvite(SipServletRequest req)
       throws ServletException, IOException
   {
       SdpMessage sdp = new SdpMessage(req.getContent());

       // Checks all the media declarations.
       int mcount = sdp.countMedias();
       for(int i = 0; i < mcount; i++) {
           SdpMessage.SdpMedia media = sdp.getMedia(i);
           if(! "audio".equals(media.getMediaType()))
               continue;

           // Checks the payload of the "audio" media.
           int pcount = media.countPayloads();
           for(int j = 0; j < pcount; j++) {
               SdpMessage.Payload p = media.getPayload(j);

               // Processes on a payload basis (confirming accessible media, etc.)

           }
       }
   }

The following example shows generating the sending SDP message using the SdpMessage class.

   SdpMessage sdp = new SdpMessage();
   sdp.setLocalOrigin("-", false);
   sdp.setSessionName("VoiceRecorder");
   sdp.setLocalConnection();
   sdp.setTime(0, 0);

   sdp.clearMedia();
   sdp.addMedia(media);

   SipServletResponse res = req.createResponse(200);
   res.setContent(sdp.toString(), "application/sdp");
   res.send();

For more information about each class, see JavaDoc.

DateUtils Class

DateUtils is a utility class for handling the Date header used in SIP. This class defines static methods about time representation. SIP uses the time representation that conforms to RFC1123. But the timezone should be fixed to GMT.

Time representation example: Sat, 13 Nov 2010 23:29:00 GMT

package com.oki.sip.equips.util;

public class DateUtils {

    public static String getString();
    public static String getString(long time);
    public static String getString(Date date);

    public static Date parse(String time);
}

getString is a method that retrieves a string representing time for SIP. getString() returns the current time. getString(long time) returns the time representation of the specified time. Specify time representation (long type) internally used in Java. getString(Date date) returns the time representation of the specified time. Specify the Date object that represents the specified time in date.

parse is a method that parses the time represented by string. It returns the Date object as the result of the parse. If the time argument does not conform to RFC1123, java.text.ParseException is thrown.

Last Modified:Wed Jan 12 19:29:43 JST 2005