KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > contineo > actions > rest > RESTAction


1 /* License: GNU General Public License (GPL) version 2 from June 1991; but not any newer version!
2  */

3 package org.contineo.actions.rest;
4
5 import java.io.PrintWriter JavaDoc;
6
7 import javax.servlet.http.HttpServletResponse JavaDoc;
8 import javax.xml.parsers.DocumentBuilder JavaDoc;
9 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
10 import javax.xml.parsers.ParserConfigurationException JavaDoc;
11 import javax.xml.transform.OutputKeys JavaDoc;
12 import javax.xml.transform.Transformer JavaDoc;
13 import javax.xml.transform.TransformerConfigurationException JavaDoc;
14 import javax.xml.transform.TransformerException JavaDoc;
15 import javax.xml.transform.TransformerFactory JavaDoc;
16 import javax.xml.transform.TransformerFactoryConfigurationError JavaDoc;
17 import javax.xml.transform.dom.DOMSource JavaDoc;
18 import javax.xml.transform.stream.StreamResult JavaDoc;
19
20 import org.apache.log4j.Level;
21 import org.apache.log4j.Logger;
22 import org.contineo.apis.rest.HttpStatusCodes;
23 import org.contineo.core.DateBean;
24 import org.contineo.core.LoggingManager;
25 import org.w3c.dom.Document JavaDoc;
26 import org.w3c.dom.Element JavaDoc;
27 import org.w3c.dom.Text JavaDoc;
28
29 public abstract class RESTAction {
30     
31     /** the HTTP status code */
32     protected int httpStatusCode = HttpStatusCodes.OK;
33     
34     /** in this object we store the response */
35     protected HttpServletResponse JavaDoc response = null;
36     
37     /** id of the user requesting the service */
38     protected String JavaDoc userName;
39     
40     /** namespace prefix */
41     protected final String JavaDoc namespaceUrlPrefix = "http://contineo.sourceforge.net/";
42
43     /** location of the XML Schemas used for the exchanged XML messages */
44     protected final String JavaDoc schemaLocation = namespaceUrlPrefix + "schemas/ver2.2/";
45     
46     /**
47      * name of the schema file; this name is different for the different actions, so
48      * it must be set by the inheriting classes in the constructor
49      */

50     protected final String JavaDoc schemaName;
51     
52     /** Url requested by the client; we need this to build other Urls in the XML responses */
53     protected final String JavaDoc localRESTUrl;
54     
55     /** string summarising the REST interface like: "GET REST/document/XX: download doc XX" */
56     private final String JavaDoc interfaceIdentifier;
57     
58     /** for log message creation */
59     protected Logger logger;
60     
61     /**
62      * constructor of RESTAction, must be called by inheriting classes
63      * @param p_schemaName name of the schema file for the handled message or null,
64      * if the inheriting class does not send or receive an XML message
65      * @param p_response the HTTP object we should send the response to
66      * @param p_userName the user name requesting the service
67      * @param requestedUrl URL requested by the client
68      */

69     protected RESTAction(String JavaDoc p_schemaName, String JavaDoc requestedRESTUrl, String JavaDoc p_userName,
70                          HttpServletResponse JavaDoc p_response, String JavaDoc p_interfaceIdentifier) {
71         schemaName = p_schemaName;
72         localRESTUrl = requestedRESTUrl;
73         response = p_response;
74         userName = p_userName;
75         logger = LoggingManager.getLogger(this.getClass());
76         interfaceIdentifier = p_interfaceIdentifier;
77     }
78     
79     /** each inheriting class must implement this function; here the actual request processing is done */
80     protected abstract void processRequest();
81
82     /**
83      * creates an XML document
84      */

85     protected Document JavaDoc createXMLDocument() throws ParserConfigurationException JavaDoc {
86         DocumentBuilderFactory JavaDoc docBuildFactory = DocumentBuilderFactory.newInstance();
87         DocumentBuilder JavaDoc docBuilder = docBuildFactory.newDocumentBuilder();
88         Document JavaDoc xmlDoc = docBuilder.newDocument();
89         return xmlDoc;
90     }
91
92     /**
93      * gets the XML document in memory and writes it to the output writer
94      * @param xmlDoc the XML document as input (memory)
95      * @param responseWriter the output
96      */

97     protected void writeXMLDocument(Document JavaDoc xmlDoc, PrintWriter JavaDoc responseWriter)
98         throws TransformerFactoryConfigurationError JavaDoc, TransformerConfigurationException JavaDoc, TransformerException JavaDoc {
99         // transform XML document
100
TransformerFactory JavaDoc transFactory = TransformerFactory.newInstance();
101         Transformer JavaDoc transformer = transFactory.newTransformer();
102         transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // otherwise there are no linebreaks
103
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
104         transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
105         
106         // output XML document
107
DOMSource JavaDoc domSrc = new DOMSource JavaDoc(xmlDoc);
108         StreamResult JavaDoc result = new StreamResult JavaDoc(responseWriter);
109         transformer.transform(domSrc, result);
110     }
111
112     /**
113      * creates the root element for the XML document containing namespace settings and schema location
114      * @param xmlDoc it should be the root element of this XML document
115      * @param nameRootElement the name of the root element
116      * @param resourceName name of the resource, so e.g. folder or document
117      * @param schemaFile name of the XML schema file belonging to this document
118      */

119     protected Element JavaDoc createRootElement(Document JavaDoc xmlDoc, String JavaDoc nameRootElement, String JavaDoc resourceName, String JavaDoc schemaFile) {
120         String JavaDoc namespace = namespaceUrlPrefix + resourceName;
121         Element JavaDoc rootElement = xmlDoc.createElement(nameRootElement);
122         rootElement.setAttribute("xmlns", namespace);
123         rootElement.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
124         rootElement.setAttribute("xsi:schemaLocation", namespace + " " + schemaLocation + schemaFile);
125         xmlDoc.appendChild(rootElement);
126         return rootElement;
127     }
128
129     /**
130      * creates a new element and adds it to the given parent element
131      * @param xmlDoc the XML document the element should belong to
132      * @param name the name of the element
133      * @param parentElement the parent element it should be added to as child
134      * @param namespace the namespace, can be also ""
135      */

136     protected Element JavaDoc createChildElement(Document JavaDoc xmlDoc, String JavaDoc name, Element JavaDoc parentElement, String JavaDoc namespace) {
137         if (xmlDoc == null)
138             return null;
139         Element JavaDoc newElement = xmlDoc.createElement(name);
140         newElement.setAttribute("xmlns", namespace);
141         if (parentElement != null)
142             parentElement.appendChild(newElement);
143         return newElement;
144     }
145
146     /**
147      * creates a new text node element and adds it to the parent element as a child
148      * @param xmlDoc the XML document the text node element should belong to
149      * @param elementName the name of the text node element
150      * @param parentElement the parent element it should be added to as child
151      * @param textValue content of the element
152      */

153     protected void createTextNodeElement(Document JavaDoc xmlDoc, String JavaDoc elementName, Element JavaDoc parentElement, String JavaDoc textValue) {
154         if (xmlDoc == null || parentElement == null)
155             return;
156         Element JavaDoc newElement = xmlDoc.createElement(elementName);
157         parentElement.appendChild(newElement);
158         Text JavaDoc textNode = xmlDoc.createTextNode(textValue);
159         newElement.appendChild(textNode);
160     }
161     
162     /**
163      * creates a new text node element and adds it to the parent element as a child
164      * @param xmlDoc the XML document the text node element should belong to
165      * @param elementName the name of the text node element
166      * @param parentElement the parent element it should be added to as child
167      * @param boolValue content of the element
168      */

169     protected void createTextNodeElement(Document JavaDoc xmlDoc, String JavaDoc elementName, Element JavaDoc parentElement, boolean boolValue) {
170         createTextNodeElement(xmlDoc, elementName, parentElement, (new Boolean JavaDoc(boolValue)).toString());
171     }
172     
173     /**
174      * creates a new text node element and adds it to the parent element as a child
175      * @param xmlDoc the XML document the text node element should belong to
176      * @param elementName the name of the text node element
177      * @param parentElement the parent element it should be added to as child
178      * @param intValue content of the element
179      */

180     protected void createTextNodeElement(Document JavaDoc xmlDoc, String JavaDoc elementName, Element JavaDoc parentElement, int intValue) {
181         createTextNodeElement(xmlDoc, elementName, parentElement, (new Integer JavaDoc(intValue)).toString());
182     }
183     
184     /** returns the response object */
185     public HttpServletResponse JavaDoc getResponse() {
186         return response;
187     }
188     
189     /** returns the HTTP status code property */
190     public int getHttpStatusCode() {
191         return httpStatusCode;
192     }
193
194     /** sets the HTTP status code property; not for external access */
195     protected void setHttpStatusCode(int p_httpStatusCode) {
196         httpStatusCode = p_httpStatusCode;
197     }
198     
199     /** returns, if request was successful */
200     public boolean isSuccessful() {
201         if (httpStatusCode == HttpStatusCodes.OK || httpStatusCode == HttpStatusCodes.CREATED)
202             return true;
203         else
204             return false;
205     }
206
207     /** converts a date from contineo's internal representation to a valid XML string */
208     protected String JavaDoc convertDateToXML(String JavaDoc date) {
209         return DateBean.convertDate("yyyyMMdd", "yyyy-MM-dd", date);
210
211     }
212     
213     /**
214      * adds the given message to the log files
215      */

216     protected void addLogMessage(String JavaDoc msg) {
217         if (logger.isEnabledFor(Level.ERROR))
218             logger.error(interfaceIdentifier + " - " + msg);
219     }
220 }
Popular Tags