KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > xquark > servlet > bridge > XQBridgeServlet


1 /*
2  * This file belongs to the XQuark distribution. Copyright (C) 2003 Universite de Versailles Saint-Quentin.
3  *
4  * This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
5  *
6  * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
7  *
8  * You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307. You can also get it at http://www.gnu.org/licenses/lgpl.html
9  *
10  * For more information on this software, see http://www.xquark.org.
11  */

12
13 package org.xquark.servlet.bridge;
14
15 import java.io.*;
16 import java.net.MalformedURLException JavaDoc;
17 import java.util.HashMap JavaDoc;
18
19 import javax.servlet.ServletConfig JavaDoc;
20 import javax.servlet.ServletException JavaDoc;
21 import javax.servlet.http.HttpServlet JavaDoc;
22 import javax.servlet.http.HttpServletRequest JavaDoc;
23 import javax.servlet.http.HttpServletResponse JavaDoc;
24 import javax.xml.parsers.SAXParserFactory JavaDoc;
25
26 import org.xml.sax.SAXException JavaDoc;
27 import org.xml.sax.helpers.AttributesImpl JavaDoc;
28 import org.xquark.bridge.Mapper;
29 import org.xquark.bridge.Mapping;
30 import org.xquark.bridge.XQBridge;
31 import org.xquark.serialize.XMLSerializer;
32 import org.xquark.servlet.util.FileExtensionFilter;
33 import org.xquark.servlet.util.PostDataParser;
34 import org.xquark.xml.xdbc.*;
35
36 public class XQBridgeServlet extends HttpServlet JavaDoc {
37
38     private static final String JavaDoc JNDI_SOURCE = "java:comp/env/jdbc/TestDB";
39
40     private XQBridge bridge;
41
42     private SAXParserFactory JavaDoc factory;
43
44     private HashMap JavaDoc mappings;
45
46     public void init(ServletConfig JavaDoc config) throws ServletException JavaDoc {
47         super.init(config);
48         factory = SAXParserFactory.newInstance();
49         factory.setNamespaceAware(true);
50         bridge = new XQBridge("jndi:" + JNDI_SOURCE);
51         mappings = loadMappingsFromFiles(config.getServletContext().getRealPath("/WEB-INF/mappings"));
52     }
53
54     public void doGet(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException {
55         PrintWriter out = response.getWriter();
56         XMLConnection conn = null;
57         try {
58             String JavaDoc query = request.getParameter("exec");
59             if (query != null) {
60                 conn = bridge.getXMLConnection();
61                 execQuery(conn, query, out);
62             } else {
63                 reportError(response, "Unrecognized command: <B>" + request.getContextPath() + request.getServletPath() + request.getQueryString() + "</B>.", "query.jsp");
64                 return;
65             }
66         } catch (XMLDBCException e) {
67             reportException(response, e, "query.jsp");
68         } finally {
69             out.close();
70             if (conn != null)
71                 try {
72                     conn.close();
73                 } catch (XMLDBCException e) {
74                     // ignore
75
}
76         }
77     }
78
79     public void doPost(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException {
80         PrintWriter out = response.getWriter();
81         String JavaDoc mapping = null;
82         String JavaDoc file = null;
83         if (request.getContentType().startsWith("multipart/form-data;")) {
84             PostDataParser poster = new PostDataParser(request);
85             mapping = poster.getParameter("mapping");
86             file = poster.getFileContent("file");
87         } else if (request.getContentType().equals("application/x-www-form-urlencoded")) {
88             mapping = request.getParameter("mapping");
89             file = request.getParameter("file");
90         } else {
91             reportError(response, "Unknown content type: " + request.getContentType(), "insert.jsp");
92             return;
93         }
94         if (mapping == null || file == null) {
95             reportError(response, "Missing parameters for file insertion", "insert.jsp");
96         } else {
97             Mapping map = null;
98             Mapper mapper = null;
99             try {
100                 String JavaDoc mapFile = (String JavaDoc) mappings.get(mapping);
101                 map = bridge.getMapping(mapFile);
102                 mapper = map.getMapper();
103                 mapper.setDocumentBase("file:/c:/");
104                 mapper.insertDocument(file);
105                 reportMessage(response, "Document inserted successfully.", "insert.jsp");
106             } catch (SAXException JavaDoc ex) {
107                 if (ex.getException() != null)
108                     reportException(response, ex.getException(), "insert.jsp");
109                 else
110                     reportException(response, ex, "insert.jsp");
111             } catch (Exception JavaDoc ex) {
112                 reportException(response, ex, "insert.jsp");
113             } finally {
114                 try {
115                     if (mapper != null)
116                         mapper.close();
117                 } catch (XMLDBCException e) {
118                 }
119                 try {
120                     if (map != null)
121                         map.close();
122                 } catch (XMLDBCException e) {
123                 }
124             }
125         }
126     }
127
128     private HashMap JavaDoc loadMappingsFromFiles(String JavaDoc realPath) {
129         HashMap JavaDoc result = new HashMap JavaDoc();
130         FileFilter mapFilter = new FileExtensionFilter(".map");
131         File mappingsDir = new File(realPath);
132         File[] mapDirs = mappingsDir.listFiles();
133         for (int i = 0; i < mapDirs.length; i++) {
134             File mapDir = mapDirs[i];
135             if (mapDir.isDirectory()) {
136                 File[] mapFiles = mapDir.listFiles(mapFilter);
137                 if (mapFiles.length > 0) {
138                     String JavaDoc mapFile = null;
139                     try {
140                         mapFile = mapFiles[0].toURL().toString();
141                         Mapping mapping = bridge.getMapping(mapFile);
142                         result.put(mapDir.getName(), mapFile);
143                     } catch (MalformedURLException JavaDoc ex) {
144                         log("Error while loading mapping file: " + mapFile, ex);
145                     } catch (XMLDBCException ex) {
146                         log("Error while loading mapping file: " + mapFile, ex);
147                     }
148                 }
149             }
150         }
151         return result;
152     }
153
154     private void execQuery(XMLConnection conn, String JavaDoc query, PrintWriter out) throws ServletException JavaDoc, XMLDBCException {
155         XMLStatement stmt = null;
156         XMLResultSet xrs = null;
157         try {
158             stmt = conn.createStatement();
159             xrs = stmt.executeQuery(query);
160             XMLSerializer serializer = new XMLSerializer(out, "iso-8859-1");
161             xrs.setContentHandler(serializer);
162             xrs.setLexicalHandler(serializer);
163             serializer.startDocument();
164             //serializer.processingInstruction("xml-stylesheet", "href=\"xsl/beautify.xsl\" type=\"text/xsl\"");
165
serializer.startElement("", "results", "results", new AttributesImpl JavaDoc());
166             while (xrs.hasNext())
167                 xrs.nextAsSAX();
168             serializer.endElement("", "results", "results");
169             serializer.endDocument();
170         } catch (SAXException JavaDoc e) {
171             throw new ServletException JavaDoc("Error while producing document result", e);
172         } finally {
173             if (xrs != null)
174                 xrs.close();
175             if (stmt != null)
176                 stmt.close();
177         }
178     }
179
180     private void reportMessage(HttpServletResponse JavaDoc response, String JavaDoc message, String JavaDoc url) throws IOException {
181         response.sendRedirect(response.encodeRedirectURL("info.jsp?url=" + url + "&message=" + message));
182     }
183
184     private void reportError(HttpServletResponse JavaDoc response, String JavaDoc error, String JavaDoc url) throws IOException {
185         response.sendRedirect(response.encodeRedirectURL("error.jsp?url=" + url + "&message=" + error));
186     }
187
188     private void reportException(HttpServletResponse JavaDoc response, Exception JavaDoc e, String JavaDoc url) throws IOException {
189         /*
190          * StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String message = " <pre> "+sw.toString()+" </pre> "; response.sendRedirect(response.encodeRedirectURL("exception.jsp?url="+url+"&message="+message));
191          */

192         PrintWriter out = response.getWriter();
193         out.println("<html><body><pre>");
194         e.printStackTrace(out);
195         out.println("</pre></body></html>");
196     }
197 }
Popular Tags