KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > knowgate > http > HttpQueryServlet


1 /*
2   Copyright (C) 2003 Know Gate S.L. All rights reserved.
3                       C/Oņa, 107 1š2 28050 Madrid (Spain)
4
5   Redistribution and use in source and binary forms, with or without
6   modification, are permitted provided that the following conditions
7   are met:
8
9   1. Redistributions of source code must retain the above copyright
10      notice, this list of conditions and the following disclaimer.
11
12   2. The end-user documentation included with the redistribution,
13      if any, must include the following acknowledgment:
14      "This product includes software parts from hipergate
15      (http://www.hipergate.org/)."
16      Alternately, this acknowledgment may appear in the software itself,
17      if and wherever such third-party acknowledgments normally appear.
18
19   3. The name hipergate must not be used to endorse or promote products
20      derived from this software without prior written permission.
21      Products derived from this software may not be called hipergate,
22      nor may hipergate appear in their name, without prior written
23      permission.
24
25   This library is distributed in the hope that it will be useful,
26   but WITHOUT ANY WARRANTY; without even the implied warranty of
27   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
28
29   You should have received a copy of hipergate License with this code;
30   if not, visit http://www.hipergate.org or mail to info@hipergate.org
31 */

32
33 package com.knowgate.http;
34
35 import java.io.InputStream JavaDoc;
36 import java.io.IOException JavaDoc;
37 import java.io.FileNotFoundException JavaDoc;
38
39 import java.util.Properties JavaDoc;
40
41 import javax.servlet.*;
42 import javax.servlet.http.*;
43
44 import java.lang.System JavaDoc;
45 import java.util.StringTokenizer JavaDoc;
46
47 import java.sql.DriverManager JavaDoc;
48 import java.sql.SQLException JavaDoc;
49 import java.sql.Connection JavaDoc;
50 import java.sql.PreparedStatement JavaDoc;
51 import java.sql.ResultSet JavaDoc;
52
53 import com.knowgate.debug.DebugFile;
54 import com.knowgate.misc.Environment;
55 import com.knowgate.hipergate.QueryByForm;
56
57 /**
58  * <p>Get Query By Form results</p>
59  * @author Sergio Montoro Ten
60  * @version 1.0
61  * @see com.knowgate.hipergate.QueryByForm
62  */

