KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openbravo > base > HttpBaseServlet


1 /*
2  ************************************************************************************
3  * Copyright (C) 2001-2006 Openbravo S.L.
4  * Licensed under the Apache Software License version 2.0
5  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6  * Unless required by applicable law or agreed to in writing, software distributed
7  * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
8  * CONDITIONS OF ANY KIND, either express or implied. See the License for the
9  * specific language governing permissions and limitations under the License.
10  ************************************************************************************
11 */

12 package org.openbravo.base;
13
14 import org.openbravo.xmlEngine.XmlEngine;
15 import org.openbravo.data.FieldProvider;
16
17 import java.sql.*;
18 import java.io.*;
19 import javax.servlet.*;
20 import javax.servlet.http.*;
21 import java.util.*;
22 import org.xml.sax.*;
23 import org.apache.fop.messaging.*;
24 import org.apache.fop.apps.Driver;
25 import org.apache.log4j.Logger;
26 import org.apache.log4j.PropertyConfigurator;
27 import java.rmi.*;
28 import rmi.*;
29 import org.openbravo.utils.FormatUtilities;
30 import org.openbravo.database.*;
31 import org.openbravo.exception.*;
32 import org.apache.commons.pool.ObjectPool;
33
34 import org.apache.avalon.framework.logger.Log4JLogger;
35
36 import javax.net.ssl.*;
37
38 public class HttpBaseServlet extends HttpServlet implements ConnectionProvider
39 {
40   protected static PeriodicGarbageCollector myGc;
41   protected static ConnectionProviderImpl myPool;
42   public String JavaDoc strBaseConfigPath;
43   public String JavaDoc strBaseDesignPath;
44   public String JavaDoc strDefaultDesignPath;
45   public String JavaDoc strDireccion;
46   public String JavaDoc strReplaceWith;
47   public String JavaDoc strReplaceWithFull;
48   private String JavaDoc strLocalReplaceWith;
49   public String JavaDoc strFopConfig;
50   public String JavaDoc strGarbageCollectionTime;
51   protected static String JavaDoc strBBDD;
52   public String JavaDoc strVersion;
53   public String JavaDoc strParentVersion;
54   protected static String JavaDoc prefix = null;
55   protected static String JavaDoc strContext = null;
56   protected static String JavaDoc strSystemLanguage;
57   protected static String JavaDoc strFileProperties;
58   protected static String JavaDoc strFileSeparator;
59   protected static String JavaDoc strDefaultServlet;
60   public XmlEngine xmlEngine=null;
61   public Logger log4j = Logger.getLogger(this.getClass());
62   protected static Log4JLogger logger;
63   String JavaDoc strServidorRenderFo = "";
64   protected static String JavaDoc stcFileProperties = null;
65   protected String JavaDoc PoolFileName;
66
67   public void init (ServletConfig config) {
68     try {
69       super.init(config);
70       strBaseConfigPath = config.getServletContext().getInitParameter("BaseConfigPath");
71       if (prefix == null) {
72         prefix = config.getServletContext().getRealPath("/");
73         if (log4j.isDebugEnabled()) log4j.debug("************************prefix: " + prefix);
74         if (strContext==null || strContext.equals("")) {
75           String JavaDoc path = "/";
76           int secondPath = -1;
77           int firstPath = prefix.lastIndexOf(path);
78           if (firstPath==-1) {
79             path = "\\";
80             firstPath = prefix.lastIndexOf(path);
81           }
82           if (firstPath!=-1) {
83             secondPath = prefix.lastIndexOf(path, firstPath-1);
84             strContext = prefix.substring(secondPath+1, firstPath);
85           }
86         }
87         if (log4j.isDebugEnabled()) log4j.debug("context: " + strContext);
88         String JavaDoc file = config.getServletContext().getInitParameter("log4j-init-file");
89         if (log4j.isDebugEnabled()) log4j.debug("Log file: " + file);
90         // if the log4j-init-file is not set, then no point in trying
91
if(file != null) {
92           //PropertyConfigurator.configure(prefix+file);
93
PropertyConfigurator.configure(prefix + "/" + strBaseConfigPath + "/" + file);
94         }
95       }
96       stcFileProperties = prefix + "/" + strBaseConfigPath + "/" + "Openbravo.properties";
97       logger = new Log4JLogger(log4j);
98       MessageHandler.setQuiet(true);
99       MessageHandler.setScreenLogger(logger);
100       String JavaDoc strFileFormat = config.getServletContext().getInitParameter("FormatFile");
101       strFopConfig = config.getServletContext().getInitParameter("FOPConfig");
102       strBaseDesignPath = config.getServletContext().getInitParameter("BaseDesignPath");
103       strDefaultDesignPath = config.getServletContext().getInitParameter("DefaultDesignPath");
104       strDefaultServlet = config.getServletContext().getInitParameter("DefaultServlet");
105       strGarbageCollectionTime = config.getServletContext().getInitParameter("GarbageCollectionTime");
106       log4j.info("BaseConfigPath: " + strBaseConfigPath);
107       log4j.info("BaseDesignPath: " + strBaseDesignPath);
108       strVersion = config.getServletContext().getInitParameter("Version");
109       strParentVersion = config.getServletContext().getInitParameter("Parent_Version");
110       try {
111         strSystemLanguage = System.getProperty("user.language") + "_" + System.getProperty("user.country");
112       } catch (java.security.AccessControlException JavaDoc err) {
113         log4j.warn(err.getMessage());
114         strSystemLanguage = "en_US";
115       }
116       try {
117         strFileSeparator = System.getProperty("file.separator");
118       } catch (java.security.AccessControlException JavaDoc err) {
119         log4j.warn(err.getMessage());
120         strFileSeparator = "/";
121       }
122       try {
123         strFileProperties = System.getProperty("user.home") + strFileSeparator + "TAD.properties";
124       } catch (java.security.AccessControlException JavaDoc err) {
125         log4j.warn(err.getMessage());
126         strFileProperties = "";
127       }
128       xmlEngine = new XmlEngine();
129       xmlEngine.fileBaseLocation = new File(prefix + "/" + strBaseDesignPath);
130       xmlEngine.strReplaceWhat = config.getServletContext().getInitParameter("ReplaceWhat");
131       strLocalReplaceWith = config.getServletContext().getInitParameter("ReplaceWith");
132       xmlEngine.strReplaceWith = strLocalReplaceWith;
133       log4j.info("Replace attribute value: \"" + xmlEngine.strReplaceWhat + "\" with: \"" + xmlEngine.strReplaceWith + "\".");
134       xmlEngine.strTextDividedByZero = config.getServletContext().getInitParameter("TextDividedByZero");
135       xmlEngine.fileXmlEngineFormat = new File (prefix + "/" + strBaseConfigPath + "/" + strFileFormat);
136       xmlEngine.initialize();
137       strServidorRenderFo = config.getServletContext().getInitParameter("ServidorRenderFo");
138
139       log4j.info("Text of divided by zero: " + xmlEngine.strTextDividedByZero);
140
141       if(myPool == null) {
142         try {
143           PoolFileName = config.getServletContext().getInitParameter("PoolFile");
144           makeConnection();
145         } catch (Exception JavaDoc ex) {
146           ex.printStackTrace();
147         }
148       }
149       if((myGc == null)&&(strGarbageCollectionTime!=null && !strGarbageCollectionTime.equals(""))) { // Only created by first servlet to call
150
try {
151           String JavaDoc garbageCollectionTime = strGarbageCollectionTime;
152           log4j.info("garbageCollectionTime: " + garbageCollectionTime);
153
154           PeriodicGarbageCollector myLocalGc = new PeriodicGarbageCollector(Long.parseLong(garbageCollectionTime));
155           if (myLocalGc==null)
156             log4j.error("Could not start the garbage collector: ");
157           myGc = myLocalGc;
158         }
159         catch (Exception JavaDoc e) {
160           e.printStackTrace();
161         }
162       }
163     } catch (ServletException e) {
164       e.printStackTrace();
165     }
166   }
167
168   public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
169     strDireccion = HttpBaseUtils.getLocalAddress(request);
170     String JavaDoc strActualUrl = HttpBaseUtils.getLocalHostAddress(request);
171     log4j.info("Server name: " + strActualUrl);
172     HttpSession session = request.getSession(true);
173     String JavaDoc strLanguage = "";
174     try {
175       strLanguage = (String JavaDoc) session.getAttribute("#AD_LANGUAGE");
176       if (strLanguage==null || strLanguage.trim().equals("")) strLanguage = "";
177     }
178     catch (Exception JavaDoc e) {
179       strLanguage = "";
180     }
181     if (strBaseDesignPath.endsWith("/")) strDefaultDesignPath = strDefaultDesignPath.substring(0, strDefaultDesignPath.length()-1);
182     log4j.info("*********************Base path: " + strBaseDesignPath);
183     String JavaDoc strNewAddBase = strDefaultDesignPath;
184     String JavaDoc strFinal = strBaseDesignPath;
185     if (!strLanguage.equals("") && !strLanguage.equals("en_US")) strNewAddBase = strLanguage;
186     if (!strFinal.endsWith("/" + strNewAddBase)) strFinal += "/" + strNewAddBase;
187     log4j.info("*********************Base path: " + strFinal);
188     xmlEngine.fileBaseLocation = new File(prefix + "/" + strFinal);
189     strReplaceWith = strLocalReplaceWith.replace("@actual_url_context@", strDireccion);
190     strReplaceWith = strReplaceWith.replace("@actual_url@", strActualUrl);
191     strReplaceWithFull = strReplaceWith;
192     strReplaceWith = HttpBaseUtils.getRelativeUrl(request, strReplaceWith);
193     log4j.info("xmlEngine.strReplaceWith: " + strReplaceWith);
194     xmlEngine.strReplaceWith = strReplaceWith;
195
196     log4j.info("Call to HttpServlet.service");
197     super.service(request,response);
198   }
199
200   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
201     doPost(request,response);
202   }
203
204   public void doGetCall(HttpServletRequest request, HttpServletResponse response) throws Exception JavaDoc {
205     doPostCall(request, response);
206   }
207
208   public void doPostCall(HttpServletRequest request, HttpServletResponse response) throws Exception JavaDoc {
209     return;
210   }
211
212   public static String JavaDoc getJavaDateTimeFormat() {
213     String JavaDoc javaDateTimeFormat = "dd-MM-yyyy HH:mm:ss";
214     Properties properties = new Properties();
215     try {
216       properties.load(new FileInputStream(stcFileProperties));
217       System.out.println("***************"+stcFileProperties);
218       javaDateTimeFormat = properties.getProperty("dateTimeFormat.java");
219     } catch (IOException e) {
220       // catch possible io errors from readLine()
221
System.out.println("Uh oh, got an IOException error!");
222       e.printStackTrace();
223     }
224     return javaDateTimeFormat;
225   }
226
227
228   /* Database access utilities
229   */

