April 13, 2011

Jain SIP: How to read a SDP content

import javax.sdp.*;
import javax.sip.*;

ContentTypeHeader contentType = (ContentTypeHeader) msg.getHeader(ContentTypeHeader.NAME);
ContentLengthHeader contentLen = (ContentLengthHeader) msg.getHeader(ContentLengthHeader.NAME);

if ( contentLen.getContentLength() > 0 && contentType.getContentSubType().equals("sdp") ){
    String charset = null;
   
    if (contentType != null)
        charset = contentType.getParameter("charset");
    if (charset == null)
        charset = "UTF-8"; // RFC 3261

    //Save the SDP content in a String
    byte[] rawContent = msg.getRawContent();
    String sdpContent = new String(rawContent, charset);

    //Use the static method of SdpFactory to parse the content
    SdpFactory sdpFactory = SdpFactory.getInstance();
    SessionDescription sessionDescription = sdpFactory.createSessionDescription(sdpContent);
    Origin origin = sessionDescription.getOrigin();
   
    System.out.println("A Session ID is " + origin.getSessionId());
} else {
    System.out.println("It is not a SDP content");
}

How to create initialized enum in Java.

One day I needed to create enum initialized to values other than its default values in Java. It can be done easily in C++. For example, look at the code below:

typedef enum ResponseType{
     OK = 200,
     TRYING = 100,
     RINGING = 180
} TResponseType;

However it is not so obvious in Java.

public enum ResponseType {
     OK(200),
     TRYING(100),
     RINGING(180),
     SESSION_PROGRESS(183),
     BAD_REQUEST(400),
     NOT_FOUND(404);

     private int value;

     ResponseType(int value){
           this.value = value;
     }

     public int getValue() {
          return value;
     }
};