KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > echo2example > chatserver > ChatServerServlet


1 /*
2  * This file is part of the Echo Web Application Framework (hereinafter "Echo").
3  * Copyright (C) 2002-2005 NextApp, Inc.
4  *
5  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
6  *
7  * The contents of this file are subject to the Mozilla Public License Version
8  * 1.1 (the "License"); you may not use this file except in compliance with
9  * the License. You may obtain a copy of the License at
10  * http://www.mozilla.org/MPL/
11  *
12  * Software distributed under the License is distributed on an "AS IS" basis,
13  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14  * for the specific language governing rights and limitations under the
15  * License.
16  *
17  * Alternatively, the contents of this file may be used under the terms of
18  * either the GNU General Public License Version 2 or later (the "GPL"), or
19  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
20  * in which case the provisions of the GPL or the LGPL are applicable instead
21  * of those above. If you wish to allow use of your version of this file only
22  * under the terms of either the GPL or the LGPL, and not to allow others to
23  * use your version of this file under the terms of the MPL, indicate your
24  * decision by deleting the provisions above and replace them with the notice
25  * and other provisions required by the GPL or the LGPL. If you do not delete
26  * the provisions above, a recipient may use your version of this file under
27  * the terms of any one of the MPL, the GPL or the LGPL.
28  */

29
30 package echo2example.chatserver;
31
32 import java.io.IOException JavaDoc;
33 import java.io.InputStream JavaDoc;
34
35 import javax.servlet.ServletException JavaDoc;
36 import javax.servlet.http.HttpServlet JavaDoc;
37 import javax.servlet.http.HttpServletRequest JavaDoc;
38 import javax.servlet.http.HttpServletResponse JavaDoc;
39 import javax.xml.parsers.DocumentBuilder JavaDoc;
40 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
41 import javax.xml.parsers.ParserConfigurationException JavaDoc;
42 import javax.xml.transform.Transformer JavaDoc;
43 import javax.xml.transform.TransformerException JavaDoc;
44 import javax.xml.transform.TransformerFactory JavaDoc;
45 import javax.xml.transform.dom.DOMSource JavaDoc;
46 import javax.xml.transform.stream.StreamResult JavaDoc;
47
48 import org.w3c.dom.Document JavaDoc;
49 import org.w3c.dom.Element JavaDoc;
50 import org.w3c.dom.NodeList JavaDoc;
51 import org.w3c.dom.Text JavaDoc;
52 import org.xml.sax.SAXException JavaDoc;
53
54 /**
55  * Chat Server Servlet
56  */

