The SIP Servlet Tutorial

Click-To-Dial's SIP Servlets

The SIP functionality in Click-To-Dial is split into two separate SIP servlets, RegistrarServlet and CallSipServlet.

SIP Application Annotations in CllickToDial

A @SipApplication annotation is used in ClickToDial to define a set of SIP servlets used together to provide SIP functionality. The @SipApplication annotation is set at the package level by putting it in the file in the clicktodial.sip package.

Example 2–1 Package-level @SipApplicaton Annotation in ClickToDial

package clicktodial.sip;

The @SipApplication annotation sets two elements: the name of the application, and the main servlet. The name element is required, and is set to the application name. The optional mainServlet element defines which SIP servlet will initially respond to SIP requests. In this case, the RegistrarServlet, which registers SIP clients so they can be later contacted for calls, is the main servlet for ClickToDial.

The RegistrarServlet

The RegistrarServlet allows users to register soft-phones with the application, and stores the user's data in a database using the Java Persistence API.

RegistrarServlet has three methods: doRegister, handleRegister, and handleUnregister.

The doRegister method responds to REGISTER messages and performs some checks on the incoming request, extracts the user name from the request, looks the user up in the database of users, and examines the EXPIRES header of the request to determine whether the request is a registration or unregistration request. If it is a registration request, the handleRegister private helper method is called. If it is an unregistration request, the handleUnregister private helper method is called. These methods will return a SIP response to send back to the client.

Example 2–2 The doResponse Method

