KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > cofax > cds > CDSServlet


1 /*
2  * CDSServlet is part of the Cofax content management system library.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  *
18  * Please see http://www.cofax.org for contact information and other related informaion.
19  *
20  * $Header: /cvsroot/cofax/cofax/src/org/cofax/cds/CDSServlet.java,v 1.36.2.1 2006/12/11 16:19:28 fxrobin Exp $
21  */

22
23 package org.cofax.cds;
24
25 import java.io.File JavaDoc;
26 import java.io.FileWriter JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.io.PrintWriter JavaDoc;
29 import java.io.UnsupportedEncodingException JavaDoc;
30 import java.net.URLEncoder JavaDoc;
31 import java.util.Date JavaDoc;
32 import java.util.Enumeration JavaDoc;
33 import java.util.HashMap JavaDoc;
34 import java.util.Iterator JavaDoc;
35 import java.util.Properties JavaDoc;
36
37 import javax.servlet.RequestDispatcher JavaDoc;
38 import javax.servlet.ServletConfig JavaDoc;
39 import javax.servlet.ServletContext JavaDoc;
40 import javax.servlet.ServletException JavaDoc;
41 import javax.servlet.ServletOutputStream JavaDoc;
42 import javax.servlet.http.HttpServlet JavaDoc;
43 import javax.servlet.http.HttpServletRequest JavaDoc;
44 import javax.servlet.http.HttpServletResponse JavaDoc;
45
46 import org.cofax.CofaxCache;
47 import org.cofax.CofaxJspResponse;
48 import org.cofax.CofaxPage;
49 import org.cofax.CofaxUtil;
50 import org.cofax.DataStore;
51 import org.cofax.Glossary;
52 import org.cofax.Redirection;
53 import org.cofax.TemplateLoader;
54 import org.cofax.TemplateProcessor;
55 import org.cofax.cms.login.ILoginHandler;
56
57 /**
58  * The Cofax project's web serving program.
59  * <p>
60  *
61  * <code>CDSServlet</code> is a small <i>"driver program"</i> that uses
62  * various Cofax modules to serve an interactive web site. <code>
63  * CDSServlet</code>
64  * dynamically loads modules listed in the configuration to serve as data store
65  * connectors, template processing engines, personalization engines, and
66  * delivery engines.
67  * </p>
68  *
69  * @author Rajiv Pant
70  * @author Karl Martino
71  * @author Hung Dao
72  * @author Sam Cohen
73  * @author Lee Bolding
74  * @author F.X. Robin
75  * @author Cedric Aveline
76  * @since February 26, 2001
77  */

