View Javadoc

1   /*
2    * $Header: /cvsroot/jdbforms/dbforms/src/org/dbforms/servlets/ConfigServlet.java,v 1.41 2006/02/25 20:48:34 nicparise Exp $
3    * $Revision: 1.41 $
4    * $Date: 2006/02/25 20:48:34 $
5    *
6    * DbForms - a Rapid Application Development Framework
7    * Copyright (C) 2001 Joachim Peer <joepeer@excite.com>
8    *
9    * This library is free software; you can redistribute it and/or
10   * modify it under the terms of the GNU Lesser General Public
11   * License as published by the Free Software Foundation; either
12   * version 2.1 of the License, or (at your option) any later version.
13   *
14   * This library is distributed in the hope that it will be useful,
15   * but WITHOUT ANY WARRANTY; without even the implied warranty of
16   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17   * Lesser General Public License for more details.
18   *
19   * You should have received a copy of the GNU Lesser General Public
20   * License along with this library; if not, write to the Free Software
21   * Foundation, Inc., 59 Temaple Place, Suite 330, Boston, MA  02111-1307 USA
22   */
23  
24  package org.dbforms.servlets;
25  
26  import org.apache.commons.lang.StringUtils;
27  import org.apache.commons.logging.Log;
28  import org.apache.commons.logging.LogFactory;
29  
30  import org.apache.commons.validator.ValidatorResources;
31  import org.apache.commons.validator.ValidatorResourcesInitializer;
32  
33  import org.apache.log4j.LogManager;
34  import org.apache.log4j.PropertyConfigurator;
35  import org.apache.log4j.xml.DOMConfigurator;
36  
37  import org.dbforms.config.ConfigLoader;
38  import org.dbforms.config.DbFormsConfig;
39  import org.dbforms.config.DbFormsConfigRegistry;
40  import org.dbforms.config.DbFormsErrors;
41  
42  import org.dbforms.util.MessageResources;
43  import org.dbforms.util.Util;
44  
45  import org.dbforms.validation.ValidatorConstants;
46  
47  import org.xml.sax.SAXException;
48  
49  import java.io.IOException;
50  import java.io.InputStream;
51  import java.io.PrintWriter;
52  
53  import java.util.Properties;
54  
55  import javax.servlet.ServletException;
56  import javax.servlet.UnavailableException;
57  import javax.servlet.http.HttpServlet;
58  import javax.servlet.http.HttpServletRequest;
59  import javax.servlet.http.HttpServletResponse;
60  
61  
62  
63  /***
64   * This Servlet runs at application startup and reads the XML configuration in
65   * dbforms-config.xml, populates a DbFormsConfig - Object and stores it in
66   * application context.
67   *
68   * @author Joe Peer
69   */
70  public class ConfigServlet extends HttpServlet {
71     /*** DOCUMENT ME! */
72     private static Log logCat;
73  
74     // ----------------------------------------------------- Instance Variables
75     private transient ConfigLoader loader = new ConfigLoader();
76  
77     // ---------------------------------------------------- HttpServlet Methods
78  
79     /***
80      * Gracefully shut down this controller servlet, releasing any resources
81      * that were allocated at initialization.
82      */
83     public void destroy() {
84        log("finalizing");
85     }
86  
87  
88     /***
89      * Process an HTTP "GET" request.
90      *
91      * @param request The servlet request we are processing
92      * @param response The servlet response we are creating
93      *
94      * @exception IOException if an input/output error occurs
95      * @exception ServletException if a servlet exception occurs
96      */
97     public void doGet(HttpServletRequest  request,
98                       HttpServletResponse response)
99                throws IOException, ServletException {
100       process(request, response);
101    }
102 
103 
104    /***
105     * Process an HTTP "POST" request.
106     *
107     * @param request The servlet request we are processing
108     * @param response The servlet response we are creating
109     *
110     * @exception IOException if an input/output error occurs
111     * @exception ServletException if a servlet exception occurs
112     */
113    public void doPost(HttpServletRequest  request,
114                       HttpServletResponse response)
115                throws IOException, ServletException {
116       process(request, response);
117    }
118 
119 
120    /***
121     * Initialize this servlet.
122     *
123     * @exception ServletException if we cannot configure ourselves correctly
124     */
125    public void init() throws ServletException {
126       try {
127          initLogging();
128 
129          loader.setFieldClassName(getServletConfig().getInitParameter("className.Field"));
130          loader.setTableClassName(getServletConfig().getInitParameter("className.Table"));
131          loader.setQueryClassName(getServletConfig().getInitParameter("className.Query"));
132          loader.setForeignKeyClassName(getServletConfig().getInitParameter("className.ForeignKey"));
133          loader.setReferenceClassName(getServletConfig().getInitParameter("className.Reference"));
134 
135          initXMLConfig();
136          initXMLErrors();
137          initXMLValidator();
138          initApplicationResources();
139          initLocaleKey();
140       } catch (IOException ioe) {
141          ioe.printStackTrace();
142       } catch (Exception e) {
143          e.printStackTrace();
144       }
145    }
146 
147 
148    /***
149     * Initialize Logging for this web application a url/path to a log4j
150     * properties or xml file should be defined by the servlet init parameter
151     * "log4j.configuration"
152     */
153    public void initLogging() {
154       String  configurationStr = this.getServletConfig()
155                                      .getInitParameter("log4j.configuration");
156       boolean usingURL = true;
157 
158       if (!Util.isNull(configurationStr)) {
159          try {
160             //Works fine with Tomcat 4.1.27 and Weblogic
161             InputStream fis = getServletContext()
162                                  .getResourceAsStream(configurationStr);
163 
164             if (fis != null) {
165                try {
166             	   LogManager.resetConfiguration();
167             	   if (configurationStr.endsWith(".xml")) {
168             		  // log4j config in xml format
169             		  new DOMConfigurator().doConfigure(fis,LogManager.getLoggerRepository());
170             	   }
171             	   else {
172             	      // log4j config in properties format
173             		  Properties log4jProperties = new Properties();
174 	                  log4jProperties.load(fis);	                  
175 	                  PropertyConfigurator.configure(log4jProperties);
176             	   }
177                } finally {
178                   fis.close();
179                }
180             } else {
181                System.err.println("ConfigServlet::initLogging - log4j.configuration not found!");
182             }
183          } catch (IOException e) {
184             System.err.println("ConfigServlet::initLogging - log4j.properties not found!");
185 
186             PropertyConfigurator.configure(configurationStr);
187             usingURL = false;
188          }
189 
190          logCat = LogFactory.getLog(ConfigServlet.class.getName());
191          // logging category for this class
192          logCat.info("### LOGGING INITALIZED, USING URL: " + usingURL + " ###"
193                      + configurationStr);
194       }  else {
195           logCat = LogFactory.getLog(ConfigServlet.class.getName());
196           // logging category for this class
197           logCat.info("### LOGGING INITALIZED, USING DEFAULT CONFIGURATION.");
198        }
199    }
200 
201 
202    /***
203     * Initialize the SubClass information use by the ResourceBundle for this
204     * application. ATTENTION: Here the "application" it's use as Class name,
205     * not like path/file coordonnates. (see java.util.ResourceBundle)
206     *
207     * @exception IOException if an input/output error is encountered
208     * @exception ServletException if we cannot initialize these resources
209     */
210    protected void initApplicationResources() {
211       logCat.info("initialize Application Resources.");
212 
213       String value = getServletConfig()
214                         .getInitParameter(ValidatorConstants.RESOURCE_BUNDLE);
215 
216       if (value == null) {
217          logCat.warn(" Application Resources file not setted in Web.xml, ApplicationResources handler disabled!");
218 
219          return;
220       }
221 
222       MessageResources.setSubClass(value);
223 
224       logCat.info(" DbForms Application Resources : SubClass initialized ");
225    }
226 
227 
228    /***
229     * Initialize the Locale key for Session scope. Usefull for sharing the same
230     * Locale across different framework. Ex: By setting "localeKey" to
231     * "org.apache.struts.action.LOCALE" you can share the same Locale in the
232     * session scope with Struts.
233     */
234    protected void initLocaleKey() {
235       logCat.info("initialize Locale Key for session attribute.");
236 
237       String value = getServletConfig()
238                         .getInitParameter("localeKey");
239 
240       if (value == null) {
241          logCat.warn(" Locale Key not setted, use \""
242                      + MessageResources.LOCALE_KEY
243                      + "\" as key to access the Locale in session scope.");
244       } else {
245          MessageResources.LOCALE_KEY = value.trim();
246          logCat.info(" Locale Key setted with \"" + MessageResources.LOCALE_KEY
247                      + "\" as key to access the Locale in session scope.");
248       }
249    }
250 
251 
252    /***
253     * Initialize the mapping information for this application.
254     *
255     * @exception IOException if an input/output error is encountered
256     * @exception ServletException if we cannot initialize these resources
257     */
258    protected void initXMLConfig() throws IOException, ServletException {
259       // Initialize the context-relative path to our configuration resources
260       String value = getServletConfig().getInitParameter(DbFormsConfig.CONFIG);
261       loader.setConfig(value);
262       String[] s = StringUtils.split(loader.getConfig(), ",");
263       for (int i = 0; i < s.length; i++)
264          initXMLConfigFile(s[i]);
265    }
266 
267 
268    /***
269     * DOCUMENT ME!
270     *
271     * @param config DOCUMENT ME!
272     *
273     * @throws IOException DOCUMENT ME!
274     * @throws ServletException DOCUMENT ME!
275     */
276    protected void initXMLConfigFile(String config)
277                              throws IOException, ServletException {
278 
279       InputStream input = getServletContext()
280                              .getResourceAsStream(config);
281 
282       if (input == null) {
283          throw new UnavailableException("configMissing");
284       }
285 
286       try {
287          // register the config object into the DbFormsConfigRegistry
288          // as the default config (fossato, 2002.12.02)
289          DbFormsConfigRegistry registry      = DbFormsConfigRegistry.instance();
290          DbFormsConfig         dbFormsConfig = null;
291 
292          try {
293             dbFormsConfig = registry.lookup();
294          } catch (Exception e) {
295             dbFormsConfig = null;
296          }
297 
298          if (dbFormsConfig == null) {
299             dbFormsConfig = new DbFormsConfig();
300 
301             // store a reference to ServletConfig (for interoperation with other parts of the Web-App!)
302             dbFormsConfig.setServletConfig(getServletConfig());
303 
304             // ---------------------------------------------------------------
305             registry.setServletContext(getServletContext());
306             registry.register(dbFormsConfig);
307          }
308 
309          // ---------------------------------------------------------------
310          // Parse the input stream to configure our mappings
311          try {
312             loader.loadConfig(input, dbFormsConfig);
313          } catch (SAXException e) {
314             logCat.error("::initXMLConfig - SaxException", e);
315             throw new ServletException(e.toString());
316          }
317       } finally {
318          input.close();
319       }
320    }
321 
322 
323    // --------------------------------------------------------- Public Methods
324    // ------------------------------------------------------ Protected Methods
325 
326    /***
327     * Initialize the mapping information for this application.
328     *
329     * @exception IOException if an input/output error is encountered
330     * @exception ServletException if we cannot initialize these resources
331     */
332    protected void initXMLErrors() throws IOException, ServletException {
333       logCat.info("initialize XML Errors.");
334 
335       // Look to see if developer has specified his/her own errors filename & location
336       String value = getServletConfig()
337                         .getInitParameter(DbFormsErrors.ERRORS);
338 
339       loader.setErrors(value);
340 
341       // Acquire an input stream to our errors resource
342       InputStream input = getServletContext()
343                              .getResourceAsStream(loader.getErrors());
344 
345       if (input == null) {
346          // File not available, log warning
347          logCat.warn("XML Errors file not found, XML error handler disabled!");
348 
349          return;
350       }
351 
352       try {
353          // Build a digester to process our errors resource
354          DbFormsErrors dbFormsErrors = new DbFormsErrors();
355 
356          // store a reference to ServletErrors (for interoperation with other parts of the Web-App!)
357          dbFormsErrors.setServletConfig(getServletConfig());
358 
359          // store this errors object in the servlet context ("application")
360          getServletContext()
361             .setAttribute(DbFormsErrors.ERRORS, dbFormsErrors);
362 
363          try {
364             loader.loadErrors(input, dbFormsErrors);
365          } catch (SAXException e) {
366             throw new ServletException(e.toString());
367          }
368 
369          logCat.info("DbForms Error: " + dbFormsErrors);
370       } finally {
371          input.close();
372       }
373    }
374 
375 
376    /***
377     * Initialize the ValidatorResources information for this application.
378     *
379     * @exception IOException if an input/output error is encountered
380     * @exception ServletException if we cannot initialize these resources
381     */
382    protected void initXMLValidator() throws ServletException {
383       // Map the commons-logging used by commons-validator to Log4J logger
384 /* 200050906-HKK Not neccesary to configure logging here. 
385  *               Use the global logging configuration in init logging instead!!!   
386 	   try {
387          System.setProperty("org.apache.commons.logging.Log",
388                             "org.apache.commons.logging.impl.Log4JCategoryLog");
389       } catch (java.security.AccessControlException e) {
390          logCat.warn("Unable map commons-logging to Log4j, due to SecurityManager",
391                      e);
392       }
393 */
394 
395       ValidatorResources resources = new ValidatorResources();
396       logCat.info("initialize XML Validator.");
397 
398       String value;
399       value = getServletConfig()
400                  .getInitParameter(ValidatorConstants.VALIDATOR_RULES);
401 
402       loader.setValidatorRules(value);
403 
404       initXMLValidatorRules(resources, loader.getValidatorRules());
405 
406       value = getServletConfig()
407                  .getInitParameter(ValidatorConstants.VALIDATION);
408 
409       loader.setValidation(value);
410 
411       String[] s = StringUtils.split(loader.getValidation(), ",");
412 
413       for (int i = 0; i < s.length; i++)
414          initXMLValidatorValidation(resources, s[i]);
415 
416       // store this errors object in the servlet context ("application")
417       getServletContext()
418          .setAttribute(ValidatorConstants.VALIDATOR, resources);
419 
420       logCat.info(" DbForms Validator : Loaded ");
421    }
422 
423 
424    /***
425     * DOCUMENT ME!
426     *
427     * @param resources DOCUMENT ME!
428     * @param validator_rules DOCUMENT ME!
429     *
430     * @throws IOException DOCUMENT ME!
431     * @throws ServletException DOCUMENT ME!
432     */
433    protected void initXMLValidatorRules(ValidatorResources resources,
434                                         String             validator_rules)
435                                  throws ServletException {
436       // Acquire an input stream validator_rules
437       InputStream inputValidatorRules = getServletContext()
438                                            .getResourceAsStream(validator_rules);
439 
440       if (inputValidatorRules == null) {
441          // File not available, log warning
442          logCat.warn("XML Validator rule file not found, XML Validator handler disabled!");
443 
444          return;
445       }
446 
447       //
448       // Initialize ValidatorResources
449       //
450       try {
451          ValidatorResourcesInitializer.initialize(resources, inputValidatorRules);
452       } catch (IOException e) {
453          logCat.warn("XML Validator Exception ValidatorResourcesInitializer.initialize  : "
454                      + e.getMessage());
455          throw new ServletException(e.toString());
456       } finally {
457          try {
458             inputValidatorRules.close();
459          } catch (Exception e) {
460             logCat.error("initXMLValidatorRules", e);
461          }
462       }
463    }
464 
465 
466    /***
467     * DOCUMENT ME!
468     *
469     * @param resources DOCUMENT ME!
470     * @param validation DOCUMENT ME!
471     *
472     * @throws IOException DOCUMENT ME!
473     * @throws ServletException DOCUMENT ME!
474     */
475    protected void initXMLValidatorValidation(ValidatorResources resources,
476                                              String             validation)
477                                       throws ServletException {
478       //
479       // LOAD Validation & Validator_rules files
480       //
481       // Acquire an input stream validation
482       InputStream inputValidation = getServletContext()
483                                        .getResourceAsStream(validation);
484 
485       if (inputValidation == null) {
486          // File not available, log warning
487          logCat.warn("XML Validation file not found, XML Validator handler disabled!");
488 
489          return;
490       }
491 
492       try {
493          ValidatorResourcesInitializer.initialize(resources, inputValidation);
494       } catch (IOException e) {
495          logCat.warn("XML Validator Exception ValidatorResourcesInitializer.initialize  : "
496                      + e.getMessage());
497          throw new ServletException(e.toString());
498       } finally {
499          try {
500             inputValidation.close();
501          } catch (Exception e) {
502             logCat.error("initXMLValidatorValidation", e);
503          }
504       }
505    }
506 
507 
508    /***
509     * Process an HTTP request.
510     *
511     * @param request The servlet request we are processing
512     * @param response The servlet response we are creating
513     *
514     * @exception IOException if an input/output error occurs
515     * @exception ServletException if a servlet exception occurs
516     */
517    protected void process(HttpServletRequest  request,
518                           HttpServletResponse response)
519                    throws IOException {
520       PrintWriter out = response.getWriter();
521 
522       try {
523          DbFormsConfig dbFormsConfig = DbFormsConfigRegistry.instance()
524                                                             .lookup();
525          out.println(dbFormsConfig.toString());
526       } catch (Exception e) {
527          throw new IOException(e.getMessage());
528       }
529    }
530 }