KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mmbase > applications > dove > servlet > DoveServlet


1 /*
2  
3 This software is OSI Certified Open Source Software.
4 OSI Certified is a certification mark of the Open Source Initiative.
5  
6 The license (Mozilla version 1.0) can be read at the MMBase site.
7 See http://www.MMBase.org/license
8  
9  */

10 package org.mmbase.applications.dove.servlet;
11
12 import java.io.*;
13
14 import javax.servlet.http.*;
15 import javax.servlet.*;
16
17
18 import javax.xml.parsers.DocumentBuilder JavaDoc;
19 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
20 import org.xml.sax.*;
21 import org.w3c.dom.*;
22
23 import org.mmbase.util.*;
24
25 import org.mmbase.util.logging.*;
26 import org.mmbase.util.xml.*;
27 import org.mmbase.applications.dove.*;
28 import org.mmbase.servlet.MMBaseServlet;
29
30 /**
31  * This servlet routes RPC requests (represented in xml) to the intended method of
32  * the 'Dove' object.
33  *
34  * @author Pierre van Rooden
35  * @since MMBase-1.5
36  * @version $Id: DoveServlet.java,v 1.12 2005/01/30 16:46:40 nico Exp $
37  */

38 public class DoveServlet extends MMBaseServlet { // MMBase, only to be able to use its logging
39

40     private static final Logger log = Logging.getLoggerInstance(DoveServlet.class);
41
42     /**
43      * Handles a request using the GET method.
44      * No communication is handled through GET - this method is for testing whether the servlet is online.
45      * @param req the HTTP Request object
46      * @param res the HTTP Response object
47      */

48     public void doGet(HttpServletRequest req, HttpServletResponse res)
49     throws ServletException, IOException {
50         PrintWriter out = res.getWriter();
51         
52         res.setContentType("text/html");
53         out.println("<html><head><title>Dove</title></head>");
54         out.println("<body><h1>Dove RPC Router</h1>");
55         out.println("<p>The Dove servlet is active. use HTTP Post to send RPC commands.</p></body></html>");
56     }
57     
58     /**
59      * Handles a request using the POST method.
60      * Retrieves the value of the 'xml' parameter, and parses the body of that
61      * parameter as an xml text. The resulting DOM tree is then passed to the Dove
62      * class, which runs the RPCs described in that tree.
63      * The result of Dove (also a DOM tree) is returned as xml to the client.
64      * The mime type of the result is 'text/xml', unless the 'plain' parameter
65      * is set to 'yes', in which case the mime type is 'text/plain'.
66      * Specifying a 'pretty' parameter with value 'yes' results in pretty printed xml.
67      * Both these parameters are ment for debugging.
68      * <br />
69      * XXX: Possibly we want to use xml directly in the body, instead of parameters.
70      * <br />
71      * XXX: Daniel suggested using CRC to validate calls. This is not implemented yet.
72      * <br />
73      * XXX: We have not yet established how we will use session-info and usercontext.
74      *
75      * @param req the HTTP Request object
76      * @param res the HTTP Response object
77      */

78     public void doPost(HttpServletRequest req, HttpServletResponse res)
79     throws ServletException, IOException {
80         String JavaDoc error="unknown error";
81         String JavaDoc errortype="unknown";
82         boolean pretty="yes".equals(req.getParameter("pretty"));
83         boolean plain="yes".equals(req.getParameter("plain"));
84         try {
85             DoveErrorHandler errorhandler = new DoveErrorHandler();
86             DocumentBuilder JavaDoc db = XMLBasicReader.getDocumentBuilder(false,errorhandler);
87             
88             // Right now we read content from parameters
89
// Maybe we want the xml to be directly in the body?
90
// Depends on how the editors will post.
91
String JavaDoc s = req.getParameter("xml");
92             if (log.isDebugEnabled()){ log.debug("received : "+s);};
93             Document document = db.parse(new InputSource(new StringReader(s)));
94             if (errorhandler.erroroccurred) {
95                 error=errorhandler.parsingerrors;
96                 errortype="parser";
97             } else {
98                 Element rootin=document.getDocumentElement();
99                 if (rootin.getTagName().equals(AbstractDove.REQUEST)) {
100                     DocumentBuilder JavaDoc docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
101                     Document doc = docBuilder.newDocument();
102                     Element rootout =doc.createElement(AbstractDove.RESPONSE);
103                     doc.appendChild(rootout);
104                     Dove birdy = new Dove(doc);
105                     birdy.doRequest(rootin, rootout);
106                     res.setStatus(HttpServletResponse.SC_OK);
107                     if (plain) {
108                         res.setContentType("text/plain");
109                     } else {
110                         res.setContentType("text/xml");
111                     }
112                     
113                     BufferedWriter out=new BufferedWriter( new OutputStreamWriter(res.getOutputStream()));
114                     String JavaDoc content = XMLWriter.write(doc,pretty);
115                     if (log.isDebugEnabled()){log.debug("sending : " + content);}
116                     out.write(content);
117                     out.flush();
118                     return;
119                 } else {
120                     error="No request found.";
121                     errortype="parser";
122                 }
123             }
124         } catch (Exception JavaDoc e) {
125             log.error(Logging.stackTrace(e));
126             error="System error: "+e;
127             errortype="server";
128         }
129         ServletOutputStream out = res.getOutputStream();
130         res.setStatus(HttpServletResponse.SC_OK);
131         if (plain) {
132             res.setContentType("text/plain");
133         } else {
134             res.setContentType("text/xml");
135         }
136         out.println("<response><error type=\"" + errortype + "\">" + error + "</error></response>");
137         out.flush();
138     }
139     
140     /**
141      * Dove Error handler for catching and storing parsing exceptions.
142      * The Error handler catches all exceptions and stores their descriptions.
143      * These can then be retrieved by the Dove servlet, so it can generate an
144      * error response.
145      */

146     public class DoveErrorHandler implements ErrorHandler {
147         
148         /**
149          * The errors that occurred during the parse.
150          */

151         public String JavaDoc parsingerrors="";
152         
153         /**
154          * Indicates whether any errors occurred.
155          */

156         public boolean erroroccurred=false;
157         
158         /**
159          * Logs an error and adds it to the list of parsing errors.
160          * @param ex the parsing exception describing the error
161          */

162         public void error(SAXParseException ex) {
163             erroroccurred=true;
164             String JavaDoc s = getErrorString(ex);
165             log.error(s);
166             parsingerrors=parsingerrors+s+"\n";
167         }
168         
169         /**
170          * Logs a warning.
171          * Warnings are not added to the list of parsing errors.
172          * @param ex the parsing exception describig the error
173          */

174         public void warning(SAXParseException ex) {
175             log.warn(getErrorString(ex));
176         }
177         
178         /**
179          * Logs a fatal error.
180          * Fatal errors are not added to the list of parsing errors, they
181          * throw an exception and abort parsing.
182          * @param ex the parsing exception describing the error
183          */

184         public void fatalError(SAXParseException ex) throws SAXException {
185             log.error("[Fatal Error] "+ getErrorString(ex));
186             throw ex;
187         }
188         
189         /**
190          * Returns a string describing the error.
191          * @param ex the parsing exception describing the error
192          * @return the error string
193          */

194         private String JavaDoc getErrorString(SAXParseException ex) {
195             String JavaDoc msg = "";
196             String JavaDoc systemId = ex.getSystemId();
197             if (systemId != null) {
198                 int index = systemId.lastIndexOf('/');
199                 msg=systemId.substring(index + 1)+":";
200             }
201             return msg +ex.getLineNumber()+":"+
202             ex.getColumnNumber()+":"+
203             ex.getMessage();
204         }
205     }
206     
207 }
208
Popular Tags