KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > dbforms > servlets > ConfigServlet


1 /*
2  * $Header: /cvsroot/jdbforms/dbforms/src/org/dbforms/servlets/ConfigServlet.java,v 1.36 2004/10/06 14:36:14 hkollmann Exp $
3  * $Revision: 1.36 $
4  * $Date: 2004/10/06 14:36:14 $
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.log4j.BasicConfigurator;
31
import org.apache.commons.validator.ValidatorResources;
32 import org.apache.commons.validator.ValidatorResourcesInitializer;
33
34 import org.apache.log4j.LogManager;
35 import org.apache.log4j.PropertyConfigurator;
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 JavaDoc;
48
49 import java.io.IOException JavaDoc;
50 import java.io.InputStream JavaDoc;
51 import java.io.PrintWriter JavaDoc;
52
53 import java.util.Properties JavaDoc;
54
55 import javax.servlet.ServletException JavaDoc;
56 import javax.servlet.UnavailableException JavaDoc;
57 import javax.servlet.http.HttpServlet JavaDoc;
58 import javax.servlet.http.HttpServletRequest JavaDoc;
59 import javax.servlet.http.HttpServletResponse JavaDoc;
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 JavaDoc {
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 JavaDoc request,
98                      HttpServletResponse JavaDoc response)
99               throws IOException JavaDoc, ServletException JavaDoc {
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 JavaDoc request,
114                       HttpServletResponse JavaDoc response)
115                throws IOException JavaDoc, ServletException JavaDoc {
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 JavaDoc {
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 JavaDoc ioe) {
141          ioe.printStackTrace();
142       } catch (Exception JavaDoc e) {
143          e.printStackTrace();
144       }
145    }
146
147
148    /**
149     * Initialize Logging for this web application a url/path to a log4j
150     * properties file should be defined by the servlet init parameter
151     * "log4j.configuration"
152     */

153    public void initLogging() {
154       String JavaDoc 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 JavaDoc fis = getServletContext()
162                                  .getResourceAsStream(configurationStr);
163
164             if (fis != null) {
165                try {
166                   Properties JavaDoc log4jProperties = new Properties JavaDoc();
167                   log4jProperties.load(fis);
168                   LogManager.resetConfiguration();
169                   PropertyConfigurator.configure(log4jProperties);
170                } finally {
171                   fis.close();
172                }
173             } else {
174                System.err.println("ConfigServlet::initLogging - log4j.configuration not found!");
175             }
176          } catch (IOException JavaDoc e) {
177             System.err.println("ConfigServlet::initLogging - log4j.properties not found!");
178
179             PropertyConfigurator.configure(configurationStr);
180             usingURL = false;
181          }
182
183          logCat = LogFactory.getLog(ConfigServlet.class.getName());
184
185          // logging category for this class
186
logCat.info("### LOGGING INITALIZED, USING URL: " + usingURL + " ###"
187                      + configurationStr);
188       }
189
190       /* remove default - use tomcats instead!
191             else {
192                BasicConfigurator.configure();
193                logCat = LogFactory.getLog(ConfigServlet.class.getName());
194                // logging category for this class
195                logCat.info("### LOGGING INITALIZED, USING BASIC CONFIGURATION.");
196                logCat.info(
197                   "### You can use init-parameter \"log4j.configuration\" in web.xml for defining individual properties, if you want. Check DbForms manual!");
198             }
199       */

200    }
201
202
203    /**
204     * Initialize the SubClass information use by the ResourceBundle for this
205     * application. ATTENTION: Here the "application" it's use as Class name,
206     * not like path/file coordonnates. (see java.util.ResourceBundle)
207     *
208     * @exception IOException if an input/output error is encountered
209     * @exception ServletException if we cannot initialize these resources
210     */

211    protected void initApplicationResources() {
212       logCat.info("initialize Application Resources.");
213
214       String JavaDoc value = getServletConfig()
215                         .getInitParameter(ValidatorConstants.RESOURCE_BUNDLE);
216
217       if (value == null) {
218          logCat.warn(" Application Resources file not setted in Web.xml, ApplicationResources handler disabled!");
219
220          return;
221       }
222
223       MessageResources.setSubClass(value);
224
225       logCat.info(" DbForms Application Resources : SubClass initialized ");
226    }
227
228
229    /**
230     * Initialize the Locale key for Session scope. Usefull for sharing the same
231     * Locale across different framework. Ex: By setting "localeKey" to
232     * "org.apache.struts.action.LOCALE" you can share the same Locale in the
233     * session scope with Struts.
234     */

