KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > lutris > appserver > server > httpPresentation > servlet > HttpPresentationServlet


1 /*
2  * Enhydra Java Application Server Project
3  *
4  * The contents of this file are subject to the Enhydra Public License
5  * Version 1.1 (the "License"); you may not use this file except in
6  * compliance with the License. You may obtain a copy of the License on
7  * the Enhydra web site ( http://www.enhydra.org/ ).
8  *
9  * Software distributed under the License is distributed on an "AS IS"
10  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
11  * the License for the specific terms governing rights and limitations
12  * under the License.
13  *
14  * The Initial Developer of the Enhydra Application Server is Lutris
15  * Technologies, Inc. The Enhydra Application Server and portions created
16  * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
17  * All Rights Reserved.
18  *
19  * Contributor(s):
20  *
21  * $Id: HttpPresentationServlet.java,v 1.15 2005/06/20 15:11:31 slobodan Exp $
22  */

23
24
25
26
27
28 package com.lutris.appserver.server.httpPresentation.servlet;
29
30 import java.io.File JavaDoc;
31 import java.io.IOException JavaDoc;
32 import java.io.PrintWriter JavaDoc;
33 import java.lang.reflect.Constructor JavaDoc;
34 import java.util.regex.Pattern JavaDoc;
35
36 import javax.servlet.ServletConfig JavaDoc;
37 import javax.servlet.ServletContext JavaDoc;
38 import javax.servlet.ServletException JavaDoc;
39 import javax.servlet.ServletRequest JavaDoc;
40 import javax.servlet.http.HttpServlet JavaDoc;
41 import javax.servlet.http.HttpServletRequest JavaDoc;
42 import javax.servlet.http.HttpServletResponse JavaDoc;
43
44 import org.apache.axis.transport.http.AxisServlet;
45 import org.enhydra.server.EnhydraServer;
46 import org.enhydra.util.ConfigFileInterface;
47
48 import com.lutris.appserver.server.Application;
49 import com.lutris.appserver.server.ApplicationException;
50 import com.lutris.appserver.server.Enhydra;
51 import com.lutris.appserver.server.httpPresentation.HttpPresentationException;
52 import com.lutris.appserver.server.httpPresentation.HttpPresentationManager;
53 import com.lutris.appserver.server.httpPresentation.HttpPresentationRequest;
54 import com.lutris.appserver.server.httpPresentation.HttpPresentationResponse;
55 import com.lutris.appserver.server.session.Session;
56 import com.lutris.classloader.MultiClassLoader;
57 import com.lutris.logging.LogChannel;
58 import com.lutris.logging.Logger;
59 import com.lutris.util.Config;
60
61 /**
62  * Presentation server implemented as a servlet. Translates servlet
63  * requests into HttpPresentationManager requests. There is a one
64  * to one correspondence between an instance of this servlet and
65  * an Enhydra application. An instance of the application is created by
66  * the servlet.
67  *
68  * The servlet requires a single init parameter `configFile', that
69  * contains the path to the application's configuration file. This
70  * file must define the following fields:
71  * <UL>
72  * <LI> <CODE>server.classPath</CODE> - The class path for the application,
73  * as a comma seperated list. This should not contain the class path
74  * for the Java runtime classes or the Lutris classes.
75  * <LI> <CODE>server.appClass</CODE> - The full class name of the application
76  * class. This must implement
77  * <CODE>com.lutris.appserver.server.Application</CODE>.
78  * <LI> <CODE>server.presentationPrefix</CODE> - This is the path that is used as
79  * a prefixed for all URL references withing the application. It must use
80  * a `/' seperator (as with URLs).
81  * <LI> <CODE>server.autoReload</CODE> - A flag to indicate whether or not
82  * the application should be automatically reloaded when any class or
83  * jar file changes in the application's classpath. <B><I>NOTE: THIS IS
84  * A DEBUGGING OPTION AND MAY SLOW DOWN THE APPLICATION!</I></B>
85  * <LI>
86  * </UL> <P>
87  *
88  * This servlet also implements the <CODE>ListenableServlet</CODE>
89  * interface. This allows other objects to register with this servlet and
90  * be notified every time <CODE>service</CODE> is called. These remote
91  * listeners may ignore the notification, examine the request, or even
92  * replace the request and/or response with extended versions. This is
93  * used by the debugging and monitoring servlets.
94  *
95  *
96  * @version $Revision: 1.15 $
97  * @author Mark Diekhans
98  * @author Damir Milovic
99  * @author Strahinja Videnovic
100  * @since 1.3
101  */