230   public static ConnectionProviderImpl getPoolWS() throws PoolNotFoundException {
231     if (myPool == null)
232       throw new PoolNotFoundException("Default pool not found");
233     else
234       return myPool;
235   }
236   private ObjectPool getPool(String JavaDoc poolName) throws PoolNotFoundException {
237     if (myPool == null)
238       throw new PoolNotFoundException("Default pool not found");
239     else
240       return myPool.getPool(poolName);
241   }
242
243   private ObjectPool getPool() throws PoolNotFoundException {
244     if (myPool == null)
245       throw new PoolNotFoundException("Default pool not found");
246     else
247       return myPool.getPool();
248   }
249
250   public Connection getConnection() throws NoConnectionAvailableException {
251     return (myPool.getConnection());
252   }
253
254   public String JavaDoc getRDBMS() {
255     return (myPool.getRDBMS());
256   }
257
258   public Connection getTransactionConnection() throws NoConnectionAvailableException, SQLException {
259     return myPool.getTransactionConnection();
260   }
261
262   public void releaseCommitConnection(Connection conn) throws SQLException {
263     myPool.releaseCommitConnection(conn);
264   }
265
266   public void releaseRollbackConnection(Connection conn) throws SQLException {
267     myPool.releaseRollbackConnection(conn);
268   }
269
270   public PreparedStatement getPreparedStatement(String JavaDoc poolName, String JavaDoc strSql) throws Exception JavaDoc {
271     return (myPool.getPreparedStatement(poolName, strSql));
272   }
273
274   public PreparedStatement getPreparedStatement(String JavaDoc strSql) throws Exception JavaDoc {
275     return (myPool.getPreparedStatement(strSql));
276   }
277
278   public PreparedStatement getPreparedStatement(Connection conn, String JavaDoc strSql) throws SQLException {
279     return (myPool.getPreparedStatement(conn, strSql));
280   }
281
282   public void releasePreparedStatement(PreparedStatement preparedStatement) throws SQLException {
283     myPool.releasePreparedStatement(preparedStatement);
284   }
285
286   public Statement getStatement(String JavaDoc poolName) throws Exception JavaDoc {
287     return (myPool.getStatement(poolName));
288   }
289
290   public Statement getStatement() throws Exception JavaDoc {
291     return (myPool.getStatement());
292   }
293
294   public Statement getStatement(Connection conn) throws SQLException {
295     return (myPool.getStatement(conn));
296   }
297
298   public void releaseStatement(Statement statement) throws SQLException {
299     myPool.releaseStatement(statement);
300   }
301
302   public void releaseTransactionalStatement(Statement statement) throws SQLException {
303     myPool.releaseTransactionalStatement(statement);
304   }
305
306   public void releaseTransactionalPreparedStatement(PreparedStatement preparedStatement) throws SQLException {
307     myPool.releaseTransactionalPreparedStatement(preparedStatement);
308   }
309
310   public CallableStatement getCallableStatement(String JavaDoc poolName, String JavaDoc strSql) throws Exception JavaDoc {
311     return (myPool.getCallableStatement(poolName, strSql));
312   }
313
314   public CallableStatement getCallableStatement(String JavaDoc strSql) throws Exception JavaDoc {
315     return (myPool.getCallableStatement(strSql));
316   }
317
318   public CallableStatement getCallableStatement(Connection conn, String JavaDoc strSql) throws SQLException {
319     return (myPool.getCallableStatement(conn, strSql));
320   }
321
322   public void releaseCallableStatement(CallableStatement callableStatement) throws SQLException {
323     myPool.releaseCallableStatement(callableStatement);
324   }
325
326
327   public String JavaDoc getPoolStatus() {
328     return myPool.getStatus();
329   }
330
331   /**
332    * renders an FO inputsource into a PDF file which is rendered
333    * directly to the response object's OutputStream
334    */