protected void doRegister(SipServletRequest req) 
        	throws ServletException, IOException {"Received register request: " + req.getTo());
        int response = SipServletResponse.SC_SERVER_INTERNAL_ERROR;
        ModelFacade mf = (ModelFacade) getServletContext().getAttribute("Model");
        // Figure out the name the user is registering with.  This is the
        // user portion of the SIP URI, e.g. "Bob" in "sip:Bob@x.y.z:port"
        String username = null;
        if (req.getTo().getURI().isSipURI()) {
            username = ((SipURI) req.getTo().getURI()).getUser();
        // get the Person object from the database
        Person p = mf.getPerson(username);
        if (p != null) {
            // the Expires header tells us if this is a registration or
            // unregistration attempt.  An expires value of 0 or no Expires
            // header means it is an unregistration.
            int expires = 0;
            String expStr = req.getHeader("Expires");
            if (expStr != null) {
                expires = Integer.parseInt(expStr);
            if (expires == 0) {
                // unregister
                response = handleUnregister(req, p);
            } else {
                // register
                response = handleRegister(req, p);
        } else {
            // no person found in the database
            response = SipServletResponse.SC_NOT_FOUND;
        // send the response
        SipServletResponse resp = req.createResponse(response);

The handleRegister method extracts the user's SIP address from the request, stores it in the user database, and returns a SIP OK response. The user can now place and receive calls.

Example 2–3 The handleRegister Method

private int handleRegister(SipServletRequest req, Person p)
        throws ServletException {

        // Get the contact address from the request.  Prefer the
        // "Contact" address if given, otherwise use the "To" address
        Address addr = req.getTo();
        String contact = req.getHeader("Contact");
        if (contact != null) {
            addr = sf.createAddress(contact);
       "Register address: " + addr);
        // store the contact address in the database
        ModelFacade mf = (ModelFacade) getServletContext().getAttribute("Model");
        return SipServletResponse.SC_OK;

The handleUnregister method removes the user's SIP address from the database by setting it to null, then sends a SIP OK response back. The user cannot place or receive calls after being unregistered.

Example 2–4 The handleUnregister Method

private int handleUnregister(SipServletRequest req, Person p) {
        // store the contact address in the database
        ModelFacade mf = (ModelFacade) getServletContext().getAttribute("Model");
        return SipServletResponse.SC_OK;

The CallSipServlet

The CallSipServlet SIP servlet connects registered SIP users to one another, allowing users to place calls to one another. There are 5 main SIP methods in CallSipServlet: doSuccessResponse, sendInviteToClient, sendAckToClient, sendAckToServer, and sent200OKToClient.

CallSipServlet is annotated at the class-level with a @SipServlet and @SipListener annotation.

public class CallSipServlet extends SipServlet implements SipSessionListener {

The doSuccessResponse method connects a call between two registered users. When the first user Alice initiates a call to the second user Bob, first Alice's phone rings. If Alice answers her phone, a SIP OK message is sent. At that point, Bob's address is extracted from the request, a SIP INVITE message is sent to Bob's address by calling the sendInviteToClient private method, and Bob's phone rings. If Bob answers the phone, a SIP OK message is sent. The two SIP sessions, from Alice and Bob respectively, are linked, and a SIP ACK message is sent to both user's phones by calling the sendAckToClient and sendAckToServer private methods. Alice and Bob are now connected and can have a conversation. When the call is terminated, a BYE message is sent from the server, and the send200OKToClient private method is called.

Example 2–5 The doSuccessResponse Method

protected void doSuccessResponse(SipServletResponse resp)
        throws ServletException, IOException {"Received a response.\n" + resp);

    if (resp.getMethod().equals("INVITE")) {
        List<SipSession> sipSessions = getSipSessions(resp.getApplicationSession());
        if (sipSessions.size() == 1) {
            sipSessions.get(0).setAttribute("ACK", resp.createAck());
        } else { // 200 OK from Client
    } else if (resp.getMethod().equals("BYE")) {

Example 2–6 The sendInviteToClient Method

private void sendInviteToClient(SipServletResponse serverResp)
        throws ServletException, IOException {
    SipServletRequest serverReq = serverResp.getRequest();
    B2buaHelper b2buaHelper = serverReq.getB2buaHelper();

    // Swap To & From headers.
    Map<String, List<String>> headerMap = new HashMap<String, List<String>>();
    List<String> from = new ArrayList<String>();
    headerMap.put("To", from);
    List<String> to = new ArrayList<String>();
    headerMap.put("From", to);

    SipServletRequest clientRequest = b2buaHelper
				.createRequest(serverReq, true, headerMap);
    if (serverResp.getContent() != null) { // set sdp1
    }"Sending INVITE to client.\n" + clientRequest);

Example 2–7 The sendAckToClient Method

private void sendAckToClient(SipServletResponse clientResp) 
        throws ServletException, IOException {
    SipServletRequest ack = clientResp.createAck();"Sending ACK to client.\n" + ack);

Example 2–8 The sendAckToServer Method

private void sendAckToServer(SipServletResponse clientResp) 
        throws ServletException, IOException {
    B2buaHelper b2buaHelper = clientResp.getRequest().getB2buaHelper();
    SipSession clientSession = clientResp.getSession();
    SipSession serverSession = b2buaHelper.getLinkedSession(clientSession);
    SipServletRequest ack = (SipServletRequest) serverSession.getAttribute("ACK");
    if (clientResp.getContent() != null) { // set sdp2
        ack.setContent(clientResp.getContent(), clientResp.getContentType());
    }"Sending ACK to server.\n" + ack);

Example 2–9 The send200OKToClient Method

    protected void doBye(SipServletRequest request)
        throws ServletException, IOException 
    {"Got bye");
        SipSession session = request.getSession();
        // end the linked call 
        SipSession linkedSession = (SipSession) session.getAttribute("LinkedSession");
        if (linkedSession != null) {
            // create a BYE request to the linked session
            SipServletRequest bye = linkedSession.createRequest("BYE");
  "Sending bye to " + linkedSession.getRemoteParty());
            // send the BYE request
        // send an OK for the BYE
        SipServletResponse ok = request.createResponse(SipServletResponse.SC_OK);

There are three SIP session listener methods implemented in CallSipServlet, from the SipSessionListener interface: sessionCreated, sessionDestroyed, and sessionReadyToInvalidate. In CallSipServlet, the methods simply log the events.

Example 2–10 SipSessionListener Methods Implemented in CallSipServlet

public void sessionCreated(SipSessionEvent sse) {"Session created");

public void sessionDestroyed(SipSessionEvent sse) {"Session destroyed");
public void sessionReadyToInvalidate(SipSessionEvent sse) {"Session ready to be invalidated");