Professional Documents
Culture Documents
Sun Microsystems, Inc. 4150 Network Circle Santa Clara, CA 95054 U.S.A.
Part No: 8203007 April, 2008
Sun Microsystems, Inc. has intellectual property rights relating to technology embodied in the product that is described in this document. In particular, and without limitation, these intellectual property rights may include one or more U.S. patents or pending patent applications in the U.S. and in other countries. U.S. Government Rights Commercial software. Government users are subject to the Sun Microsystems, Inc. standard license agreement and applicable provisions of the FAR and its supplements. This distribution may include materials developed by third parties. Parts of the product may be derived from Berkeley BSD systems, licensed from the University of California. UNIX is a registered trademark in the U.S. and other countries, exclusively licensed through X/Open Company, Ltd. Sun, Sun Microsystems, the Sun logo, the Solaris logo, the Java Coffee Cup logo, docs.sun.com, Java, and Solaris are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries. All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. in the U.S. and other countries. Products bearing SPARC trademarks are based upon an architecture developed by Sun Microsystems, Inc. The OPEN LOOK and SunTM Graphical User Interface was developed by Sun Microsystems, Inc. for its users and licensees. Sun acknowledges the pioneering efforts of Xerox in researching and developing the concept of visual or graphical user interfaces for the computer industry. Sun holds a non-exclusive license from Xerox to the Xerox Graphical User Interface, which license also covers Sun's licensees who implement OPEN LOOK GUIs and otherwise comply with Sun's written license agreements. Products covered by and information contained in this publication are controlled by U.S. Export Control laws and may be subject to the export or import laws in other countries. Nuclear, missile, chemical or biological weapons or nuclear maritime end uses or end users, whether direct or indirect, are strictly prohibited. Export or reexport to countries subject to U.S. embargo or to entities identified on U.S. export exclusion lists, including, but not limited to, the denied persons and specially designated nationals lists is strictly prohibited. DOCUMENTATION IS PROVIDED AS IS AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BE LEGALLY INVALID. Copyright 2008 Sun Microsystems, Inc. 4150 Network Circle, Santa Clara, CA 95054 U.S.A. Tous droits rservs.
Sun Microsystems, Inc. dtient les droits de proprit intellectuelle relatifs la technologie incorpore dans le produit qui est dcrit dans ce document. En particulier, et ce sans limitation, ces droits de proprit intellectuelle peuvent inclure un ou plusieurs brevets amricains ou des applications de brevet en attente aux Etats-Unis et dans d'autres pays. Cette distribution peut comprendre des composants dvelopps par des tierces personnes. Certaines composants de ce produit peuvent tre drives du logiciel Berkeley BSD, licencis par l'Universit de Californie. UNIX est une marque dpose aux Etats-Unis et dans d'autres pays; elle est licencie exclusivement par X/Open Company, Ltd. Sun, Sun Microsystems, le logo Sun, le logo Solaris, le logo Java Coffee Cup, docs.sun.com, Java et Solaris sont des marques de fabrique ou des marques dposes de Sun Microsystems, Inc. aux Etats-Unis et dans d'autres pays. Toutes les marques SPARC sont utilises sous licence et sont des marques de fabrique ou des marques dposes de SPARC International, Inc. aux Etats-Unis et dans d'autres pays. Les produits portant les marques SPARC sont bass sur une architecture dveloppe par Sun Microsystems, Inc. L'interface d'utilisation graphique OPEN LOOK et Sun a t dveloppe par Sun Microsystems, Inc. pour ses utilisateurs et licencis. Sun reconnat les efforts de pionniers de Xerox pour la recherche et le dveloppement du concept des interfaces d'utilisation visuelle ou graphique pour l'industrie de l'informatique. Sun dtient une licence non exclusive de Xerox sur l'interface d'utilisation graphique Xerox, cette licence couvrant galement les licencis de Sun qui mettent en place l'interface d'utilisation graphique OPEN LOOK et qui, en outre, se conforment aux licences crites de Sun. Les produits qui font l'objet de cette publication et les informations qu'il contient sont rgis par la legislation amricaine en matire de contrle des exportations et peuvent tre soumis au droit d'autres pays dans le domaine des exportations et importations. Les utilisations finales, ou utilisateurs finaux, pour des armes nuclaires, des missiles, des armes chimiques ou biologiques ou pour le nuclaire maritime, directement ou indirectement, sont strictement interdites. Les exportations ou rexportations vers des pays sous embargo des Etats-Unis, ou vers des entits figurant sur les listes d'exclusion d'exportation amricaines, y compris, mais de manire non exclusive, la liste de personnes qui font objet d'un ordre de ne pas participer, d'une faon directe ou indirecte, aux exportations des produits ou des services qui sont rgis par la legislation amricaine en matire de contrle des exportations et la liste de ressortissants spcifiquement designs, sont rigoureusement interdites. LA DOCUMENTATION EST FOURNIE "EN L'ETAT" ET TOUTES AUTRES CONDITIONS, DECLARATIONS ET GARANTIES EXPRESSES OU TACITES SONT FORMELLEMENT EXCLUES, DANS LA MESURE AUTORISEE PAR LA LOI APPLICABLE, Y COMPRIS NOTAMMENT TOUTE GARANTIE IMPLICITE RELATIVE A LA QUALITE MARCHANDE, A L'APTITUDE A UNE UTILISATION PARTICULIERE OU A L'ABSENCE DE CONTREFACON.
080411@19860
Contents
Preface .....................................................................................................................................................5
Overview of Session Initiation Protocol (SIP) Application Development .................................. 11 About the SIP Protocol ....................................................................................................................... 11 SIP Requests .................................................................................................................................. 11 SIP Responses ............................................................................................................................... 12 What Are SIP Servlets? ....................................................................................................................... 12 SIP Servlet Methods ..................................................................................................................... 12 SIP Servlets and the SIP Servlet Container ................................................................................ 12 Differences Between HTTP Servlets and SIP Servlets ............................................................. 13 SIP Servlets and Other Java EE Components ........................................................................... 13 Structure of a SIP Application .................................................................................................... 13
Simple SIP Servlet Examples ............................................................................................................. 15 Prerequisites for Running the Examples .......................................................................................... 15 The SipProxy Example ....................................................................................................................... 15 Developing the SIP Servlet .......................................................................................................... 15 Deploying and Running SipProxy ............................................................................................ 17 Deploying and Running SipProxy in NetBeans IDE 6.0 ................................................. 18 Testing SipProxy with the SIPp Application .................................................................... 18 The Click-To-Dial Example ............................................................................................................... 18 Architecture of the Click-To-Dial Example ............................................................................. 18 Running the Click-To-Dial Example ........................................................................................ 21 Deploying and Running Click-To-Dial in NetBeans IDE 6.0 ......................................... 21 Registering Alice's SIP Phone .............................................................................................. 21 Registering Bob's SIP Phone ............................................................................................... 22
3
Contents
Preface
This is The SIP Servlet Tutorial, a tutorial that describes how to develop telecommunications applications that use the session initialization protocol (SIP) on the Java EE platform. This tutorial also covers how you can integrate SIP applications with other Java EE technologies, like web applications and enterprise beans. Here we cover all the things you need to know to make the best use of this tutorial.
Java programming language developers interested in learning about how to create SIP applications. SIP application developers who are new to server-side Java programming language development. Anyone interested in how SIP applications work, and how they can be integrated in with traditional web applications and Java EE components.
This tutorial assumes you are conversant in reading Java programming language source code, and you have a basic understanding of client/server network applications.
Required Software
The following software is required to run the examples.
5
Preface
Tutorial Bundle
The tutorial example source is contained in the tutorial bundle. You can download the tutorial from https://sailfin.dev.java.net. After you have installed the tutorial bundle, the example source code is in the INSTALL/sip-tutorial-1.0/examples/ directory, where INSTALL is the directory where you installed the tutorial. The examples directory contains subdirectories for each of the example applications discussed in the tutorial.
Preface
7. Navigate to the download location of the modules, select all SIP Test Agent and SIP Application Development modules, and click Open. 8. Click Install, then Next. 9. Select I Agree in the License Agreement window and click Install. 10. Click Continue to install the unsigned modules, then click Finish.
Apache Ant
Ant is a Java technology-based build tool developed by the Apache Software Foundation (http://ant.apache.org), and is used to build, package, and deploy the tutorial examples. Ant is included with the Communications Application Server 1.0. To use the ant command, add JAVAEE_HOME/lib/ant/bin to your PATH environment variable.
Select Tools-->Server Manager to open the Server Manager dialog. Click Add Server. Under Server, select Sun Java System Application Server and click Next. Under Platform Location, enter the location of your Application Server installation. Select Register Local Default Domain and click Next. Under Admin Username and Admin Password, enter the admin name and password created when you installed the Application Server. Click Finish.
Preface
build.xml: Ant build file src/java: Java source files for the module src/conf: configuration files for the module, with the exception of web applications web: JSP and HTML pages, style sheets, tag files, and images web/WEB-INF: configuration files for web applications nbproject: NetBeans IDE project files
The Ant build files (build.xml) distributed with the examples contain targets to create a build subdirectory and to copy and compile files into that directory; a dist subdirectory, which holds the packaged module file; and a client-jar directory, which holds the retrieved application client JAR.
document. Sun does not endorse and is not responsible or liable for any content, advertising, products, or other materials that are available on or through such sites or resources. Sun will not be responsible or liable for any actual or alleged damage or loss caused or alleged to be caused by or in connection with use of or reliance on any such content, goods, or services that are available on or through such sites or resources.
The SailFin project home (https://sailfin.dev.java.net) The GlassFish project home (https://glassfish.dev.java.net) JSR 289: SIP Servlet 1.1 Specification (http://jcp.org/en/jsr/detail?id=289)
Preface
Typographic Conventions
The following table describes the typographic conventions that are used in this book.
TABLE P1 Typeface
Typographic Conventions
Meaning Example
AaBbCc123
The names of commands, files, and directories, and onscreen computer output
Edit your .login file. Use ls -a to list all files. machine_name% you have mail.
AaBbCc123
What you type, contrasted with onscreen computer output Placeholder: replace with a real name or value Book titles, new terms, and terms to be emphasized
machine_name% su Password: The command to remove a file is rm filename. Read Chapter 6 in the User's Guide. A cache is a copy that is stored locally. Do not save the file. Note: Some emphasized items appear bold online.
aabbcc123 AaBbCc123
Shell Prompts
Prompt
C shell C shell for superuser Bourne shell and Korn shell Bourne shell and Korn shell for superuser
machine_name% machine_name# $ #
10
C H A P T E R
This chapter describes the SIP protocol and the background needed for developing SIP applications using the Java programming language.
SIP Requests
The SIP protocol defines the following request types:
SIP Responses
The SIP Protocol uses response codes similar to the HTTP protocol, and are organized as follows:
100 (Trying) 200 (OK) 404 (Not found) 500 (Server internal failure)
HTTP servlets have a particular context (called the context-root) in which they run, while SIP servlets have no context. HTTP servlets typically return HTML pages to the requesting client, while SIP servlets typically connect SIP-enabled hardware to enable telecommunications between the client and server. SIP is a peer-to-peer protocol, unlike HTTP, and SIP servlets can originate SIP requests, unlike HTTP servlets which only send responses to the originating client. SIP servlets often act as proxies to other SIP endpoints, while HTTP servlets are typically the final endpoint for incoming HTTP requests. SIP servlets can generate multiple responses for a particular request. SIP servlets can communicate asynchronously, and are not obligated to respond to incoming requests. SIP servlets often work in concert with other SIP servlets to respond to particular SIP requests, unlike HTTP servlets which typically are solely responsible for responding to HTTP requests.
One or more SIP servlets. Optional utility and helper classes such as SIP listeners. Static resources used by the classes. Metadata and configuration files.
13
14
C H A P T E R
This chapter describes several of the simple SIP servlet examples that are included with Communications Application Server 1.0.
public class SimpleProxyServlet extends SipServlet implements SipErrorListener,Servlet { /** Creates a new instance of SimpleProxyServlet */ public SimpleProxyServlet() { }
protected void doInvite(SipServletRequest request) throws ServletException, IOException { if (request.isInitial()) { Proxy proxy = request.getProxy(); proxy.setRecordRoute(true); proxy.setSupervised(true); proxy.proxyTo(request.getRequestURI()); // bobs uri } System.out.println("SimpleProxyServlet: Got request:\n" + request); }
protected void doBye(SipServletRequest request) throws ServletException, IOException { System.out.println("SimpleProxyServlet: Got BYE request:\n" + request); super.doBye(request); }
protected void doResponse(SipServletResponse response) throws ServletException, IOException { System.out.println("SimpleProxyServlet: Got response:\n" + response); super.doResponse(response); }
16
// SipErrorListener public void noAckReceived(SipErrorEvent ee) { System.out.println("SimpleProxyServlet: Error: noAckReceived."); } public void noPrackReceived(SipErrorEvent ee) { System.out.println("SimpleProxyServlet: Error: noPrackReceived."); } }
SIP Methods
In SimpleProxyServlet, you override several methods to respond to the main SIP methods.
doInvite- responds to INVITE requests. In SimpleProxyServlet, upon receiving an INVITE request the servlet will create a javax.servlet.sip.Proxy instance, set some options, and proxy the request to the target SIP server.
doBye- responds to BYTE requests. In SimpleProxyServlet, the servlet logs a message upon receiving a BYE message, and calls the doBye method of the parent class (javax.servlet.sip.SipServlet).
SipErrorListener Methods
Because SimpleProxyServlet implements the SipErrorListener interface, it must implement the following methods:
noAckReceived is invoked to notify the application that no ACK message was received for an INVITE transaction. noPrackReceived is invoked when no PRACK message was received for a previously sent response.
17
Click FileOpen Project and navigate to sip-tutorial-1.0/examples/. Select SipProxy and click Open Project. Right-click on SipProxy in the Projects pane and click Run.
Be sure you have installed the SIPp test application, as described.... In a terminal, enter the following command to start the SIPp server on port 5090:
% sipp -sn uas -p 5090
In a new terminal enter the following command to start the SIPp client on port 5080:
% sipp -sn uac -rsa 127.0.0.1:5060 -p 5080 127.0.0.1:5090
You should now see the messages from the client get returned by the server, with the SipProxy application acting as a proxy between them.
3. Alice clicks on Bob's Call link from the web application to start a phone call to Bob. The PlaceCallServletHTTP servlet passes the data to CallSipServlet in order to initiate the connection. 4. Alice's phone rings. 5. When Alice picks up her phone, a call is placed to Bob's phone, and Bob's phone rings. 6. When Bob picks up his phone, the connection is established, and Alice and Bob can have a conversation. 7. When Alice or Bob hangs up, the connection is terminated, and they are able to receive calls again.
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. Here is the full code listing for the RegistrarServlet class.
public class RegistrarServlet extends SipServlet { private static final Logger logger = Logger.getLogger(RegistrarServlet.class.getName()); // inject the SipFactory @Resource(mappedName="sip/ClickToDial") private SipFactory sf; protected void doRegister(SipServletRequest req) throws ServletException, IOException { logger.info("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(); }
Chapter 2 Simple SIP Servlet Examples 19
// 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); resp.send(); } 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); } logger.info("Register address: " + addr); // store the contact address in the database p.setTelephone(addr.getURI().toString()); ModelFacade mf = (ModelFacade) getServletContext().getAttribute("Model");
20 The SIP Servlet Tutorial April, 2008
mf.updatePerson(p); return SipServletResponse.SC_OK; } private int handleUnregister(SipServletRequest req, Person p) { // store the contact address in the database p.setTelephone(null); ModelFacade mf = (ModelFacade) getServletContext().getAttribute("Model"); mf.updatePerson(p); return SipServletResponse.SC_OK; } }
In NetBeans IDE 6.0, click Open Project and navigate to sip-tutorial/examples/ClickToDial. Right-click on the ClickToDial project and select Run. This will open a browser to http://localhost:8080/ClickToDial.
In your web browser select Alice from the drop-down menu and click Login. In NetBeans IDE 6.0 right-click on ClickToDial and select SIP Test Agent. This will open a new Test Agent instance that will represent Alice's phone. Click New Request in Alice's SIP Test Agent and under Method select REGISTER. Under Headers click Add. For the new Header, under Name, select Expires, and under Value type 10. The SIP request requires an Expires header to be set in order to register Alice. Click Send.
Chapter 2 Simple SIP Servlet Examples 21
3 4 5
Refresh your web browser to see that Alice now has a registered SIP URI.
In your web browser, click Logout to logout as Alice. At the Login page, select Bob and click Login. In NetBeans IDE 6.0 right-click on ClickToDial and select SIP Test Agent. This will open a new Test Agent instance that will represent Bob's phone. Under Agent Name, enter Bob. Under Listening Port, change the port number to 6061 and click Apply. Click New Request in Bob's SIP Test Agent and under Method select REGISTER. Under Headers click Add. For the new Header, under Name, select Expires, and under Value type 10. The SIP request requires an Expires header to be set in order to register Alice. Click Send. Refresh your web browser. You should see that Bob now has a registered SIP URI. You may now click Call next to Alice's name and SIP URI to place a call to Alice.
Note The SIP Test Agent doesn't actually function as a SIP phone. It is primarily used for sending and receiving SIP messages.
4 5 6 7 8
9 10
22
A P P E N D I X
SIP Messages
SIP Requests
This section lists the SIP requests as defined by RFC 3261.
TABLE A1 SIP Request
SIP Requests
Description
initiate a session between two participants the client acknowledges receiving the final message from an INVITE request terminates a connection cancels any pending actions, but does not terminate any accepted connections queries the server for a list of capabilities registers the address in the To header with the server
SIP Responses
TABLE A2
SIP Requests
Description
SIP Response
100-199 200-299
23
SIP Responses
TABLE A2
SIP Requests
(Continued)
Description
SIP Response
Redirection responses Client error responses Server error responses Global failure responses
24