63
64 public class HttpQueryServlet extends HttpServlet {
65
66   // -----------------------------------------------------------
67

68   private boolean isVoid(String JavaDoc sParam) {
69     if (null==sParam)
70       return true;
71     else
72       return (sParam.length()==0);
73   }
74
75   /**
76    * <p>Initialize Servlet Parameters</p>
77    * Take Database Driver, Conenction URL and User from /WEB-INF/web.xml.<br>
78    * If any parameter is not found then look it up at hipergate.cnf Properties
79    * file using Environment singleton.
80    * @throws ServletException
81    * @throws UnavailableException If jdbcDriverClassName parameter is not found
82    * and driver property at hipergate.cnf is not found or if jdbcURL parameter
83    * is not found and dburl property at hipergate.cnf is not found.
84    * @see com.knowgate.misc.Environment
85    */

86   public void init() throws ServletException {
87
88     ServletConfig config = getServletConfig();
89     jdbcDriverClassName = config.getInitParameter("jdbcDriverClassName");
90     jdbcURL = config.getInitParameter("jdbcURL");
91     dbUserName = config.getInitParameter("dbUserName");
92     dbUserPassword = config.getInitParameter("dbUserPassword");
93
94     if (isVoid(jdbcDriverClassName) || isVoid(jdbcURL) || isVoid(dbUserName) || isVoid(dbUserPassword)) {
95       Properties JavaDoc env = Environment.getProfile("hipergate");
96
97       if (isVoid(jdbcDriverClassName))
98         jdbcDriverClassName = env.getProperty("driver");
99
100       if (isVoid(jdbcURL))
101         jdbcURL = env.getProperty("dburl");
102
103       if (isVoid(dbUserName))
104         dbUserName = env.getProperty("dbuser");
105
106       if (isVoid(dbUserPassword))
107         dbUserPassword = env.getProperty("dbpassword");
108     }
109
110     if (jdbcDriverClassName == null || jdbcURL == null)
111       throw new UnavailableException("Init params missing");
112   } // init()
113

114
115   // -----------------------------------------------------------
116

117   /**
118    * <p>Get Query By Form results throught response output stream.</p>
119    * @param queryspec Name of XML file containing the Query Specification
120    * @param columnlist List of comma separated column names to retrieve
121    * @param where SQL WHERE clause to apply
122    * @param order by SQL ORDER BY clause to apply
123    * @param showas Output format. One of { "CSV" <i>(comma separated)</i>, "TSV" <i>(tabbed separated)</i>, "XLS" <i>(Excel)</i> }
124    * @throws IOException
125    * @throws FileNotFoundException
126    * @throws ServletException
127    */

128   public void doGet(HttpServletRequest request, HttpServletResponse response)
129      throws IOException JavaDoc, FileNotFoundException JavaDoc, ServletException
130      {
131      Class JavaDoc oDriver;
132      Connection JavaDoc oConn = null;
133      ServletOutputStream oOut = response.getOutputStream();
134      QueryByForm oQBF;
135      String JavaDoc sQuerySpec;
136      String JavaDoc sColumnList;
137      String JavaDoc sWhere;
138      String JavaDoc sOrderBy;
139      String JavaDoc sShowAs;
140      String JavaDoc sStorage;
141
142      if (DebugFile.trace) {
143        DebugFile.writeln("Begin HttpQueryServlet.doGet(...)");
144        DebugFile.incIdent();
145      }
146
147      sStorage = Environment.getProfileVar("hipergate", "storage");
148
149      if (DebugFile.trace) DebugFile.writeln("storage=" + sStorage);
150
151      try {
152        oDriver = Class.forName(jdbcDriverClassName);
153      }
154      catch (ClassNotFoundException JavaDoc ignore) {
155        oDriver = null;
156        if (DebugFile.trace) DebugFile.writeln("Class.forName(" + jdbcDriverClassName + ") : " + ignore.getMessage());
157        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database driver not found");
158      }
159
160      if (null==oDriver) return;
161
162      try {
163        if (DebugFile.trace) DebugFile.writeln("DriverManager.getConnection(" + jdbcURL + ",...)");
164
165        oConn = DriverManager.getConnection(jdbcURL,dbUserName,dbUserPassword);
166
167        sQuerySpec = request.getParameter("queryspec");
168        sColumnList = request.getParameter("columnlist");
169        if (null==sColumnList) sColumnList = "*";
170        sWhere = request.getParameter("where");
171        if (null==sWhere) sWhere = "1=1";
172        sOrderBy = request.getParameter("orderby");
173        if (null==sOrderBy) sOrderBy = "";
174        sShowAs = request.getParameter("showas");
175        if (null==sShowAs) sShowAs = "CSV";
176
177        if (DebugFile.trace) DebugFile.writeln("queryspec=" + sQuerySpec!=null ? sQuerySpec : "null");
178        if (DebugFile.trace) DebugFile.writeln("where=" + sWhere);
179        if (DebugFile.trace) DebugFile.writeln("orderby=" + sOrderBy);
180
181        oQBF = new QueryByForm("file://" + sStorage + "/qbf/" + sQuerySpec + ".xml");
182
183        // Send some basic http headers to support binary d/l.
184
if (sShowAs.equalsIgnoreCase("XLS")) {
185          response.setContentType("application/x-msexcel");
186          response.setHeader("Content-Disposition", "inline; filename=\"" + oQBF.getTitle(request.getLocale().getLanguage())+ " 1.csv\"");
187        }
188        else if (sShowAs.equalsIgnoreCase("CSV")) {
189          response.setContentType("text/plain");
190          response.setHeader("Content-Disposition","attachment; filename=\"" + oQBF.getTitle(request.getLocale().getLanguage())+ " 1.csv\"");
191        }
192        else if (sShowAs.equalsIgnoreCase("TSV")) {
193          response.setContentType("text/tab-separated-values");
194          response.setHeader("Content-Disposition","attachment; filename=\"" + oQBF.getTitle(request.getLocale().getLanguage())+ " 1.tsv\"");
195        }
196        else {
197          response.setContentType("text/plain");
198          response.setHeader("Content-Disposition", "inline; filename=\"" + oQBF.getTitle(request.getLocale().getLanguage())+ " 1.txt\"");
199        }
200
201        if (0==sOrderBy.length())
202          oQBF.queryToStream(oConn, sColumnList, oQBF.getBaseFilter(request) + " " + sWhere, oOut, sShowAs);
203        else
204          oQBF.queryToStream(oConn, sColumnList, oQBF.getBaseFilter(request) + " " + sWhere + " ORDER BY " + sOrderBy, oOut, sShowAs);
205
206        oConn.close();
207        oConn = null;
208
209        oOut.flush();
210      }
211      catch (SQLException JavaDoc e) {
212        if (DebugFile.trace) DebugFile.writeln("SQLException " + e.getMessage());
213        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
214      }
215      catch (ClassNotFoundException JavaDoc e) {
216        if (DebugFile.trace) DebugFile.writeln("ClassNotFoundException " + e.getMessage());
217        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
218      }
219      catch (IllegalAccessException JavaDoc e) {
220        if (DebugFile.trace) DebugFile.writeln("IllegalAccessException " + e.getMessage());
221        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
222      }
223      catch (Exception JavaDoc e) {
224        if (DebugFile.trace) DebugFile.writeln("Exception " + e.getMessage());
225        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
226      }
227      finally {
228        try { if(null!=oConn) if(!oConn.isClosed()) oConn.close(); }
229        catch (SQLException JavaDoc e) { if (DebugFile.trace) DebugFile.writeln("SQLException " + e.getMessage()); }
230      }
231
232      if (DebugFile.trace) {
233        DebugFile.decIdent();
234        DebugFile.writeln("End HttpQueryServlet.doGet()");
235      }
236    } // doGet()
237

238   // **********************************************************
239
// * Private Variables
240

241   private String JavaDoc jdbcDriverClassName;
242   private String JavaDoc jdbcURL;
243   private String JavaDoc dbUserName;
244   private String JavaDoc dbUserPassword;
245
246 }
Popular Tags