235    protected void initLocaleKey() {
236       logCat.info("initialize Locale Key for session attribute.");
237
238       String JavaDoc value = getServletConfig()
239                         .getInitParameter("localeKey");
240
241       if (value == null) {
242          logCat.warn(" Locale Key not setted, use \""
243                      + MessageResources.LOCALE_KEY
244                      + "\" as key to access the Locale in session scope.");
245       } else {
246          MessageResources.LOCALE_KEY = value.trim();
247          logCat.info(" Locale Key setted with \"" + MessageResources.LOCALE_KEY
248                      + "\" as key to access the Locale in session scope.");
249       }
250    }
251
252
253    /**
254     * Initialize the mapping information for this application.
255     *
256     * @exception IOException if an input/output error is encountered
257     * @exception ServletException if we cannot initialize these resources
258     */

259    protected void initXMLConfig() throws IOException JavaDoc, ServletException JavaDoc {
260       // Initialize the context-relative path to our configuration resources
261
String JavaDoc value = getServletConfig()
262                         .getInitParameter(DbFormsConfig.CONFIG);
263
264       loader.setConfig(value);
265
266       String JavaDoc[] s = StringUtils.split(loader.getConfig(), ",");
267
268       for (int i = 0; i < s.length; i++)
269          initXMLConfigFile(s[i]);
270    }
271
272
273    /**
274     * DOCUMENT ME!
275     *
276     * @param config DOCUMENT ME!
277     *
278     * @throws IOException DOCUMENT ME!
279     * @throws ServletException DOCUMENT ME!
280     */

281    protected void initXMLConfigFile(String JavaDoc config)
282                              throws IOException JavaDoc, ServletException JavaDoc {
283       // Build a digester to process our configuration resource
284
String JavaDoc realPath = getServletContext()
285                            .getRealPath("/");
286
287       // Acquire an input stream to our configuration resource
288
InputStream JavaDoc input = getServletContext()
289                              .getResourceAsStream(config);
290
291       if (input == null) {
292          throw new UnavailableException JavaDoc("configMissing");
293       }
294
295       try {
296          // register the config object into the DbFormsConfigRegistry
297
// as the default config (fossato, 2002.12.02)
298
DbFormsConfigRegistry registry = DbFormsConfigRegistry.instance();
299          DbFormsConfig dbFormsConfig = null;
300
301          try {
302             dbFormsConfig = registry.lookup();
303          } catch (Exception JavaDoc e) {
304             dbFormsConfig = null;
305          }
306
307          if (dbFormsConfig == null) {
308             dbFormsConfig = new DbFormsConfig(realPath);
309
310             // store a reference to ServletConfig (for interoperation with other parts of the Web-App!)
311
dbFormsConfig.setServletConfig(getServletConfig());
312
313             // ---------------------------------------------------------------
314
registry.setServletContext(getServletContext());
315             registry.register(dbFormsConfig);
316          }
317
318          // ---------------------------------------------------------------
319
// Parse the input stream to configure our mappings
320
try {
321             loader.loadConfig(input, dbFormsConfig);
322          } catch (SAXException JavaDoc e) {
323             logCat.error("::initXMLConfig - SaxException", e);
324             throw new ServletException JavaDoc(e.toString());
325          }
326       } finally {
327          input.close();
328       }
329    }
330
331
332    // --------------------------------------------------------- Public Methods
333
// ------------------------------------------------------ Protected Methods
334

335    /**
336     * Initialize the mapping information for this application.
337     *
338     * @exception IOException if an input/output error is encountered
339     * @exception ServletException if we cannot initialize these resources
340     */

341    protected void initXMLErrors() throws IOException JavaDoc, ServletException JavaDoc {
342       logCat.info("initialize XML Errors.");
343
344       // Look to see if developer has specified his/her own errors filename & location
345
String JavaDoc value = getServletConfig()
346                         .getInitParameter(DbFormsErrors.ERRORS);
347
348       loader.setErrors(value);
349
350       // Acquire an input stream to our errors resource
351
InputStream JavaDoc input = getServletContext()
352                              .getResourceAsStream(loader.getErrors());
353
354       if (input == null) {
355          // File not available, log warning
356
logCat.warn("XML Errors file not found, XML error handler disabled!");
357
358          return;
359       }
360
361       try {
362          // Build a digester to process our errors resource
363
DbFormsErrors dbFormsErrors = new DbFormsErrors();
364
365          // store a reference to ServletErrors (for interoperation with other parts of the Web-App!)
366
dbFormsErrors.setServletConfig(getServletConfig());
367
368          // store this errors object in the servlet context ("application")
369
getServletContext()
370             .setAttribute(DbFormsErrors.ERRORS, dbFormsErrors);
371
372          try {
373             loader.loadErrors(input, dbFormsErrors);
374          } catch (SAXException JavaDoc e) {
375             throw new ServletException JavaDoc(e.toString());
376          }
377
378          logCat.info("DbForms Error: " + dbFormsErrors);
379       } finally {
380          input.close();
381       }
382    }
383
384
385    /**
386     * Initialize the ValidatorResources information for this application.
387     *
388     * @exception IOException if an input/output error is encountered
389     * @exception ServletException if we cannot initialize these resources
390     */