102 //FIXME: Explain the presentationPrefix better; give example.
103
//FIXME: Integrate URLEncodeServlet
104
public class HttpPresentationServlet extends HttpServlet JavaDoc {
105
106   /**
107    * Log level for DOM statistics.
108    */

109   public static final String JavaDoc XMLC_DOM_STATS_LOG_LEVEL = "XMLC_DOM_STATS";
110
111   /**
112    * Servlet is started under this context
113    */

114   protected ServletContext JavaDoc context;
115
116   /*
117    * Application configuration definitions.
118    */

119   private static final String JavaDoc APP_CONFIG_INIT_PARAM_NAME =
120       EnhydraServer.CONF_FILE;
121   private static final String JavaDoc APP_CONFIG_FILE_CLASS =
122       EnhydraServer.CONF_FILE_CLASS; // TJ 08.11.2003.
123
private static final String JavaDoc APP_CLASS_PATH_FIELD =
124       EnhydraServer.SERVER + "." + EnhydraServer.CLASS_PATH;
125   private static final String JavaDoc APP_APP_CLASS_FIELD =
126       EnhydraServer.SERVER + "." + EnhydraServer.APP_CLASS;
127   private static final String JavaDoc APP_PRESENTATION_PREFIX_FIELD =
128       EnhydraServer.SERVER + "." + EnhydraServer.PRESENTATION_PREFIX;
129   private static final String JavaDoc APP_AUTO_RELOAD_FIELD =
130       EnhydraServer.SERVER + "." + EnhydraServer.AUTO_RELOAD;
131   private static final String JavaDoc APP_DEFERRED_PARSING_FIELD =
132       EnhydraServer.SERVER + ".XMLC.DeferredParsing"; //SV
133
private static final String JavaDoc APP_JIVAN_RELOAD_FIELD =
134       EnhydraServer.SERVER + ".AutoReload"; //vr 16.05.2004.
135
private static final String JavaDoc APP_ENCODING_TYPE =
136       EnhydraServer.APPLICATION + "." + "Encoding";
137   private static final String JavaDoc APP_PRESENTATION_TOOLS =
138       EnhydraServer.APPLICATION + ".PresentationTools"; //vr 22.06.2004.
139

140
141   /*
142    * For logging info about starting applications
143    */

144   private LogChannel logChannel;
145
146   /*
147    * If we create the central logger, we save a copy of it for later
148    * initialization. If we didn't create it, this will be null.
149    */

150   private Logger standardLogger;
151
152   /*
153    * If we create the central logger, we will need to initialize it later
154    * when init() is called.
155    */

156   private boolean needToConfigureLogChannel = true;
157  
158   
159   /*
160    * Specify character encoding which will be used by server to encode form data.
161    */

162    String JavaDoc characterEncoding;
163    private boolean needToSetCharacterEncoding = false;
164
165   /*
166    * Application and its configuration information.
167    */

168   Application application = null;
169   Config JavaDoc appConfig = null;
170   String JavaDoc presentationPrefix;
171   String JavaDoc logClassName;
172   boolean cacheClasses;
173   boolean cacheFiles;
174   boolean autoReload; // Reload application when its classes are modified?
175

176   HttpPresentationManager presentationManager = null;
177
178   private boolean isMemoryPersistence = false; // MemoryPersistence support
179

180   private String JavaDoc appName = null; // MemoryPersistence support
181

182   /**
183    * If not null, log DOM statistics here after each DOM write.
184    */

185   private PrintWriter JavaDoc domStatsLogWriter;
186   private AxisServlet axisServlet = null;
187   private Pattern JavaDoc axisPattern = Pattern.compile(".*Axis.*");
188
189   private MultiClassLoader appClassLoader = null; //vr
190

191   /**
192    * Create a new HttpPresentationServlet.
193    */

194   public HttpPresentationServlet() {
195     super();
196   }
197
198   /**
199    * Throw a servlet exceptionm logging the message if possible.
200    */

201   private void throwServletException(String JavaDoc msg, Throwable JavaDoc cause) throws
202       ServletException JavaDoc {
203     if (logChannel != null) {
204       logChannel.write(Logger.ERROR, msg, cause);
205     }
206     else {
207       // Desprite
208
System.err.println("Error: " + msg);
209       cause.printStackTrace();
210     }
211     throw new ServletException JavaDoc(msg + "\ncaused by "
212                                + cause.getClass() + ": " + cause.getMessage());
213   }
214
215
216   /**
217    * Generate an error for a field not being specified in a config file.
218    */

219   private void missingConfField(String JavaDoc field, String JavaDoc file) throws
220       HttpPresentationException {
221     throw new HttpPresentationException("field \"" + field
222                                         +
223                                         "\" not specified in application config file \""
224                                         + file + "\"");
225   }
226
227   /**
228    * Open and read the application's configuration file and initialize the
229    * application
230    */

231
232   private String JavaDoc initConfig(ServletConfig JavaDoc servletConfig) throws
233       ServletException JavaDoc {
234
235     try {
236       // Get configuration file and parameters.
237
String JavaDoc configFileName = servletConfig.getInitParameter( APP_CONFIG_INIT_PARAM_NAME);
238       if (configFileName == null) {
239         throw new HttpPresentationException("init parameter \"" +
240                                             APP_CONFIG_INIT_PARAM_NAME +
241                                             "\" not specified for Enhydra servlet");
242       }
243       // if confgFile is relative, make it absolute
244
// TJ 08.11.2003 begin
245
String JavaDoc classDefinition = servletConfig.getInitParameter(APP_CONFIG_FILE_CLASS);
246       if (classDefinition == null)
247         classDefinition = EnhydraServer.DEFAULT_CONF_FILE_CLASS;
248       Class JavaDoc imp = null;
249       try {
250         imp = Class.forName(classDefinition);
251       }
252       catch (Exception JavaDoc ex) {
253         try {
254           classDefinition = EnhydraServer.DEFAULT_CONF_FILE_CLASS;
255           imp = Class.forName(classDefinition);
256         }
257         catch (Exception JavaDoc e) {
258           throw new ServletException JavaDoc("Can not create configFile");
259         }
260       }
261
262       Class JavaDoc[] classParam = new Class JavaDoc[1];
263       classParam[0] = Class.forName("java.io.File");
264       Constructor JavaDoc constr = imp.getConstructor(classParam);
265       Object JavaDoc[] arguments = new Object JavaDoc[1];
266       File JavaDoc configFile = new File JavaDoc(configFileName);
267       String JavaDoc contextUrl = this.getServletConfig().getServletContext().getRealPath("");
268       if (!configFile.isAbsolute() && !configFileName.startsWith("/")) { /*for Windows OS check */
269         configFile = new File JavaDoc(contextUrl, "WEB-INF/" + configFileName);
270       }
271       arguments[0] = (Object JavaDoc) (configFile);
272       ConfigFileInterface configF = (ConfigFileInterface) constr.newInstance(arguments);
273       appConfig = configF.getConfig();
274
275       return configFileName;
276     }
277     catch (Exception JavaDoc except) {
278       throwServletException("Initialization of application failed", except);
279     }
280     return null;
281   }
282
283   /**
284    * Open and read the application's configuration file and initialize the
285    * application, but don't start it yet. This is done on in service so it
286    * part of the standard state-change mechanism.
287    */

288   private void initApplication(ServletConfig JavaDoc servletConfig) throws
289       ServletException JavaDoc {
290     try {
291       int uuu = 0;
292       String JavaDoc configFileName = servletConfig.getInitParameter( APP_CONFIG_INIT_PARAM_NAME);
293       if (configFileName == null)
294         throw new HttpPresentationException("init parameter \"" +
295                                             APP_CONFIG_INIT_PARAM_NAME +
296                                             "\" not specified for Enhydra servlet");
297       String JavaDoc contextUrl = this.getServletConfig().getServletContext().
298           getRealPath("");
299
300       //adds all archive files from lib into classloader classpath
301
File JavaDoc libDir = new File JavaDoc(contextUrl, "WEB-INF/lib");
302       File JavaDoc[] archives = libDir.listFiles(new ArchiveFilter());
303       if (archives != null) {
304         for (int i = 0; i < archives.length; i++) {
305           this.appClassLoader.addClassPath(archives[i]);
306         }
307       }
308       
309       //add classes dir into claspath
310
this.appClassLoader.addClassPath(new File JavaDoc(contextUrl, "WEB-INF/classes"));
311       // Add application's class path from config file into classloader.
312
String JavaDoc[] appClassPath = appConfig.getStrings(APP_CLASS_PATH_FIELD, null);
313       if (appClassPath != null)
314         this.appClassLoader.addClassPath(appClassPath);
315
316
317       // for MemoryPersistence support, we need key
318
String JavaDoc appClass = appConfig.getString(APP_APP_CLASS_FIELD);
319       String JavaDoc name = appClass;
320   /* int idxn = name.lastIndexOf('.');
321       if (idxn >= 0)
322         name = name.substring(idxn + 1); //application name from Class name
323         //do not save ClassLoader if MemoryPersistence = false
324       this.appName = name;
325       isMemoryPersistence = false;
326       if (appConfig.containsKey("SessionManager.MemoryPersistence"))
327         isMemoryPersistence = appConfig.getBoolean("SessionManager.MemoryPersistence");
328       if (isMemoryPersistence) {
329         ClassLoader cl = MemoryPersistence.getClassLoader(name);
330         if (cl == null) {
331           MemoryPersistence.setClassLoader(name, appClassLoader);
332         }
333         else {
334           appClassLoader = (MultiClassLoader) cl;
335         }
336       }
337   */

338       if (appClass == null) {
339         missingConfField(APP_APP_CLASS_FIELD, configFileName);
340       }
341       presentationPrefix = appConfig.getString(APP_PRESENTATION_PREFIX_FIELD);
342       if (presentationPrefix == null) {
343         missingConfField(APP_PRESENTATION_PREFIX_FIELD, configFileName);
344       }
345       autoReload = appConfig.getBoolean(APP_AUTO_RELOAD_FIELD, false);
346
347       characterEncoding = appConfig.getString(APP_ENCODING_TYPE,null);
348       if (characterEncoding != null) {
349         needToSetCharacterEncoding=true;
350       }
351    
352
353       // Config of presentation manager
354
cacheClasses = appConfig.getBoolean("PresentationManager.CacheClasses", true);
355       cacheFiles = appConfig.getBoolean("PresentationManager.CacheFiles", false);
356
357       logChannel.write(Logger.DEBUG, "Loaded Enhydra application: " + appClass);
358       logChannel.write(Logger.DEBUG, " presentation prefix: " + presentationPrefix);
359
360       // Load actual application object.
361
Class JavaDoc appClassObj = appClassLoader.loadClass(appClass);
362       application = (Application) appClassObj.newInstance();
363
364       /*
365        * Register the application object with this thread.
366        * We do this so that all calls into the Application object
367        * can count the Enhydra class to sucessfully return the
368        * Application object.
369        */

370       Enhydra.register(application);
371
372       try {
373 // vr application.setLogChannel(Logger.getCentralLogger().getChannel(name));
374
application.setLogChannel(standardLogger.getChannel(name)); // vr
375

376         // FIXME: need to load app logger configuration from app conf file
377
application.setName(name);
378       }
379       finally {
380         // Be sure the thread is unregistered no matter what.
381
Enhydra.unRegister();
382       }
383       setPresentationManager(context, appClassLoader);
384
385 // vr 22.06.2004 begin
386
// reads list of available presentation tools
387
String JavaDoc[] presTools = appConfig.getStrings(this.APP_PRESENTATION_TOOLS, new String JavaDoc[] {"xmlc"});
388       for (int i = 0; i < presTools.length; i++) {
389
390         if (presTools[i].equalsIgnoreCase("xmlc")) {
391           // sets XMLC Factory (needs classLoader set).
392
boolean xmlcDeferredParsing = appConfig.getBoolean(this.APP_DEFERRED_PARSING_FIELD, false);
393           application.setXMLCFactory(xmlcDeferredParsing);
394         }
395         else if (presTools[i].equalsIgnoreCase("jivan")) {
396           // sets Jivan Factory.
397
boolean jivanAutoReload = appConfig.getBoolean(this.APP_JIVAN_RELOAD_FIELD, false);
398           application.setJivanFactory(jivanAutoReload);
399         }
400       }
401 // vr 22.06.2004 end
402

403       LogChannel appLogChannel = application.getLogChannel();
404       if (appLogChannel != null) {
405         if (appLogChannel.isEnabled(XMLC_DOM_STATS_LOG_LEVEL)) {
406           domStatsLogWriter = appLogChannel.getLogWriter(XMLC_DOM_STATS_LOG_LEVEL);
407         }
408       }
409
410       // Tell the presentation manager about addititonal
411
// extension/mime-type mappings.
412
Config JavaDoc mimeTypes = appConfig.getConfig("Server.MimeType");
413       if (mimeTypes != null) {
414         String JavaDoc extensions[] = mimeTypes.keys();
415         for (int idx = 0; idx < extensions.length; idx++) {
416           presentationManager.addMimeType(mimeTypes.getString(extensions[idx]),
417                                           extensions[idx]);
418         }
419       }
420     }
421     catch (Exception JavaDoc except) {
422       throwServletException("Initialization of application failed", except);
423     }
424   }
425
426   /*
427    * Standard servlet init function, creates the presentation manager
428    * we are going to use.
429    *
430    * @param config Object containing the servlet's startup
431    * configuration and initialization parameters.
432    * @exception ServletException if a servlet exception has occurred.
433    */

434   public synchronized void init(ServletConfig JavaDoc config) throws ServletException JavaDoc {
435     super.init(config); // You must do this when overriding this method.
436

437     context = config.getServletContext();
438     //SM 11.05.2004.
439
initConfig(config);
440
441
442     ClassLoader JavaDoc secondaryLoader = Thread.currentThread().getContextClassLoader(); //vr
443
//this.appClassLoader = new MultiClassLoader(secondaryLoader.getParent(), secondaryLoader, logChannel); //vr
444
this.appClassLoader = new MultiClassLoader(secondaryLoader, null, logChannel); //vr
445
appClassLoader.forceSecondaryLoader(true);
446     appClassLoader.enableAutoReloadForSecLoader(this.autoReload);
447
448     try {
449       logClassName = appConfig.getString(EnhydraServer.LOG_CLASS, EnhydraServer.DEFAULT_LOG_CLASS);
450       if (logClassName == null)
451         logClassName = EnhydraServer.DEFAULT_LOG_CLASS;
452 //vr standardLogger = (Logger) Class.forName(logClassName).getConstructor(new
453
standardLogger = (Logger) Class.forName(logClassName, true, appClassLoader).getConstructor(new
454           Class JavaDoc[] {Boolean.TYPE}).newInstance(new Object JavaDoc[] {new Boolean JavaDoc(true)});
455       if (needToConfigureLogChannel) {
456         standardLogger.configure(appConfig);
457         needToConfigureLogChannel = false;
458       }
459     }
460     catch (Exception JavaDoc e) {
461       throwServletException("Initialization of logger failed", e);
462     }
463     logChannel = standardLogger.getChannel("Enhydra");
464
465     initApplication(config);
466
467     // This call is added for the 3.0 release.
468
// in the past ensure app is running was called by the servletmanager
469
// after a cast of the servlet variable.
470
ensureAppIsRunning();
471     /**
472      * register servlet on startup to EnhydraServer
473      * (need for admin application)
474      */

475     EnhydraServer es = EnhydraServer.getInstance();
476     es.register(this);
477   }
478
479   /**
480    * Sets the presentation manager for the application. First creates a
481    * new presentation manager with the presentationPrefix, application,
482    * cacheClasses and cacheFiles fields (so these parameters must already
483    * be initialized). Then, the presentation manager is set in the
484    * application.
485    *
486    * @param context The servlet context for this application.
487    * @param appClassLoader The class loader for this application.
488    * @exception ServletException if a servlet exception has occurred.
489    */

490   private void setPresentationManager(ServletContext JavaDoc context,
491                                       ClassLoader JavaDoc appClassLoader) throws
492       ServletException JavaDoc {
493     try {
494       presentationManager = new HttpPresentationManager(presentationPrefix,
495           application, appClassLoader, cacheClasses, cacheFiles);
496       presentationManager.setServletAndContext(this, context);
497     }
498     catch (Exception JavaDoc except) {
499       throwServletException("Initialization of presentation manager failed", except);
500     }
501
502     /*
503      * Tell application about the presentation manager running it.
504      *
505      * Register the application object with this thread.
506      * We do this so that all calls into the Application object
507      * can count the Enhydra class to sucessfully return the
508      * Application object.
509      */

510     Enhydra.register(application);
511     try {
512       application.setHttpPresentationManager(presentationManager);
513     }
514     finally {
515       // Be sure the thread is unregistered no matter what.
516
Enhydra.unRegister();
517     }
518   }
519
520   /**
521    * Attempt to change the application to the running state.
522    */

523   private synchronized void changeToRunningState() throws ApplicationException {
524
525     // We may or may not be registered here..
526
boolean isRegistered = (Enhydra.getApplication() != null);
527     if (!isRegistered) {
528       Enhydra.register(application);
529     }
530     try {
531       switch (application.getState()) {
532         case Application.STOPPED:
533           application.startup(appConfig);
534           isRegistered = (Enhydra.getApplication() != null);
535           break;
536         case Application.RUNNING:
537           break;
538         case Application.INCOMPLETE:
539           application.restartup(appConfig);
540           break;
541         case Application.DEAD:
542           throw new ApplicationException("The application " +
543                                          application.getName() +
544                                          " is dead");
545         case Application.HALTED:
546           throw new ApplicationException("The application " +
547                                          application.getName() +
548                                          " is halted");
549
550         default:
551           throw new ApplicationException("The application " +
552                                          application.getName() +
553                                          " in invalid state");
554       }
555     }
556     finally {
557       if (!isRegistered) {
558         Enhydra.unRegister();
559       }
560     }
561   }
562
563   /**
564    * This is an HTTP-specific version of the Servlet.service method
565    * that translates that request into a request to a presentation
566    * manager. This object is method is not synchronized, the thread
567    * is used to handle to entire request. <P>
568    *
569    * As part of implementing the FiterableServlet interface, the real work
570    * is done here in serviceDirect(), while calls to service() result in
571    * filters being applied and called. The end of the filter chain is a
572    * glue servlet that directly calls this method.
573    *
574    * @param req encapsulates the request to the servlet
575    * @param resp encapsulates the response from the servlet
576    * @exception ServletException if the request could not be handled
577    * @exception IOException if detected when handling the request
578    */

579   public void serviceDirect(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc resp) throws
580       ServletException JavaDoc, IOException JavaDoc {
581
582     /*
583      * Register the application object with this thread.
584      * We do this so that all the calls into the Application object
585      * can count on the Enhydra class to return the Application object.
586      * This is important not so much for the Application object, but
587      * for any utility classes it may call.
588      */

589     Enhydra.register(application);
590     try {
591       ensureAppIsRunning();
592       String JavaDoc usrAgent = req.getHeader("user-agent");
593       String JavaDoc query = req.getQueryString();
594       boolean wsdl = false;
595     
596       if(needToSetCharacterEncoding)
597            req.setCharacterEncoding(characterEncoding);
598        
599     
600    /* Enumeration e = req.getParameterNames();
601    
602       boolean wsdl = false;
603  
604       if (e.hasMoreElements()) {
605          System.out.println(" Ima parametara ");
606         String pName = (String) e.nextElement();
607         System.out.println(" parametar : "+pName);
608         if (pName.equals("wsdl")) {
609           wsdl = true;
610           logChannel.write(Logger.DEBUG,
611                            "It is an Axis request for a wsdl sevice description");
612         }
613       }
614      */

615       if(query != null && query.equals("wsdl"))
616       {
617        wsdl=true;
618        logChannel.write(Logger.DEBUG,
619                            "It is an Axis request for a wsdl sevice description");
620        }
621       logChannel.write(Logger.DEBUG, "HUA: " + usrAgent, null);
622
623       if (usrAgent != null && (wsdl || axisPattern.matcher(usrAgent).matches())) {
624         // It is Axis request, so initialise the axisServlet if not initialised
625
logChannel.write(Logger.DEBUG, "It is an Axis request ");
626         if (axisServlet == null) {
627           logChannel.write(Logger.INFO, "Initialising the Axis servlet "+application.getName());
628           axisServlet = new AxisServlet();
629           axisServlet.init(getServletConfig());
630         }
631         try {
632           // Service the request
633
logChannel.write(Logger.INFO, "Servicing the Axis request "+application.getName());
634           axisServlet.service(req, resp);
635         }
636         catch (Exception JavaDoc excp) {
637           //Do nothing. proceed and try to service it Enhydra way
638
presentationManager.Run(new ServletHttpPresentationRequest(req),
639                                   new ServletHttpPresentationResponse(resp,
640               domStatsLogWriter));
641         }
642       }
643       else
644
645     presentationManager.Run(new ServletHttpPresentationRequest(req),
646                               new ServletHttpPresentationResponse(resp,
647           domStatsLogWriter));
648     }
649     catch (HttpPresentationException except) {
650       throwServletException(
651           "An unhandled error occured while servicing an application request",
652           except);
653     }
654     finally {
655       // Be sure the thread is unregistered no matter what.
656
Enhydra.unRegister();
657     }
658   }
659
660   /**
661    * This method is public for use by the ServletManager
662    * to run the application startup() method after init().
663    * @exception ServletException
664    * If any error occurs on startup.
665    */

666   public void ensureAppIsRunning() throws ServletException JavaDoc {
667     checkAutoReload();
668     // If an application is associated,
669
// then make sure it's in the run state.
670
if ( (application != null) &&
671         (application.getState() != Application.RUNNING)) {
672       try {
673         changeToRunningState();
674         context.setAttribute(EnhydraServer.SESSION_MANAGER_KEY,
675                              application.getSessionManager());
676       }
677       catch (Throwable JavaDoc except) {
678         throwServletException("Unable to change application to running state", except);
679       }
680     }
681   }
682
683   /**
684    * Return information specific to this servlet.
685    */

686   public String JavaDoc getServletInfo() {
687     return com.lutris.Enhydra.getEnhydraLongName() + "/" +
688         com.lutris.Enhydra.getEnhydraVersion(); // FIXME: return some valid info
689
}
690
691   /**
692    * This method instantiates the HttpPresentationRequest
693    * object that the presentation manager expects when
694    * servicing a request.
695    *
696    * @param req
697    * The servlet request object.
698    * @param resp
699    * The servlet response object.
700    * @return The HttpPresentationRequest object used
701    * by the presentation manager.
702    */

703   protected HttpPresentationRequest getHttpPresentationRequest(
704       HttpServletRequest JavaDoc req,
705       HttpServletResponse JavaDoc resp) {
706     return new ServletHttpPresentationRequest(req);
707   }
708
709   /**
710    * This method instantiates the HttpPresentationResponse
711    * object that the presentation manager expects when
712    * servicing a request.
713    *
714    * @param req
715    * The servlet request object.
716    * @param resp
717    * The servlet response object.
718    * @return The HttpPresentationResponse object used
719    * by the presentation manager.
720    */

721   protected HttpPresentationResponse getHttpPresentationResponse(
722       HttpServletRequest JavaDoc req,
723       HttpServletResponse JavaDoc resp) {
724     return new ServletHttpPresentationResponse(resp, domStatsLogWriter);
725   }
726
727   /**
728    * Returns the application being run by this instance of
729    * the servlet.
730    */

731   public Application getApplication() {
732     return application;
733   }
734
735   /**
736    * Returns the application configuration init parameter.
737    */

738   protected Config JavaDoc getAppConfigInitParam() {
739     return appConfig;
740   }
741
742   /**
743    * Returns the application configuration init parameter name.
744    */

745   protected String JavaDoc getAppConfigInitParamName() {
746     return APP_CONFIG_INIT_PARAM_NAME;
747   }
748
749   /**
750    * Handle a service request. Use the first filter to wrap the request,
751    * response, and servlet (this) objects. This will return new objects.
752    * Then use the second filter to wrap those, again returning new
753    * objects. Then use the fourth filter to wrap those etc....
754    * Then finally call <CODE>service()</CODE> on the outermost results.
755    *
756    * @param request
757    * The original servlet request object.
758    * @param response
759    * The original servlet response object.
760    */

761   public void service(HttpServletRequest JavaDoc request,
762                       HttpServletResponse JavaDoc response) throws ServletException JavaDoc,
763       IOException JavaDoc {
764     /*
765      * This hook was added to support the debugger. Almost all
766      * applications will not use this.
767      */

768     if (presentationManager.servletRequestPreprocessor(this, context,
769         request, response)) {
770       // The request has been completly processed. Nothing left to do.
771
return;
772     }
773
774     serviceDirect(request, response);
775   }
776
777   /**
778    * Looks up the session object (if any) that would be used to
779    * process the request. This is will not used normally, because the
780    * session is give to the application's preprocessor method and the
781    * presentation objects. Also, it is not normal to have a raw
782    * ServletRequest. The debugger uses this to examine the session data
783    * before and after each request. Consider this an internal use only
784    * method.
785    *
786    * @param request
787    * The (raw) request that would be sent in to this application.
788    * @return
789    * The session object that would be associated with the request.
790    * Returns null if none is found; a new session is not created.
791    */

792   public Session getSession(ServletRequest JavaDoc request) {
793     if (application == null) {
794       return null;
795     }
796     Enhydra.register(application);
797     Session s = null;
798
799     try {
800       s = presentationManager.getSession(request);
801     }
802     finally {
803       Enhydra.unRegister();
804     }
805     return s;
806   }
807
808   /**
809    * Check if the application should be automatically reloaded and, if so,
810    * call <CODE>initApplication</CODE> with a new instance of the class
811    * loader. The application should be reloaded if the
812    * <CODE>autoReload</CODE> flag is <CODE>true</CODE> and any class has
813    * changed in the application's classpath.
814    *
815    * @exception ServletException if a servlet exception has occurred.
816    */

817   private void checkAutoReload() throws ServletException JavaDoc {
818     if (autoReload) {
819       if (this.appClassLoader.shouldReload()) {
820         application.shutdown();
821
822         ClassLoader JavaDoc secondaryLoader = Thread.currentThread().getContextClassLoader(); //vr
823
this.appClassLoader = new MultiClassLoader(secondaryLoader.getParent(), secondaryLoader, logChannel); //vr
824
appClassLoader.forceSecondaryLoader(true);
825         appClassLoader.enableAutoReloadForSecLoader(autoReload);
826
827         initConfig(getServletConfig());
828         initApplication(getServletConfig());
829       }
830     }
831   }
832
833   /**
834    * Destroys the servlet. Called by the servlet manager when the servlet
835    * is shutdown.
836    */

837   public synchronized void destroy() {
838     // for MemoryPersistence = false remove ClassLoader from HashTable
839
/* if (!isMemoryPersistence) {
840       MemoryPersistence.removeClassLoader(appName);
841     }
842     */

843     application.shutdown();
844     // Unregister from EnhydraServer
845
EnhydraServer es = EnhydraServer.getInstance();
846     es.unRegister(this);
847     
848     // Claering Object Attributes
849
standardLogger = null;
850     logChannel = null;
851     appClassLoader.clearClassPath();
852     appClassLoader = null;
853     presentationManager = null;
854   }
855
856 }
857
Popular Tags