335   public void renderFO(String JavaDoc strFo, HttpServletResponse response) throws ServletException {
336     // Check validity of the certificate
337
// Create a trust manager that does not validate certificate chains
338
TrustManager[] trustAllCerts = new TrustManager[] {
339       new X509TrustManager() {
340         public java.security.cert.X509Certificate JavaDoc[] getAcceptedIssuers() {return null;}
341
342         public void checkClientTrusted(java.security.cert.X509Certificate JavaDoc[] certs, String JavaDoc authType) {}
343         public void checkServerTrusted(java.security.cert.X509Certificate JavaDoc[] certs, String JavaDoc authType) {}
344         public boolean isServerTrusted(java.security.cert.X509Certificate JavaDoc[] cert) {return true;}
345         public boolean isClientTrusted(java.security.cert.X509Certificate JavaDoc[] cert) {return true;}
346       }
347     };
348     // Install the all-trusting trust manager
349
try {
350       SSLContext sc = SSLContext.getInstance("SSL");
351       sc.init(null, trustAllCerts, new java.security.SecureRandom JavaDoc());
352       HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
353     } catch (Exception JavaDoc e) {
354     }
355
356     try {
357       log4j.info("Beginning of renderFO");
358       if (strBaseDesignPath!=null && strFopConfig!=null) {
359         File fopFile = new File(prefix + "/" + strBaseConfigPath + "/" + strFopConfig);
360         if (fopFile.exists()) {
361           org.apache.fop.apps.Options options = new org.apache.fop.apps.Options(new File(prefix + "/" + strBaseConfigPath + "/" + strFopConfig));
362         }
363       }
364       strFo = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + strFo;
365
366       if ((strServidorRenderFo==null) || (strServidorRenderFo.equals(""))) {
367         if (log4j.isDebugEnabled()) log4j.debug(strFo);
368         StringReader sr = new StringReader(strFo);
369         if (log4j.isDebugEnabled()) log4j.debug(sr.toString());
370         InputSource inputFO = new InputSource(sr);
371
372         //log4j.info("Beginning of ByteArrayOutputStream");
373
log4j.info("Beginning of response.setContentType");
374         response.setContentType("application/pdf; charset=UTF-8");
375         log4j.info("Beginning of driver");
376         Driver driver = new Driver();
377         driver.setLogger(logger);
378         driver.setRenderer(Driver.RENDER_PDF);
379         driver.setInputSource(inputFO);
380
381         //ByteArrayOutputStream out = new ByteArrayOutputStream();
382
driver.setOutputStream(response.getOutputStream());
383
384         log4j.info("driver.run()");
385         driver.run();
386         /*log4j.info("Beginning of out.toByteArray()");
387           byte[] content = out.toByteArray();
388           log4j.info("Beginning of response.setContentLength");
389           response.setContentLength(content.length);
390           log4j.info("Beginning of response.getOutputStream().write(content)");*/

391         /*int incr = 1000;
392           for (int i=0;i<content.length;i+=incr) {
393           int end = ((content.length<(i+incr))?content.length-i:incr);
394           response.getOutputStream().write(content, i, end);
395           response.getOutputStream().flush();
396           }*/

397         /*response.getOutputStream().write(content);
398           log4j.info("Beginning of response.getOutputStream().flush()");
399           response.getOutputStream().flush();*/

400         log4j.info("End of renderFO");
401         response.getOutputStream().flush();
402         response.getOutputStream().close();
403         sr.close();
404         driver.reset();
405         driver = null;
406       } else {
407         response.setContentType("application/pdf; charset=UTF-8");
408         RenderFoI render = (RenderFoI) Naming.lookup("rmi://"+strServidorRenderFo+"/RenderFo");
409
410         byte[] content = render.computeRenderFo(strFo);
411         response.setContentLength(content.length);
412         /*int incr = 1000;
413           for (int i=0;i<content.length;i+=incr) {
414           int end = ((content.length<(i+incr))?content.length-i:incr);
415           response.getOutputStream().write(content, i, end);
416           response.getOutputStream().flush();
417           }*/

418         response.getOutputStream().write(content);
419         response.getOutputStream().flush();
420       }
421     } catch (java.lang.IllegalStateException JavaDoc il) {
422       return;
423     } catch (Exception JavaDoc ex) {
424       try { response.getOutputStream().flush(); } catch (Exception JavaDoc ignored) {}
425       throw new ServletException(ex);
426     }
427   }
428
429   static XMLReader createParser() throws ServletException {
430     String JavaDoc parserClassName = System.getProperty("org.xml.sax.parser");
431     if (parserClassName == null) {
432       parserClassName = "org.apache.xerces.parsers.SAXParser";
433     }
434     try {
435       return (XMLReader) Class.forName(
436           parserClassName).newInstance();
437     } catch (Exception JavaDoc e) {
438       throw new ServletException(e);
439     }
440   }
441
442   public String JavaDoc arrayDobleEntrada(String JavaDoc strNombreArray, FieldProvider[] data) {
443     String JavaDoc strArray = "var " + strNombreArray + " = ";
444     if (data.length==0) {
445       strArray = strArray + "null";
446       return strArray;
447     }
448     strArray = strArray + "new Array(";
449     for (int i=0;i<data.length;i++) {
450       strArray = strArray + "\nnew Array(\"" + data[i].getField("padre") + "\", \"" + data[i].getField("id") + "\", \"" + FormatUtilities.replaceJS(data[i].getField("name")) + "\")";
451       if (i<data.length-1) strArray = strArray + ", ";
452     }
453     strArray = strArray + ");";
454     return strArray;
455   }
456
457   public String JavaDoc arrayEntradaSimple(String JavaDoc strNombreArray, FieldProvider[] data) {
458     String JavaDoc strArray = "var " + strNombreArray + " = ";
459     if (data.length==0) {
460       strArray = strArray + "null";
461       return strArray;
462     }
463     strArray = strArray + "new Array(";
464     for (int i=0;i<data.length;i++) {
465       strArray = strArray + "\nnew Array(\"" + data[i].getField("id") + "\", \"" + FormatUtilities.replaceJS(data[i].getField("name")) + "\")";
466       if (i<data.length-1) strArray = strArray + ", ";
467     }
468     strArray = strArray + ");";
469     return strArray;
470   }
471
472   public void makeConnection() throws PoolNotFoundException {
473     if (myPool != null) {
474       try {
475         myPool.destroy();
476       } catch (Exception JavaDoc ignored) {}
477       myPool = null;
478     }
479     try {
480       String JavaDoc strPoolFile = prefix + "/" + strBaseConfigPath + "/" + PoolFileName;
481       myPool = new ConnectionProviderImpl(strPoolFile, (!strPoolFile.startsWith("/") && !strPoolFile.substring(1,1).equals(":")), strContext);
482     } catch (Exception JavaDoc e) {
483       throw new PoolNotFoundException(e.getMessage());
484     }
485   }
486
487   public String JavaDoc getServletInfo() {
488     return "This servlet add some functions (connection to data base, xmlEngine, loging) over HttpServlet";
489   }
490 }
491
Popular Tags