78
79 public class CDSServlet extends HttpServlet JavaDoc {
80
81     /**
82      * UID for serialization needs
83      */

84     private static final long serialVersionUID = -1521543069026357290L;
85
86     /**
87      * Description of the Field
88      */

89     public final static String JavaDoc COFAX_VERSION = "Revision : 2.3 / Build date : 2006/12/07";
90
91     /**
92      * The maximum URL length allowed by the servlet.
93      */

94     private static int maxUrlLength;
95
96     //
97
// NOT USED ANYMORE A time out in milliseconds for template processing
98
//
99
// private static int templateTimeOut;
100

101     private static String JavaDoc searchTemplate;
102
103     /**
104      * Template for search engine file pages
105      */

106     private static String JavaDoc searchEngineFileTemplate;
107
108     /**
109      * Template for search engine index pages
110      */

111     private static String JavaDoc searchEngineListTemplate;
112
113     /**
114      * The context path of the servlet
115      */

116     public static String JavaDoc contextPath;
117
118     // FX :
119
public static String JavaDoc articleRessourceFolder;
120
121     public static String JavaDoc userImageFolder;
122
123     /**
124      * The mount point for the servlet
125      */

126     private static String JavaDoc servletPath;
127
128     /**
129      * Class name from config for dataStore
130      */

131     private static String JavaDoc dataStoreClass;
132
133     /**
134      * Class name from config for template processing
135      */

136     private static String JavaDoc templateProcessorClass;
137
138     /**
139      * AVE : Variable pour déterminer les clients privés
140      */

141     private static String JavaDoc IPStartsWith;
142
143     private static String JavaDoc IPEquals;
144
145     private static String JavaDoc IPExceptionsStartsWith;
146
147     private static String JavaDoc IPExceptionsEquals;
148
149     private static String JavaDoc PortNumberEquals;
150
151     private static String JavaDoc PortNameEquals;
152
153     /**
154      * Class to look up redirects.
155      */

156     private static Redirection cofaxRedirect;
157
158     /**
159      * Class name from config for redirects
160      */

161     private static String JavaDoc redirectionClass;
162
163     /**
164      * Cache to store and get URLs
165      */

166     static CofaxCache cacheOfPages;
167
168     /**
169      * Cache to store templates.
170      */

171     static CofaxCache cacheOfTemplates;
172
173     /**
174      * Cache to store packageTags.
175      */

176     static CofaxCache cacheOfPackageTags;
177
178     /**
179      * Class to find and load templates
180      */

181     private static TemplateLoader templateLoader;
182
183     /**
184      * Class to use as dataStore
185      */

186     static DataStore dataStore;
187
188     /**
189      * Contains the config glossary values
190      */

191     private static HashMap JavaDoc configGlossary = new HashMap JavaDoc();
192
193     /**
194      * Public informations for preview class
195      */

196     public static String JavaDoc templatePath = "";
197
198     public static String JavaDoc templateLoaderClass = "";
199
200     public static String JavaDoc listTemplate = "";
201
202     public static String JavaDoc fileTemplate = "";
203
204     /**
205      * Public informations for mail class
206      */

207     public static String JavaDoc mailHost = "";
208
209     // public static String pathInfo = ""; // fx: removed
210

211     private static String JavaDoc logFolder;
212
213     private static String JavaDoc logLocation;
214
215     /**
216      * FX , LCZ | 2006/02/21 | Automatic redirection variable to default
217      * publication
218      */

219     private static String JavaDoc defaultPublication;
220
221     /**
222      * Returns where to find more information about cofax.
223      *
224      * @return The servletInfo value
225      */

226     public String JavaDoc getServletInfo() {
227
228         return "For more information about cofax, refer to http://www.cofax.org/";
229     }
230
231     /**
232      * Runs at servlet startup. It initializes variables and the database pool.
233      * It is ran by the servlet container itself.
234      *
235      * @param config
236      * Description of the Parameter
237      * @exception ServletException
238      * Description of the Exception
239      */

240     public final void init(ServletConfig JavaDoc config) throws ServletException JavaDoc {
241
242         super.init(config);
243
244         boolean errorInitializing = false;
245         templatePath = "";
246         String JavaDoc dataStoreName = "";
247         // TO DO: Check the config file for missing parameters.
248
try {
249             // Get the servlet's context object.
250
ServletContext JavaDoc context = getServletContext();
251
252             // contextPath is the file system path to the web application
253
// folder. i.e. /usr/local/tomcat/webapps/content/
254
contextPath = context.getRealPath("/");
255
256             // FX : Initializing log path
257
logFolder = contextPath;
258             try {
259                 logFolder = config.getInitParameter("logFolder");
260                 if (!(logFolder.endsWith(File.separator)))
261                     logFolder += File.separator;
262             } catch (Exception JavaDoc e) {
263                 logFolder = contextPath;
264                 System.err.println("[WARNING] logFolder parameter not initialized. 'contextPath' value used instead");
265             }
266
267             // FX , LCZ : Initializing default publication
268
try {
269                 defaultPublication = config.getInitParameter("defaultPublication");
270                 if (!(defaultPublication.endsWith("/")))
271                     defaultPublication += "/";
272             } catch (Exception JavaDoc e) {
273                 System.err.println("[WARNING] defaultPublication parameter not initialized.");
274             }
275
276             logLocation = logFolder + "cofax-cds.log";
277
278             // Load the configGlossary object
279
// These are text bits available to template designers.
280
for (Enumeration JavaDoc params = config.getInitParameterNames(); params.hasMoreElements();) {
281                 String JavaDoc paramName = (String JavaDoc) params.nextElement();
282                 if (paramName.indexOf("configGlossary:") > -1) {
283                     configGlossary.put(paramName, config.getInitParameter(paramName));
284                 }
285             }
286
287             // Set the maximum length allowed for a request URL
288
maxUrlLength = 512;
289             try {
290                 maxUrlLength = Integer.parseInt(config.getInitParameter("maxUrlLength"));
291             } catch (Exception JavaDoc e) {
292                 maxUrlLength = 512;
293             }
294
295             // Init the user agent detection tool.
296
WebBrowser.init(contextPath + config.getInitParameter("searchEngineRobotsDb"));
297
298             // load parameters for search engine templates
299
searchEngineFileTemplate = config.getInitParameter("searchEngineFileTemplate");
300             searchEngineListTemplate = config.getInitParameter("searchEngineListTemplate");
301
302             // Initialize the Package Tags cache
303
int cache_packageTags_maxTrack = Integer.parseInt(config.getInitParameter("cachePackageTagsTrack"));
304             int cache_packageTags_maxStore = Integer.parseInt(config.getInitParameter("cachePackageTagsStore"));
305             int cache_packageTags_refresh = Integer.parseInt(config.getInitParameter("cachePackageTagsRefresh"));
306             cacheOfPackageTags = new CofaxCache(cache_packageTags_maxTrack, cache_packageTags_maxStore, cache_packageTags_refresh, 0);
307
308             // Initilalize the Page cache
309
int cache_pages_maxTrack = Integer.parseInt(config.getInitParameter("cachePagesTrack"));
310             int cache_pages_maxStore = Integer.parseInt(config.getInitParameter("cachePagesStore"));
311             int cache_pages_refresh = Integer.parseInt(config.getInitParameter("cachePagesRefresh"));
312             int cache_pages_dirtyRead = Integer.parseInt(config.getInitParameter("cachePagesDirtyRead"));
313             cacheOfPages = new CofaxCache(cache_pages_maxTrack, cache_pages_maxStore, cache_pages_refresh, cache_pages_dirtyRead);
314
315             // Initialize the Templates cache
316
int cache_templates_maxTrack = Integer.parseInt(config.getInitParameter("cacheTemplatesTrack"));
317             int cache_templates_maxStore = Integer.parseInt(config.getInitParameter("cacheTemplatesStore"));
318             int cache_templates_refresh = Integer.parseInt(config.getInitParameter("cacheTemplatesRefresh"));
319             cacheOfTemplates = new CofaxCache(cache_templates_maxTrack, cache_templates_maxStore, cache_templates_refresh, 0);
320
321             // AVE : Initialisation des variables pour le filtrage IP et port
322
IPStartsWith = config.getInitParameter("IPStartsWith");
323             IPEquals = config.getInitParameter("IPEquals");
324             IPExceptionsStartsWith = config.getInitParameter("IPExceptionsStartsWith");
325             IPExceptionsEquals = config.getInitParameter("IPExceptionsEquals");
326             PortNumberEquals = config.getInitParameter("PortNumberEquals");
327             PortNameEquals = config.getInitParameter("PortNameEquals");
328
329             // Initialize the Template Loader
330
templatePath = config.getInitParameter("templatePath");
331             templatePath = contextPath + templatePath;
332             templateProcessorClass = config.getInitParameter("templateProcessorClass");
333             listTemplate = config.getInitParameter("defaultListTemplate");
334             fileTemplate = config.getInitParameter("defaultFileTemplate");
335             searchTemplate = config.getInitParameter("defaultSearchTemplate");
336             int templateMode = Integer.parseInt(config.getInitParameter("templateMode"));
337             int templateSearchLimit = Integer.parseInt(config.getInitParameter("templateSearchLimit"));
338             templateLoaderClass = config.getInitParameter("templateLoaderClass");
339             if (templatePath == null || templatePath.equals("")) {
340                 System.err.println("ERROR getting template path");
341                 errorInitializing = true;
342             }
343             try {
344                 Class JavaDoc c = Class.forName(templateLoaderClass);
345                 templateLoader = (TemplateLoader) c.newInstance();
346                 templateLoader.setTemplateRoot(templatePath);
347                 templateLoader.setDefaultIndex(listTemplate);
348                 templateLoader.setDefaultObject(fileTemplate);
349                 templateLoader.setTemplateMode(templateMode);
350                 templateLoader.setTemplateSearchLimit(templateSearchLimit);
351             } catch (Exception JavaDoc e) {
352                 System.err.println("Error loading template loader class:");
353                 e.printStackTrace(System.err);
354                 errorInitializing = true;
355             }
356
357             // get the value for the SMTP server
358
mailHost = config.getInitParameter("mailHost");
359
360             // Initialize the Data Store
361
boolean useDataStore = Boolean.valueOf(config.getInitParameter("useDataStore")).booleanValue();
362
363             dataStoreName = config.getInitParameter("dataStoreName");
364             dataStoreClass = config.getInitParameter("dataStoreClass");
365             redirectionClass = config.getInitParameter("redirectionClass");
366
367             // dbProperties = config.getInitParameter("dbProperties");
368
// dbProperties = contextPath + dbProperties;
369
Properties JavaDoc dbProps = new Properties JavaDoc();
370             dbProps.setProperty("drivers", config.getInitParameter("dataStoreDriver"));
371             dbProps.setProperty("logfile", config.getInitParameter("dataStoreLogFile"));
372             dbProps.setProperty(dataStoreName + ".url", config.getInitParameter("dataStoreUrl"));
373             dbProps.setProperty(dataStoreName + ".user", config.getInitParameter("dataStoreUser"));
374             dbProps.setProperty(dataStoreName + ".password", config.getInitParameter("dataStorePassword"));
375             dbProps.setProperty(dataStoreName + ".initconns", config.getInitParameter("dataStoreInitConns"));
376             dbProps.setProperty(dataStoreName + ".maxconns", config.getInitParameter("dataStoreMaxConns"));
377             dbProps.setProperty(dataStoreName + ".connusagelimit", config.getInitParameter("dataStoreConnUsageLimit"));
378             dbProps.setProperty(dataStoreName + ".testquery", config.getInitParameter("dataStoreTestQuery"));
379             dbProps.setProperty(dataStoreName + ".loglevel", config.getInitParameter("dataStoreLogLevel"));
380
381             if (!useDataStore) {
382                 dataStoreName = "cofax";
383                 dataStoreClass = "org.cofax.DummyDataStore";
384                 redirectionClass = "org.cofax.DummyRedirection";
385             }
386             try {
387                 Class JavaDoc c = Class.forName(dataStoreClass);
388                 dataStore = (DataStore) c.newInstance();
389                 if (useDataStore) {
390                     dataStore.init(dbProps);
391                     dataStore.setDataStoreName(dataStoreName);
392                     dataStore.setCache(cacheOfPackageTags, DataStore.PACKAGE_TAG_CACHE);
393                 }
394             } catch (Exception JavaDoc e) {
395                 System.err.println("Error loading data store class:");
396                 e.printStackTrace(System.err);
397                 errorInitializing = true;
398             }
399             try {
400                 Class JavaDoc c = Class.forName(redirectionClass);
401                 cofaxRedirect = (Redirection) c.newInstance();
402                 if (useDataStore) {
403                     cofaxRedirect.init(dataStore);
404                 }
405             } catch (Exception JavaDoc e) {
406                 System.err.println("Error loading redirection class:");
407                 e.printStackTrace(System.err);
408                 errorInitializing = true;
409             }
410
411             // Print the configuration to the console.
412
printConfiguration();
413
414         } catch (Exception JavaDoc e) {
415             System.err.println("Error reading configuration:");
416             e.printStackTrace(System.err);
417             errorInitializing = true;
418         }
419
420         // Login Handler
421
String JavaDoc loginHandlerName = config.getInitParameter("loginHandlerName");
422         ILoginHandler loginHandler = null;
423         try {
424             Class JavaDoc c = Class.forName(loginHandlerName);
425             loginHandler = (ILoginHandler) c.newInstance();
426             loginHandler.init(config);
427         } catch (Exception JavaDoc e) {
428             System.err.println("Error reading configuration:");
429             e.printStackTrace(System.err);
430             errorInitializing = true;
431         }
432
433         // Make variables available outside of Servlet
434
getServletContext().setAttribute("cacheOfPages", cacheOfPages);
435         getServletContext().setAttribute("cacheOfTemplates", cacheOfTemplates);
436         getServletContext().setAttribute("cacheOfPackageTags", cacheOfPackageTags);
437         getServletContext().setAttribute("dataStore", dataStore);
438         getServletContext().setAttribute("dataStoreName", dataStoreName);
439         getServletContext().setAttribute("dataStoreClass", dataStoreClass);
440         getServletContext().setAttribute("COFAX_VERSION", COFAX_VERSION);
441         getServletContext().setAttribute("applicationPath", contextPath);
442         getServletContext().setAttribute("templatePath", templatePath);
443         getServletContext().setAttribute("adminEmail", CofaxUtil.getString(configGlossary, "configGlossary:adminEmail"));
444         getServletContext().setAttribute("loginHandler", loginHandler);
445
446         // If there is an error initializing - throw an exception
447
if (errorInitializing) {
448             throw new ServletException JavaDoc("Could not initilize CDSServlet. This was likely the result of a misconfiguration.");
449         }
450     }
451
452     /**
453      * this method returns a String "private" or "public").
454      * the rules are defined in the web.xml file.
455      * the first set of rules accomplishes filtering with the client IP address
456      * with - IPStartsWith (ie : 123.254)
457      * - IPEquals (ie : 123.456.789.12)
458      * - IPExceptions (ie : 123.654.789.201)
459      * the second set of rules enables filtering with the access method to the
460      * webapp with the protocol name and the used port :
461      * - PortNameEquals (ex : https)
462      * - PortNumberEquals (ex : 443)
463      *
464      * This filter works with Apache mod_proxy and takes care about
465      * the IP of the "X-Forwarded-For" field
466      *
467      * @return "public" or "private"
468      * @author cedric aveline
469      */

470     private static String JavaDoc checkClientAccessRestriction(HttpServletRequest JavaDoc req) {
471         String JavaDoc returnedString = "";
472         String JavaDoc IPClient = "";
473         String JavaDoc IPForward = "";
474
475         if (req.getHeader("X-Forwarded-For") != null)
476             IPForward = req.getHeader("X-Forwarded-For");
477
478         String JavaDoc[] tabIPStartsWith = (IPStartsWith != null) ? IPStartsWith.split(",") : null;
479         String JavaDoc[] tabIPEquals = (IPEquals != null) ? IPEquals.split(",") : null;
480         String JavaDoc[] tabIPExceptionsStartsWith = (IPExceptionsStartsWith != null) ? IPExceptionsStartsWith.split(",") : null;
481         String JavaDoc[] tabIPExceptionsEquals = (IPExceptionsEquals != null) ? IPExceptionsEquals.split(",") : null;
482         String JavaDoc[] tabPortNumberEquals = (PortNumberEquals != null) ? PortNumberEquals.split(",") : null ;
483         String JavaDoc[] tabPortNameEquals = (PortNameEquals != null ) ? PortNameEquals.split(",") : null ;
484         
485         
486         // if arrays are null then do not apply any private filtering
487
// it means that the web.xml is not setup for filtering
488
// every client is considered as "public"
489

490         if ( tabIPStartsWith == null &&
491              tabIPEquals == null &&
492              tabIPExceptionsStartsWith == null &&
493              tabIPExceptionsEquals == null &&
494              tabPortNumberEquals == null &&
495              tabPortNameEquals == null
496                 )
497         {
498             // return "public" and finish processing
499
return "public";
500         }
501             
502         String JavaDoc[] tabIPforward = null;
503
504         if ((IPForward != null) || (tabIPforward.length > 0)) {
505             tabIPforward = IPForward.split(",");
506             IPClient = tabIPforward[tabIPforward.length - 1];
507         }
508
509         if (IPClient.length() < 1) {
510             IPClient = req.getRemoteAddr();
511         }
512
513         int cptIPStartsWith = 0;
514         int cptIPEquals = 0;
515         int cptIPExceptionsStartsWith = 0;
516         int cptIPExceptionsEquals = 0;
517         int cptPortNumberEquals = 0;
518         int cptPortNameEquals = 0;
519
520         boolean privateClient = false;
521
522         if (IPStartsWith.length() > 0) {
523             while (cptIPStartsWith < tabIPStartsWith.length) {
524                 if (IPClient.startsWith(tabIPStartsWith[cptIPStartsWith]))
525                     privateClient = true;
526                 cptIPStartsWith++;
527             }
528         }
529
530         if (IPEquals.length() > 0) {
531             while (cptIPEquals < tabIPEquals.length) {
532                 if (IPClient.equals(tabIPEquals[cptIPEquals]))
533                     privateClient = true;
534                 cptIPEquals++;
535             }
536         }
537
538         if (IPExceptionsStartsWith.length() > 0) {
539             while (cptIPExceptionsStartsWith < tabIPExceptionsStartsWith.length) {
540                 if (IPClient.startsWith(tabIPExceptionsStartsWith[cptIPExceptionsStartsWith]))
541                     privateClient = false;
542                 cptIPExceptionsStartsWith++;
543             }
544         }
545
546         if (IPExceptionsEquals.length() > 0) {
547             while (cptIPExceptionsEquals < tabIPExceptionsEquals.length) {
548                 if (IPClient.equals(tabIPExceptionsEquals[cptIPExceptionsEquals]))
549                     privateClient = false;
550                 cptIPExceptionsEquals++;
551             }
552         }
553
554         if (PortNumberEquals.length() > 0) {
555             while (cptPortNumberEquals < tabPortNumberEquals.length) {
556                 if (req.getServerPort() == Integer.parseInt(tabPortNumberEquals[cptPortNumberEquals]))
557                     privateClient = true;
558                 cptPortNumberEquals++;
559             }
560         }
561
562         if (PortNameEquals.length() > 0) {
563             while (cptPortNameEquals < tabPortNumberEquals.length) {
564                 if (req.getScheme().equals(tabPortNameEquals[cptPortNameEquals]))
565                     privateClient = true;
566                 cptPortNameEquals++;
567             }
568         }
569
570         if (privateClient) {
571             returnedString = "private";
572         } else {
573             returnedString = "public";
574         }
575
576         return returnedString;
577     }
578
579     /**
580      * Function: getLastModified Purpose: to return the age in miliseconds of
581      * the page being requested Args: req - the server request object
582      * representing the web request Returns: the number of miliseconds since
583      * 1/1/1970 that this page was last changed or -1 if no page exists or is to
584      * old Author: Sam Cohen Created: 10/05/2001 Revision History:
585      *
586      * @param req
587      * Description of the Parameter
588      * @return The lastModified value
589      */

590     /*
591      * ne sert pas public long getLastModified(HttpServletRequest req) {
592      *
593      * pageId = ""; String servletPath = req.getServletPath(); pathInfo =
594      * req.getPathInfo(); queryString = req.getQueryString();
595      *
596      * if (pathInfo == null) { pathInfo = servletPath; }
597      *
598      * pageId = pathInfo;
599      *
600      * if (!(queryString == null || queryString.equals(""))) { pageId += "?" +
601      * queryString; }
602      *
603      * if (cacheOfPages.isPageCached(pageId)) {
604      * cacheOfPages.incrementHitCount(pageId); CofaxPage page =
605      * cacheOfPages.getPage(pageId); // FX : modified if (page!=null) return
606      * (page.getLastModified()); } return (-1); }
607      */

608
609     /**
610      * Calls doGet for a post
611      *
612      * @param request
613      * Description of the Parameter
614      * @param response
615      * Description of the Parameter
616      * @exception ServletException
617      * Description of the Exception
618      * @exception IOException
619      * Description of the Exception
620      */

621     public final void doPost(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
622
623         doGet(request, response);
624
625     }
626
627     /**
628      * Responds to a url requested from the server. It gathers information from
629      * the request, determines if there is a cached object to serve the request,
630      * if so, send that back as the response. If not, put together a new
631      * response. Putting together a new response involves picking a template,
632      * parsing that template with the applicable data, then processing the
633      * template's own requests for additional data. Finally, return the page
634      * generated and determine if the page should be cached for further use.
635      *
636      * @param req
637      * Description of the Parameter
638      * @param res
639      * Description of the Parameter
640      * @exception ServletException
641      * Description of the Exception
642      * @exception IOException
643      * Description of the Exception
644      */

645     public final void doGet(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res) throws ServletException JavaDoc, IOException JavaDoc {
646
647         long cacheStart = System.currentTimeMillis();
648         CofaxPage page = new CofaxPage();
649         // Create a reference to a page object for the request
650
// page.reset();
651
// start fresh
652

653         String JavaDoc pageId = "";
654         String JavaDoc hostName = "";
655
656         String JavaDoc queryString = "";
657         String JavaDoc pathInfo = "";
658         String JavaDoc requestedUrl = "";
659         String JavaDoc requestedUrlWithoutQueryString = "";
660
661         String JavaDoc templateId = "";
662         HashMap JavaDoc glossary = new HashMap JavaDoc();
663         boolean usingJSP = false;
664
665         servletPath = req.getServletPath();
666         pathInfo = req.getPathInfo();
667         if (pathInfo == null) {
668             pathInfo = servletPath;
669         }
670
671         queryString = req.getQueryString();
672         Object JavaDoc tmp = req.getHeader("host");
673         // String hostName;
674

675         if (tmp != null) {
676             hostName = (String JavaDoc) tmp;
677         } else {
678             hostName = req.getServerName();
679         }
680
681         if (pathInfo.length() > maxUrlLength) {
682             page.setStatus(HttpServletResponse.SC_REQUEST_URI_TOO_LONG);
683             page.setErrorMsg("ERROR: Requested URI was too long. The administrator has set length to: " + maxUrlLength);
684         }
685
686         // Next line is effected by a bug in Tomcat blaking the servletPath
687
// variable....
688
// String requestedUrl = req.getScheme() + "://" + hostName +
689
// servletPath + pathInfo ;
690

691         // This is the replacement of the above line.
692
requestedUrl = req.getScheme() + "://" + hostName + req.getRequestURI();
693
694         // AVE : Modification de l'id en fonction du client
695
pageId = checkClientAccessRestriction(req) + pathInfo;
696
697         String JavaDoc contextName = req.getContextPath();
698         cofaxLog("contextName= " + contextName + "\nrequestedUrl= "
699          + requestedUrl);
700         if (requestedUrl.endsWith(contextName + "/") || requestedUrl.endsWith(contextName)) {
701             if (!requestedUrl.endsWith("/"))
702                 requestedUrl += "/";
703             String JavaDoc _redirection = requestedUrl + defaultPublication + "/";
704             cofaxLog("Redirection= " + _redirection);
705             res.sendRedirect(_redirection);
706             // System.out.println("return !!");
707
return;
708         }
709
710         // System.out.println("pathInfo : " + pathInfo);
711

712         requestedUrlWithoutQueryString = requestedUrl;
713         // Generating a unique ID for the page.
714
// Currently, the pathInfo + queryString is used as the page ID
715
// since all the information required to build the
716
// page from the request is contained there.
717
// Adding queryString to requestedUrl and pageId
718
if (!(queryString == null || queryString.equals(""))) {
719             requestedUrl += "?" + queryString;
720             pageId += "?" + queryString;
721         }
722         try {
723
724             // FX: Checking if the page is already in cache with SC_OK status
725
if ((cacheOfPages.isPageCached(pageId)) && (cacheOfPages.getPage(pageId).getStatus() == HttpServletResponse.SC_OK)
726
727             ) {
728
729                 // FX : this page is already in cache
730

731                 page = cacheOfPages.getPage(pageId); // FX : getting the page
732
// from cache
733

734                 // FX : checking the page built date before sending ...
735
// otherwise let's rebuild it.
736

737                 if ((System.currentTimeMillis() - page.getLastModified()) < cacheOfPages.getRefreshInterval()) {
738                     // the page is new enough, let's send it to the client.
739
/*
740                      * added By FX : writing what is in cache on the
741                      * outputstream
742                      */

743
744                     cacheOfPages.incrementHitCount(pageId); // FX : increasing
745
// hit count for
746
// tracking
747

748                     page.setStatus(HttpServletResponse.SC_OK);
749                     page.setServingClient(req.getRemoteAddr());
750
751                     sendHeaders(page, res);
752
753                     ServletOutputStream JavaDoc out = res.getOutputStream();
754                     String JavaDoc content = new String JavaDoc(page.toString()); // copying
755
// the data
756
// into
757
// temporary
758
// buffer.
759
out.print(content);
760                     page.setEndBuildTime();
761                     out.print(page.pageAge());
762                     out.print(page.cacheTime(cacheStart));
763                     out.flush(); // ROBIN : to be sure that the data are
764
// written.
765
out.close();
766
767                     /* FX : end of modification */
768                     cacheOfPages.CleanIfPossible();
769                     return; // FX : end of delivering servlet.
770
}
771
772             }
773
774             page.reset(); // FX : let's start with a blank page.
775

776             // Initialize the Glossary and Page objects for this request
777
// System.out.println("page : "+req.getRequestURI()+" -
778
// Initialisation du glossaire ...");
779
glossary = initializeGlossary(req, page, pathInfo, requestedUrl, queryString, requestedUrlWithoutQueryString, pageId, hostName);
780
781             
782
783             // System.out.println(glossary.values().toString());
784
// System.out.println("-- glossaire OK");
785

786             // initializeGlossary could have set status to not ok.
787

788             // System.out.println("PAGE : "+page);
789
// System.out.println("Status : "+page.getStatus());
790

791             if (page.getStatus() != HttpServletResponse.SC_OK) {
792                 throw new ServletException JavaDoc("Cofax Internal Error");
793             }
794
795             // If request:redirectUrl has a value, then redirect to that
796
// location.
797
String JavaDoc urlToRedirectTo = CofaxUtil.getString(glossary, "request:urlToRedirectTo");
798
799             // System.out.println("Redirect : "+urlToRedirectTo);
800

801             if (!urlToRedirectTo.equals("")) {
802                 res.sendRedirect(urlToRedirectTo);
803                 return;
804             }
805
806             // if we are here then the page wasn't in cache so we will build it
807
addToGlossary(req, glossary);
808             // Add more members to the glossary pertaining to this request
809
page.setLastModified(Long.parseLong((String JavaDoc) glossary.get("request:todayMilliSecs")));
810             templateLoader.setTemplateSearch(templateLoader.getTemplateRoot() + "/" + glossary.get("request:templateSearch").toString());
811
812             templateId = templateLoader.choose(glossary.get("request:fileNameWithExtension").toString(), CofaxUtil.getString(glossary, "request:template"),
813                     CofaxUtil.getString(glossary, "request:fileNameExtension"));
814             if (templateId.endsWith(".JSP") || templateId.endsWith(".jsp")) {
815                 usingJSP = true;
816                 templateId = templateLoader.getResource(templateId, contextPath);
817             } else {
818                 usingJSP = false;
819             }
820
821             glossary.put("request:templateId", templateId);
822             if (templateId.equals("")) {
823                 page.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
824                 page.setErrorMsg("Error: Template not found to satisfy request.");
825             }
826
827             // Get a Data Store class for this request
828
DataStore db = null;
829             db = (DataStore) (Class.forName(dataStoreClass)).newInstance();
830
831             if (db == null) {
832                 page.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
833                 page.setErrorMsg("Error: Could not create DataStore object db.");
834                 throw new ServletException JavaDoc("Cofax Internal Error");
835             } else if (page.getStatus() == HttpServletResponse.SC_OK) {
836                 Glossary cofaxGlossary = new Glossary();
837                 page.setGlossary(cofaxGlossary);
838                 page.addToGlossary(glossary);
839                 page.setTemplateLoader(templateLoader);
840                 page.setDataStore(db);
841                 page.setServingPage(req.getRequestURI());
842                 page.setServingClient(req.getRemoteAddr());
843
844                 if (usingJSP) { // Process JSP templates
845
req.setAttribute("cofaxPage", page);
846                 
847                     
848                     try {
849                         CofaxJspResponse jspResponse = new CofaxJspResponse(res, page);
850                         RequestDispatcher JavaDoc dispatcher = getServletContext().getRequestDispatcher(templateId);
851                         dispatcher.include(req, jspResponse);
852                         if (page.getStatus() == HttpServletResponse.SC_MOVED_TEMPORARILY) {
853                             res.sendRedirect(jspResponse.getRedirect());
854                             return;
855                         }
856                         /*
857                          * fx :testing if the mimetype is passed for generating
858                          * the page
859                          */

860                         String JavaDoc _output = req.getParameter("output");
861                         if (_output != null) {
862                             page.putHeader("Content-Type", _output);
863                         }
864                         /* --------------------- */
865                         page.append(jspResponse.toString());
866                     } catch (IOException JavaDoc ioe) {
867                         String JavaDoc errText = ioe.toString();
868                         page.setErrorMsg(errText);
869                         System.err.println(ioe);
870                         throw new ServletException JavaDoc("Cofax Internal IOException");
871                     } catch (ServletException JavaDoc e) {
872                         String JavaDoc errText = e.toString();
873                         page.setErrorMsg(errText);
874                         System.err.println(e);
875                         throw new ServletException JavaDoc("Cofax Internal ServletException");
876                     } catch (Exception JavaDoc e) {
877                         String JavaDoc errText = e.toString();
878                         page.setErrorMsg(errText);
879                         System.err.println(e);
880                         throw new ServletException JavaDoc("Cofax Internal Exception");
881                     }
882
883                 } else { // Process TemplateProcessor templates
884

885                     // Load the template from the template cache or using the
886
// Template Loader
887
CofaxPage template;
888                     cacheOfTemplates.incrementHitCount(templateId);
889                     if (cacheOfTemplates.isPageCached(templateId)) {
890                         template = cacheOfTemplates.getPage(templateId);
891                     } else {
892                         template = templateLoader.load(templateId);
893                     }
894
895                     // Get a Template Processor class for this request
896
TemplateProcessor tp = null;
897                     tp = (TemplateProcessor) (Class.forName(templateProcessorClass)).newInstance();
898
899                     tp.setPage(page);
900                     tp.setTemplate(template);
901
902                     if (tp.applyTemplate()) {
903                         page.setStatus(HttpServletResponse.SC_OK);
904                     } else {
905                         if (page.getStatus() == HttpServletResponse.SC_OK) {
906                             page.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
907                         }
908                         throw new ServletException JavaDoc("Cofax Internal Error");
909                     }
910                     /*
911                      * removed by FX, cache is managed under this block // If
912                      * there was no error, continue if (page.getStatus() ==
913                      * HttpServletResponse.SC_OK) { // Cache the template if
914                      * (cacheOfTemplates.shouldPageBeCached(templateId)) {
915                      * cacheOfTemplates.addPageToCache(templateId, template); } }
916                      */

917                 }
918                 // If there was no error, continue
919
if (page.getStatus() == HttpServletResponse.SC_OK) {
920                     page.append("\r\n<!-- Powered By: " + CofaxUtil.getString(glossary, "configGlossary:poweredBy") + " at "
921                             + CofaxUtil.getString(glossary, "configGlossary:installationAt") + " -->\r\n");
922                     page.setEndBuildTime();
923                     page.append(page.buildTime(cacheStart));
924                     if (!page.mustBeCached()) {
925                         page.append("\r\n<!-- page was generated without the cache -->");
926                     }
927                     cacheOfPages.incrementHitCount(pageId);
928                     // set all of the headers here
929
page.putHeader("X-Cofax", COFAX_VERSION);
930                     page.putHeader("Server", "Cofax/" + COFAX_VERSION);
931                     if (CofaxUtil.getString(glossary, "PublicationGlossary:P3PPolicyRef") != "") {
932                         String JavaDoc P3P = CofaxUtil.getString(glossary, "PublicationGlossary:P3PPolicyRef") + ", CP="
933                                 + CofaxUtil.getString(glossary, "PublicationGlossary:P3PCompactHeader");
934                         page.putHeader("P3P", P3P);
935                     }
936                     // Cache the page if it qualifies
937
if (cacheOfPages.shouldPageBeCached(pageId) && page.mustBeCached()) {
938                         page.setPageId(pageId);
939                         cacheOfPages.addPageToCache(pageId, page);
940                     }
941                 }
942
943             }
944         } catch (Exception JavaDoc e) {
945             String JavaDoc errMsg = e.toString();
946             if (page.getStatus() == HttpServletResponse.SC_OK) {
947                 page.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
948             }
949             if (page.getErrorMsg().equals("")) {
950                 page.setErrorMsg(errMsg);
951             }
952             if (errMsg.indexOf("Cofax Internal Error") == -1) {
953                 System.err.print("Cofax Handeled Internal Error.\n ");
954                 System.err.print(" Cofax Error: " + errMsg + "\n");
955                 System.err.print(" Error: " + errMsg + "\n");
956                 System.err.print(" Stack: ");
957                 e.printStackTrace(System.err);
958                 System.err.print("\n");
959             }
960         } finally {
961             // Print out the page.
962
boolean cacheError = false;
963             if (page.getStatus() != HttpServletResponse.SC_OK) {
964                 if (page.getStatus() == HttpServletResponse.SC_NOT_FOUND) {
965                     cacheError = true;
966                 }
967
968                 if (CofaxUtil.getString(glossary, "PublicationGlossary:errorHeaders").equals("1")) {
969                     res.sendError(page.getStatus());
970                 } else {
971                     page.reset();
972                     page.append("<title>Cofax Error -- " + req.getRequestURI() + "</title>\n");
973                     page.append("<body bgcolor=FFFFFF>\n");
974                     page.append("<h2>An Error Has Occured</h2>");
975                     page.append("Cofax has encountered and error while processing your request.<br>\n");
976                     page.append("Cofax Version: " + COFAX_VERSION + "<br><br>\n");
977                     page.append("<dd><font color=FF2121>Error Message:</font> " + page.getStatus() + ": ");
978                     page.append(page.getErrorMsg() + "<br>\n");
979                     page.append("<dd>Request: " + req.getRequestURI() + "<br>\n");
980                     page.append("<dd>Template: " + templateId + "<br><br>\n");
981                     page.append("Please try one of the following:<ul>\n");
982                     page.append("<li><a HREF=javascript:window.location.reload()>reload this page</a></li>\n");
983                     page.append("<li><a HREF=javascript:window.history.back()>return to your previous page</a></li>\n");
984                     page.append("<li><a HREF=" + req.getContextPath() + "/" + CofaxUtil.getString(glossary, "request:pubName"));
985                     page.append(">go to the home for this publication</a></li>\n");
986                     page.append("<li><a HREF=mailto:i" + CofaxUtil.getString(glossary, "configGlossary:adminEmail") + ">contact "
987                             + CofaxUtil.getString(glossary, "configGlossary:adminTitle") + "</a></li></ul>\n");
988                     System.err.print("Cofax encountered and handeled a delivery Error of Type: " + page.getStatus() + "\n");
989                     System.err.print(" Error: " + page.getErrorMsg() + "\n");
990                     System.err.print(" Serving: " + req.getRequestURI() + "\n");
991
992                 }
993             }
994             if (!cacheError) // modified by FX.
995
{
996                 // page.setStatus(HttpServletResponse.SC_OK); removed by FX
997
// ROBIN, status already set.
998
sendHeaders(page, res);
999
1000                ServletOutputStream JavaDoc out = res.getOutputStream();
1001                page.setEndBuildTime();
1002                String JavaDoc content = new String JavaDoc(page.toString());
1003                out.print(content);
1004                // out.print(page.pageAge());
1005
// out.print(page.cacheTime(cacheStart));
1006
out.flush(); // added by FX .
1007
out.close();
1008
1009            } // end of modification
1010
}
1011
1012        cacheOfPages.CleanIfPossible();
1013
1014        return;
1015    }
1016
1017    /**
1018     * Sends the headers to the client that have been set for this page.
1019     *
1020     * @param page
1021     * Description of the Parameter
1022     * @param res
1023     * Description of the Parameter
1024     */

1025    private void sendHeaders(CofaxPage page, HttpServletResponse JavaDoc res) {
1026
1027        HashMap JavaDoc headers = page.getHeaders();
1028        res.setContentType(page.getHeader("Content-Type"));
1029
1030        if (headers != null && !headers.isEmpty()) {
1031            for (Iterator JavaDoc i = headers.keySet().iterator(); i.hasNext();) {
1032                String JavaDoc headerName = i.next().toString();
1033                String JavaDoc headerValue = headers.get(headerName).toString();
1034                res.setHeader(headerName, headerValue);
1035            }
1036        }
1037    }
1038
1039    
1040    /**
1041     * Performs servlet cleanup such as closing down the database pool.
1042     */

1043    public void destroy() {
1044
1045        dataStore.destroy();
1046        super.destroy();
1047
1048    }
1049
1050    /**
1051     * Parses a request into an array of items.
1052     *
1053     * @param req
1054     * Description of the Parameter
1055     * @param page
1056     * Description of the Parameter
1057     * @return Description of the Return Value
1058     */

1059    private static HashMap JavaDoc initializeGlossary(HttpServletRequest JavaDoc req, CofaxPage page, String JavaDoc pathInfo, String JavaDoc requestedUrl, String JavaDoc queryString,
1060            String JavaDoc requestedUrlWithoutQueryString, String JavaDoc pageId, String JavaDoc hostName) {
1061
1062        HashMap JavaDoc glossary = new HashMap JavaDoc();
1063
1064        Enumeration JavaDoc e;
1065        String JavaDoc tag = "";
1066        String JavaDoc value = "";
1067
1068        // Loops through HTTP_HEADERS and place them in the glossary.
1069
for (e = req.getHeaderNames(); e.hasMoreElements();) {
1070            tag = (String JavaDoc) e.nextElement();
1071            value = req.getHeader(tag);
1072            glossary.put("http_header:" + tag, value + "");
1073        }
1074
1075        // If passed "refresh" in the queryString
1076
// then force a new result to the client
1077
String JavaDoc refresh = req.getParameter("refresh");
1078        if (!(refresh == null || refresh.equals("true"))) {
1079            page.putHeader("Expires", "0");
1080            page.putHeader("Pragma", "no-cache");
1081            page.putHeader("Cache-Control", "no-cache");
1082        }
1083
1084        // Create a redirection path if requesting a section and missing
1085
// a trailing slash.
1086
// TO DO: Move this code to a function.
1087
// It blanks out fileName if it does not contain a dot.
1088
// (not a valid fileName, probably a section).
1089
boolean isSection = false;
1090        int positionOfLastSlash = pathInfo.lastIndexOf('/');
1091        if (positionOfLastSlash != -1) {
1092            String JavaDoc fileName = pathInfo.substring(positionOfLastSlash);
1093            if (fileName.indexOf('.') == -1) {
1094                isSection = true;
1095            }
1096        } else {
1097            isSection = true;
1098        }
1099        // System.out.println("IsSection : " + isSection);
1100
// System.out.println("path : " + pathInfo);
1101
String JavaDoc urlToRedirectTo = "";
1102        if (isSection && !pathInfo.endsWith("/")) {
1103            if (requestedUrl.indexOf("?") > -1) {
1104                urlToRedirectTo = requestedUrlWithoutQueryString + "/?" + queryString;
1105            } else {
1106                urlToRedirectTo = requestedUrl + "/";
1107            }
1108            // System.out.println("urlToRedirectTo : " + urlToRedirectTo);
1109
glossary.put("request:urlToRedirectTo", urlToRedirectTo);
1110        }
1111
1112        // Adjust the queryString and override template
1113
// if the browser is a crawler.
1114
// This is important because you need the pageID to be
1115
// correct for caching.
1116
WebBrowser browser = new WebBrowser(req);
1117        if (browser.isCrawler()) {
1118            if (isSection) {
1119                queryString = "template=" + searchEngineListTemplate;
1120                glossary.put("request:template", searchEngineListTemplate);
1121            } else {
1122                queryString = "template=" + searchEngineFileTemplate;
1123                glossary.put("request:template", searchEngineFileTemplate);
1124            }
1125        }
1126
1127        // Get's a redirection from the redirection class
1128
String JavaDoc redirectPathInfo = cofaxRedirect.getRedirection(pathInfo.toLowerCase());
1129
1130        if (!redirectPathInfo.equals("") && redirectPathInfo.indexOf("INVALID") == -1) {
1131            redirectPathInfo = req.getScheme() + "://" + hostName + req.getContextPath() + redirectPathInfo;
1132            glossary.put("request:urlToRedirectTo", redirectPathInfo);
1133        } else if (redirectPathInfo.indexOf("INVALID") > -1) {
1134            page.setStatus(HttpServletResponse.SC_NOT_FOUND);
1135            page.setErrorMsg("ERROR: Requested URI contained " + redirectPathInfo);
1136            return glossary;
1137        }
1138
1139        glossary.put("request:requestedUrlWithoutQueryString", requestedUrlWithoutQueryString);
1140        glossary.put("request:url", requestedUrlWithoutQueryString);
1141        glossary.put("request:pageId", pageId);
1142        glossary.put("request:requestedUrl", requestedUrl);
1143
1144        try {
1145            glossary.put("request:requestedUrlEncoded", URLEncoder.encode(requestedUrl, "UTF-8"));
1146        } catch (UnsupportedEncodingException JavaDoc uee) {
1147            System.err.println("URLEncoder error : ");
1148            uee.printStackTrace(System.err);
1149        }
1150
1151        glossary.put("request:queryString", queryString + "");
1152        glossary.put("request:query_string", queryString + "");
1153        glossary.put("request:pathInfo", pathInfo);
1154        glossary.put("request:hostName", hostName);
1155        glossary.put("request:cofaxVersion", COFAX_VERSION);
1156
1157        // copy values from configGlossary into this request's glossary
1158
for (Iterator JavaDoc i = configGlossary.keySet().iterator(); i.hasNext();) {
1159            String JavaDoc key2 = i.next().toString();
1160            String JavaDoc value2 = configGlossary.get(key2).toString();
1161            glossary.put(key2, value2);
1162        }
1163        
1164// AVE : Ajout d'une variable "client" pour personnaliser le
1165
// squelette
1166
glossary.put("client", checkClientAccessRestriction(req)); // for backward compatibilty
1167
glossary.put("request:client", checkClientAccessRestriction(req)); // use this instead
1168

1169        // RBN : Adding contextPath which is a static value to the glossary
1170
// to provide it to the templates
1171
glossary.put("request:contextPath", req.getContextPath());
1172
1173        return glossary;
1174    }
1175
1176    // end initializeGlossary
1177

1178    /**
1179     * This adds to the glossary object, the variable stack of Cofax, data
1180     * gathered from the request. This is the main request parser routine. It
1181     * also checks the request for security related items.
1182     *
1183     * @param req
1184     * The feature to be added to the ToGlossary attribute
1185     * @param glossary
1186     * The feature to be added to the ToGlossary attribute
1187     */

1188    private final static void addToGlossary(HttpServletRequest JavaDoc req, HashMap JavaDoc glossary) {
1189
1190        // Get pathInfo from glossary.
1191
// initializeGlossary may have adjusted it.
1192
String JavaDoc pathInfo = glossary.get("request:pathInfo").toString();
1193
1194        String JavaDoc pub = "";
1195        String JavaDoc date = "";
1196        String JavaDoc section = "";
1197        String JavaDoc fileNameWithExtension = "";
1198        String JavaDoc fileName = "";
1199        // boolean gotDate = false; NOT USED
1200
int datePartCount = 0;
1201        String JavaDoc fileNameExtension = "";
1202        Date JavaDoc dateObject = new Date JavaDoc();
1203        long dateMilliSecs = dateObject.getTime();
1204        int count = 0;
1205        // Split pathInfo by '/' to parse variables from it.
1206
Iterator JavaDoc paths = CofaxUtil.split("/", pathInfo).iterator();
1207
1208        while (paths.hasNext()) {
1209            // content/daily_news/2001/07/16/sports/
1210
// Get and add the next piece of the path to parse
1211
String JavaDoc path = (String JavaDoc) paths.next();
1212            glossary.put("request:pathPart[" + count + "]", path);
1213
1214            if (path.indexOf('.') > -1) {
1215                fileNameWithExtension = path;
1216                // If we find a '.' then we have a file name
1217
} else {
1218                // Get a date from the path.
1219
if (CofaxUtil.isDigits(path) && datePartCount <= 3 && !path.equals("")) {
1220                    datePartCount++;
1221                    if (datePartCount == 1) {
1222                        date = path;
1223                    } else if (datePartCount == 2) {
1224                        date = date + "/" + path;
1225                    } else if (datePartCount == 3) {
1226                        date = date + "/" + path;
1227                    }
1228                } else {
1229                    if (count == 1) {
1230                        pub = path;
1231                    } else {
1232                        if (section.equals("")) {
1233                            // If we don't find a '.' then we have a section
1234
section = path;
1235                        } else {
1236                            section = section + "/" + path;
1237                        }
1238                    }
1239                }
1240            }
1241            count++;
1242        }
1243
1244        // If the path parsing assembled a section, then add this
1245
// to the glossary.
1246
if (section.equals("")) {
1247            glossary.put("request:templateSearch", pub);
1248        } else {
1249            glossary.put("request:templateSearch", pub + "/" + section);
1250        }
1251
1252        // Removing the .htm extension from the fileName.
1253
// This is used extensively as a SLUG.
1254
int dotLoc = fileNameWithExtension.lastIndexOf('.');
1255        if (dotLoc > -1) {
1256            fileName = fileNameWithExtension.substring(0, dotLoc);
1257            fileNameExtension = fileNameWithExtension.substring(dotLoc);
1258        }
1259
1260        glossary.put("request:date", date);
1261        glossary.put("request:today", CofaxUtil.getDateFormat("yyyy/MM/dd", "") + "");
1262        glossary.put("request:todayMilliSecs", String.valueOf(dateMilliSecs));
1263        glossary.put("request:date_format_1", CofaxUtil.getDateFormat("EEEE, MMMM d, yyyy", date) + "");
1264        glossary.put("request:day_of_week", CofaxUtil.getDateFormat("EEE", date) + "");
1265        glossary.put("request:name", section);
1266        glossary.put("request:section", section);
1267        glossary.put("request:publication", pub);
1268        glossary.put("request:pubName", pub);
1269        glossary.put("request:path_info", pathInfo);
1270        glossary.put("request:file_name", fileName);
1271        glossary.put("request:fileName", fileName);
1272        glossary.put("request:fileNameWithExtension", fileNameWithExtension);
1273        glossary.put("request:fileNameExtension", fileNameExtension);
1274
1275        // Loops through form and queryString passed parameters and puts
1276
// them in the glossary. Note that this loop should be the last
1277
// place to add to the glossary before template processing.
1278
// It allows users to override values in the "request:" namespace.
1279
// Very important!
1280

1281        for (Enumeration JavaDoc e = req.getParameterNames(); e.hasMoreElements();) {
1282            String JavaDoc tag = (String JavaDoc) e.nextElement();
1283            glossary.put("request:" + tag, req.getParameter(tag) + "");
1284            if (tag.equals("search")) {
1285                glossary.put("request:template", searchTemplate);
1286            }
1287        }
1288
1289        // Fix the template override (request:template)
1290
// if sent as a parameter.
1291
String JavaDoc requestTemplate = req.getParameter("template");
1292        if (requestTemplate != null && !requestTemplate.equals("")) {
1293            requestTemplate = CofaxUtil.replace(requestTemplate, "../", "");
1294            glossary.put("request:template", requestTemplate);
1295        }
1296    }
1297
1298    /**
1299     * Description of the Method
1300     */

1301    private static void printConfiguration() {
1302        System.out.println("--------------- COFAX CONFIGURATION --------------");
1303        System.out.println("\n\nCofax version: " + COFAX_VERSION + "\n");
1304        System.out.println("CDSServlet CONFIGURATION:");
1305        System.out.println("Cache Of Package Tags");
1306        System.out.println(cacheOfPackageTags.toString());
1307        System.out.println("\nCache Of Pages");
1308        System.out.println(cacheOfPages.toString());
1309        System.out.println("\nCache Of Templates");
1310        System.out.println(cacheOfTemplates.toString());
1311        System.out.println("\nTemplate Loader");
1312        System.out.println(templateLoader.toString());
1313        System.out.println("\nRedirection");
1314        System.out.println(cofaxRedirect.toString());
1315        System.out.println("\nTemplate Processor");
1316        System.out.println("Instance Of: " + templateProcessorClass);
1317        System.out.println("\nSearch Engine Templates");
1318        System.out.println("File Template: " + searchEngineFileTemplate);
1319        System.out.println("List Template: " + searchEngineListTemplate);
1320        System.out.println("Search Template: " + searchTemplate);
1321        System.out.println("\nData Store");
1322        System.out.println(dataStore.toString());
1323        System.out.println("End CONFIGURATION, begin normal operation\n\n");
1324        System.out.println("------------------------------");
1325
1326    }
1327
1328    // FX : adding log facility for CDS SERVLET
1329
public static void cofaxLog(String JavaDoc input) {
1330        input = new java.util.Date JavaDoc().toString() + " - " + input;
1331        try {
1332            PrintWriter JavaDoc fileOutputStream = new PrintWriter JavaDoc(new FileWriter JavaDoc(logLocation, true));
1333            fileOutputStream.println(input);
1334            fileOutputStream.close();
1335
1336        } catch (IOException JavaDoc e) {
1337            System.err.println("CofaxCDSLog Error : " + e.toString());
1338        }
1339    }
1340
1341}
1342
Popular Tags