391    protected void initXMLValidator() throws ServletException JavaDoc {
392       // Map the commons-logging used by commons-validator to Log4J logger
393
try {
394          System.setProperty("org.apache.commons.logging.Log",
395                             "org.apache.commons.logging.impl.Log4JCategoryLog");
396       } catch (java.security.AccessControlException JavaDoc e) {
397          logCat.warn("Unable map commons-logging to Log4j, due to SecurityManager",
398                      e);
399       }
400
401       ValidatorResources resources = new ValidatorResources();
402       logCat.info("initialize XML Validator.");
403
404       String JavaDoc value;
405       value = getServletConfig()
406                  .getInitParameter(ValidatorConstants.VALIDATOR_RULES);
407
408       loader.setValidatorRules(value);
409
410       initXMLValidatorRules(resources, loader.getValidatorRules());
411
412       value = getServletConfig()
413                  .getInitParameter(ValidatorConstants.VALIDATION);
414
415       loader.setValidation(value);
416
417       String JavaDoc[] s = StringUtils.split(loader.getValidation(), ",");
418
419       for (int i = 0; i < s.length; i++)
420          initXMLValidatorValidation(resources, s[i]);
421
422       // store this errors object in the servlet context ("application")
423
getServletContext()
424          .setAttribute(ValidatorConstants.VALIDATOR, resources);
425
426       logCat.info(" DbForms Validator : Loaded ");
427    }
428
429
430    /**
431     * DOCUMENT ME!
432     *
433     * @param resources DOCUMENT ME!
434     * @param validator_rules DOCUMENT ME!
435     *
436     * @throws IOException DOCUMENT ME!
437     * @throws ServletException DOCUMENT ME!
438     */

439    protected void initXMLValidatorRules(ValidatorResources resources,
440                                         String JavaDoc validator_rules)
441                                  throws ServletException JavaDoc {
442       // Acquire an input stream validator_rules
443
InputStream JavaDoc inputValidatorRules = getServletContext()
444                                            .getResourceAsStream(validator_rules);
445
446       if (inputValidatorRules == null) {
447          // File not available, log warning
448
logCat.warn("XML Validator rule file not found, XML Validator handler disabled!");
449
450          return;
451       }
452
453       //
454
// Initialize ValidatorResources
455
//
456
try {
457          ValidatorResourcesInitializer.initialize(resources, inputValidatorRules);
458       } catch (IOException JavaDoc e) {
459          logCat.warn("XML Validator Exception ValidatorResourcesInitializer.initialize : "
460                      + e.getMessage());
461          throw new ServletException JavaDoc(e.toString());
462       } finally {
463          try {
464             inputValidatorRules.close();
465          } catch (Exception JavaDoc e) {
466             logCat.error("initXMLValidatorRules", e);
467          }
468       }
469    }
470
471
472    /**
473     * DOCUMENT ME!
474     *
475     * @param resources DOCUMENT ME!
476     * @param validation DOCUMENT ME!
477     *
478     * @throws IOException DOCUMENT ME!
479     * @throws ServletException DOCUMENT ME!
480     */

481    protected void initXMLValidatorValidation(ValidatorResources resources,
482                                              String JavaDoc validation)
483                                       throws ServletException JavaDoc {
484       //
485
// LOAD Validation & Validator_rules files
486
//
487
// Acquire an input stream validation
488
InputStream JavaDoc inputValidation = getServletContext()
489                                        .getResourceAsStream(validation);
490
491       if (inputValidation == null) {
492          // File not available, log warning
493
logCat.warn("XML Validation file not found, XML Validator handler disabled!");
494
495          return;
496       }
497
498       try {
499          ValidatorResourcesInitializer.initialize(resources, inputValidation);
500       } catch (IOException JavaDoc e) {
501          logCat.warn("XML Validator Exception ValidatorResourcesInitializer.initialize : "
502                      + e.getMessage());
503          throw new ServletException JavaDoc(e.toString());
504       } finally {
505          try {
506             inputValidation.close();
507          } catch (Exception JavaDoc e) {
508             logCat.error("initXMLValidatorValidation", e);
509          }
510       }
511    }
512
513
514    /**
515     * Process an HTTP request.
516     *
517     * @param request The servlet request we are processing
518     * @param response The servlet response we are creating
519     *
520     * @exception IOException if an input/output error occurs
521     * @exception ServletException if a servlet exception occurs
522     */

523    protected void process(HttpServletRequest JavaDoc request,
524                           HttpServletResponse JavaDoc response)
525                    throws IOException JavaDoc {
526       PrintWriter JavaDoc out = response.getWriter();
527
528       try {
529          DbFormsConfig dbFormsConfig = DbFormsConfigRegistry.instance()
530                                                             .lookup();
531          out.println(dbFormsConfig.toString());
532       } catch (Exception JavaDoc e) {
533          throw new IOException JavaDoc(e.getMessage());
534       }
535    }
536 }
537
Popular Tags