57 public class ChatServerServlet extends HttpServlet JavaDoc {
58     
59     private static final Server server = new Server();
60     
61     /**
62      * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
63      */

64     protected void doPost(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
65     throws ServletException JavaDoc, IOException JavaDoc {
66         Document JavaDoc requestDocument = loadRequestDocument(request);
67         Document JavaDoc responseDocument = createResponseDocument();
68         processUserAdd(requestDocument, responseDocument);
69         processUserRemove(requestDocument, responseDocument);
70         processPostMessage(requestDocument, responseDocument);
71         processGetMessages(requestDocument, responseDocument);
72         renderResponseDocument(response, responseDocument);
73     }
74     
75     /**
76      * Creates the response DOM document, containing a 'chat-server-response'
77      * document element.
78      *
79      * @return the response document
80      */

81     private Document JavaDoc createResponseDocument()
82     throws IOException JavaDoc {
83         try {
84             DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
85             factory.setNamespaceAware(true);
86             DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
87             Document JavaDoc document = builder.newDocument();
88             document.appendChild(document.createElement("chat-server-response"));
89             return document;
90         } catch (ParserConfigurationException JavaDoc ex) {
91             throw new IOException JavaDoc("Cannot create document: " + ex);
92         }
93     }
94     
95     /**
96      * Retrieves the request DOM document from an incoming
97      * <code>httpServletRequest</code>.
98      *
99      * @param request the <code>HttpServletRequest</code>
100      * @return the request DOM document
101      */

102     private Document JavaDoc loadRequestDocument(HttpServletRequest JavaDoc request)
103     throws IOException JavaDoc {
104         InputStream JavaDoc in = null;
105         try {
106             request.setCharacterEncoding("UTF-8");
107             in = request.getInputStream();
108             DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
109             factory.setNamespaceAware(true);
110             DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
111             return builder.parse(in);
112         } catch (ParserConfigurationException JavaDoc ex) {
113             throw new IOException JavaDoc("Provided InputStream cannot be parsed: " + ex);
114         } catch (SAXException JavaDoc ex) {
115             throw new IOException JavaDoc("Provided InputStream cannot be parsed: " + ex);
116         } catch (IOException JavaDoc ex) {
117             throw new IOException JavaDoc("Provided InputStream cannot be parsed: " + ex);
118         } finally {
119             if (in != null) { try { in.close(); } catch (IOException JavaDoc ex) { } }
120         }
121     }
122     
123     /**
124      * Retrieves new messages posted with id values higher than the
125      * request document's specified 'last-retrieved-id' value.
126      *
127      * @param requestDocument the request DOM document
128      * @param responseDocument the response DOM document
129      */

130     private void processGetMessages(Document JavaDoc requestDocument, Document JavaDoc responseDocument) {
131         String JavaDoc lastRetrievedIdString = requestDocument.getDocumentElement().getAttribute("last-retrieved-id");
132         Message[] messages;
133         if (lastRetrievedIdString == null || lastRetrievedIdString.trim().length() == 0) {
134             messages = server.getRecentMessages();
135         } else {
136             long lastRetrievedId = Long.parseLong(lastRetrievedIdString);
137             messages = server.getMessages(lastRetrievedId);
138         }
139         for (int i = 0; i < messages.length; ++i) {
140             Element JavaDoc messageElement = responseDocument.createElement("message");
141             messageElement.setAttribute("id", Long.toString(messages[i].getId()));
142             if (messages[i].getUserName() != null) {
143                 messageElement.setAttribute("user-name", messages[i].getUserName());
144             }
145             messageElement.setAttribute("time", Long.toString(messages[i].getPostTime()));
146             messageElement.appendChild(responseDocument.createTextNode(messages[i].getContent()));
147             responseDocument.getDocumentElement().appendChild(messageElement);
148         }
149     }
150     
151     /**
152      * Processes a request (if applicable) to post a message to the chat
153      * server.
154      *
155      * @param requestDocument the request DOM document
156      * @param responseDocument the response DOM document
157      */

158     private void processPostMessage(Document JavaDoc requestDocument, Document JavaDoc responseDocument) {
159         NodeList JavaDoc postMessageNodes = requestDocument.getDocumentElement().getElementsByTagName("post-message");
160         if (postMessageNodes.getLength() == 0) {
161             // Posting not requested.
162
return;
163         }
164         
165         String JavaDoc remoteHost = requestDocument.getDocumentElement().getAttribute("remote-host");
166
167         Element JavaDoc postMessageElement = (Element JavaDoc) postMessageNodes.item(0);
168         String JavaDoc userName = postMessageElement.getAttribute("user-name");
169         String JavaDoc authToken = postMessageElement.getAttribute("auth-token");
170         NodeList JavaDoc postMessageContentNodes = postMessageElement.getChildNodes();
171         int length = postMessageContentNodes.getLength();
172         for (int i = 0; i < length; ++i) {
173             if (postMessageContentNodes.item(i) instanceof Text JavaDoc) {
174                 server.postMessage(userName, authToken, remoteHost, ((Text JavaDoc) postMessageContentNodes.item(i)).getNodeValue());
175             }
176         }
177     }
178     
179     /**
180      * Process a request (if applicable) to add a user to the chat.
181      *
182      * @param requestDocument the request DOM document
183      * @param responseDocument the response DOM document
184      */

185     private void processUserAdd(Document JavaDoc requestDocument, Document JavaDoc responseDocument) {
186         NodeList JavaDoc userAddNodes = requestDocument.getDocumentElement().getElementsByTagName("user-add");
187         if (userAddNodes.getLength() == 0) {
188             // User add not requested.
189
return;
190         }
191
192         String JavaDoc remoteHost = requestDocument.getDocumentElement().getAttribute("remote-host");
193         
194         // Attempt to authenticate.
195
Element JavaDoc userAddElement = (Element JavaDoc) userAddNodes.item(0);
196         String JavaDoc userName = userAddElement.getAttribute("name");
197         String JavaDoc authToken = server.addUser(userName, remoteHost);
198         
199         Element JavaDoc userAuthElement = responseDocument.createElement("user-auth");
200         if (authToken == null) {
201             userAuthElement.setAttribute("failed", "true");
202         } else {
203             userAuthElement.setAttribute("auth-token", authToken);
204         }
205         responseDocument.getDocumentElement().appendChild(userAuthElement);
206     }
207     
208     /**
209      * Process a request (if applicable) to remove a user from the chat.
210      *
211      * @param requestDocument the request DOM document
212      * @param responseDocument the response DOM document
213      */

214     private void processUserRemove(Document JavaDoc requestDocument, Document JavaDoc responseDocument) {
215         NodeList JavaDoc userRemoveNodes = requestDocument.getDocumentElement().getElementsByTagName("user-remove");
216         if (userRemoveNodes.getLength() == 0) {
217             // User remove not requested.
218
return;
219         }
220         
221         Element JavaDoc userRemoveElement = (Element JavaDoc) userRemoveNodes.item(0);
222         String JavaDoc userName = userRemoveElement.getAttribute("name");
223         String JavaDoc authToken = userRemoveElement.getAttribute("auth-token");
224         
225         String JavaDoc remoteHost = requestDocument.getDocumentElement().getAttribute("remote-host");
226
227         server.removeUser(userName, authToken, remoteHost);
228     }
229     
230     /**
231      * Renders the response DOM document to the
232      * <code>HttpServletResponse</code>.
233      *
234      * @param response the outgoing <code>HttpServletResponse</code>
235      * @param responseDocument the response DOM document
236      */

237     private void renderResponseDocument(HttpServletResponse JavaDoc response, Document JavaDoc responseDocument)
238     throws IOException JavaDoc {
239         response.setContentType("text/xml; charset=UTF-8");
240         try {
241             TransformerFactory JavaDoc tFactory = TransformerFactory.newInstance();
242             Transformer JavaDoc transformer = tFactory.newTransformer();
243             DOMSource JavaDoc source = new DOMSource JavaDoc(responseDocument);
244             StreamResult JavaDoc result = new StreamResult JavaDoc(response.getWriter());
245             transformer.transform(source, result);
246         } catch (TransformerException JavaDoc ex) {
247             throw new IOException JavaDoc("Unable to write document to OutputStream: " + ex.toString());
248         }
249     }
250 }
251
Popular Tags