KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > bin > Jahia


1 // $Id: Jahia.java 16483 2007-02-21 15:35:42Z xlawrence $
2
//
3
// ____.
4
// __/\ ______| |__/\. _______
5
// __ .____| | \ | +----+ \
6
// _______| /--| | | - \ _ | : - \_________
7
// \\______: :---| : : | : | \________>
8
// |__\---\_____________:______: :____|____:_____\
9
// /_____|
10
//
11
// . . . i n j a h i a w e t r u s t . . .
12
//
13
//
14
// Jahia
15
//
16
// 30.10.2000 EV added in jahia.
17
// 17.01.2001 AK change dispatcher method.
18
// 19.01.2001 AK replace methods doGet and doPost by the method service.
19
// 29.01.2001 AK change re-init way, remove sets methods.
20
// 10.02.2001 AK pseudo-bypass the login by forwarding request attributes.
21
// 27.03.2001 AK javadoc and change the access to JahiaPrivateSettings.load().
22
// 28.03.2001 AK add some jahia path variables.
23
// 29.03.2001 AK rename jahia.basic file in jahia.skeleton.
24
// 20.04.2001 AK bugfix request uri.
25
// 17.05.2001 AK tomcat users check during init.
26
// 23.05.2001 NK bug two same parameter in url resolved by removing pathinfo data from request uri
27
//
28

29
30 package org.jahia.bin;
31
32 import java.io.File JavaDoc;
33 import java.io.FileInputStream JavaDoc;
34 import java.io.IOException JavaDoc;
35 import java.io.InputStream JavaDoc;
36 import java.text.MessageFormat JavaDoc;
37 import java.util.Enumeration JavaDoc;
38 import java.util.Hashtable JavaDoc;
39
40 import javax.servlet.ServletConfig JavaDoc;
41 import javax.servlet.ServletContext JavaDoc;
42 import javax.servlet.ServletException JavaDoc;
43 import javax.servlet.http.Cookie JavaDoc;
44 import javax.servlet.http.HttpServletRequest JavaDoc;
45 import javax.servlet.http.HttpServletResponse JavaDoc;
46 import javax.servlet.http.HttpSession JavaDoc;
47
48 import org.jahia.data.JahiaData;
49 import org.jahia.exceptions.JahiaException;
50 import org.jahia.exceptions.JahiaForbiddenAccessException;
51 import org.jahia.exceptions.JahiaOperationNotAllowedException;
52 import org.jahia.exceptions.JahiaPageNotFoundException;
53 import org.jahia.exceptions.JahiaSecurityException;
54 import org.jahia.exceptions.JahiaSessionExpirationException;
55 import org.jahia.exceptions.JahiaSiteNotFoundException;
56 import org.jahia.exceptions.JahiaSiteAndPageIDMismatchException;
57 import org.jahia.exceptions.services.ServiceNotFoundException;
58 import org.jahia.mbeans.JahiaMBeanServer;
59 import org.jahia.operations.OperationManager;
60 import org.jahia.params.ParamBean;
61 import org.jahia.pipelines.Pipeline;
62 import org.jahia.pipelines.PipelineDescriptor;
63 import org.jahia.pipelines.PipelineException;
64 import org.jahia.pipelines.valves.SsoValve;
65 import org.jahia.registries.EnginesRegistry;
66 import org.jahia.registries.JahiaContainerDefinitionsRegistry;
67 import org.jahia.registries.JahiaFieldDefinitionsRegistry;
68 import org.jahia.registries.JahiaListenersRegistry;
69 import org.jahia.registries.ServicesRegistry;
70 import org.jahia.registries.SharedTemplatePackagesRegistry;
71 import org.jahia.registries.locks.JahiaLocksRegistry;
72 import org.jahia.resourcebundle.JahiaResourceBundle;
73 import org.jahia.resourcebundle.ResourceMessage;
74 import org.jahia.security.license.License;
75 import org.jahia.security.license.LicenseConstants;
76 import org.jahia.security.license.LicenseManager;
77 import org.jahia.security.license.LicensePackage;
78 import org.jahia.security.license.Limit;
79 import org.jahia.services.cache.CacheFactory;
80 import org.jahia.services.database.ConnectionDispenser;
81 import org.jahia.services.usermanager.JahiaUser;
82 import org.jahia.settings.SettingsBean;
83 import org.jahia.urls.ServletURL;
84 import org.jahia.urls.URI;
85 import org.jahia.urls.URICodec;
86 import org.jahia.utils.JahiaChrono;
87 import org.jahia.utils.JahiaConsole;
88 import org.jahia.utils.LanguageCodeConverters;
89 import org.jahia.utils.PathResolver;
90 import org.jahia.utils.Version;
91 import org.jahia.utils.WebAppPathResolver;
92 import org.jahia.utils.modifier.TomcatUsersModifier;
93 import org.jahia.utils.xml.betwixt.XmlReader;
94 import org.springframework.beans.factory.BeanFactory;
95 import org.springframework.beans.factory.xml.XmlBeanFactory;
96 import org.xml.sax.SAXException JavaDoc;
97
98 /**
99  * desc: This is the main servlet of Jahia.
100  * ----=[ Welcome to the Jahia portal ]=----
101  *
102  * Copyright: Copyright (c) 2002
103  * Company: Jahia Ltd
104  *
105  * @author Eric Vassalli
106  * @author Alexandre Kraft
107  * @author Khue N'Guyen
108  * @version 1.0
109  */

110 public final class Jahia extends org.apache.struts.action.ActionServlet implements
111     JahiaInterface {
112     private static org.apache.log4j.Logger logger =
113         org.apache.log4j.Logger.getLogger(Jahia.class);
114
115     /** "jahia" string constant in order to avoid creating a new string for
116      * each concole output. */

117     static private final String JavaDoc JAHIA_STR = "jahia";
118
119     /** this class name */
120     static public final String JavaDoc CLASS_NAME = "Jahia";
121
122     /** properties filename */
123     static private final String JavaDoc PROPERTIES_FILENAME = "jahia.properties";
124
125     /** properties filename */
126     static private final String JavaDoc PRELOAD_CLASSES_FILENAME = "preloadclasses.xml";
127
128     /** license filename */
129     static private final String JavaDoc LICENSE_FILENAME = "license.xml";
130
131     /** skeleton properties filename */
132     static private final String JavaDoc PROPERTIES_BASIC = "jahia.skeleton";
133
134     /** ... */
135     static private final String JavaDoc JAHIA_LAUNCH = "jahiaLaunch";
136
137     /** ... */
138     static private final String JavaDoc GET_REQUEST = "GET";
139
140     /** ... */
141     static private final String JavaDoc POST_REQUEST = "POST";
142
143     /** ... */
144     static private final String JavaDoc INIT_PARAM_WEBINF_PATH = "webinf_path";
145
146     /** ... */
147     static private final String JavaDoc INIT_PARAM_LOGGING_LEVEL = "logging_level";
148
149     // web app descriptor initialization parameter
150
static private final String JavaDoc INIT_PARAM_SUPPORTED_JDK_VERSIONS =
151         "supported_jdk_versions";
152
153     static private final String JavaDoc INIT_PARAM_ADMIN_SERVLET_PATH =
154         "admin_servlet_path";
155
156     static private final String JavaDoc INIT_PARAM_CONFIG_SERVLET_PATH =
157         "config_servlet_path";
158
159     static private final String JavaDoc INIT_PARAM_DEFAULT_MAPPING_PATTERN =
160         "defaultMappingPattern";
161
162     static private final String JavaDoc INIT_PARAM_DEFAULT_CONTEXT_PATH =
163         "defaultContextPath";
164
165     static private final String JavaDoc INIT_PARAM_DEFAULT_SERVLET_PATH =
166         "defaultServletPath";
167
168     /** ... */
169     static public final String JavaDoc COPYRIGHT = "<font class=\"text\">Copyright 2002-2007 <a HREF=\"http://www.jahia.org\" target=\"newJahia\">Jahia Ltd</a> - All rights reserved.</font>";
170
171     /**
172      * the lock name in the lock registery
173      */

174     public static final String JavaDoc JAHIA_LOCK_NAME = CLASS_NAME + "_lock_name";
175
176     /** Jahia lock session id */
177     public static final String JavaDoc JAHIA_LOCK_SESSION_ID = CLASS_NAME +
178         "_lock_session_id";
179
180     /** Jahia lock session id */
181     public static final String JavaDoc JAHIA_LOCK = CLASS_NAME + "_lock";
182
183     /** Jahia lock user */
184     public static final String JavaDoc JAHIA_LOCK_USER = CLASS_NAME + "_lock_user";
185
186     static private int initTryCount = 0;
187     static private boolean reInit = false;
188     static private boolean tomcatXMLRestart = false;
189     static private boolean mInitError;
190     static private boolean mInitWarning;
191     static private boolean mInitiated = false;
192     static private boolean runInstaller;
193
194     static protected final String JavaDoc JDK_REQUIRED = "1.3";
195
196     private static SettingsBean jSettings;
197     private OperationManager operations;
198     private ServletConfig JavaDoc config;
199     static private ServletConfig JavaDoc staticServletConfig;
200     private ServletContext JavaDoc context;
201     private PathResolver pathResolver;
202
203     static protected Exception JavaDoc initException; // used to catch exception on init, where we don't have request and response...
204
static protected Exception JavaDoc initWarningException;
205
206     static private String JavaDoc jahiaPropertiesFileName;
207     static protected String JavaDoc mLicenseFilename;
208     static private String JavaDoc publicKeyStoreResourceName = "/jahiapublickeystore";
209     static private String JavaDoc publicKeyStorePassword = "jahiapublickeystore";
210
211     static protected String JavaDoc jahiaBasicFileName;
212     static protected String JavaDoc jahiaPropertiesPath;
213     static protected String JavaDoc jahiaTemplatesScriptsPath;
214     static protected String JavaDoc jahiaEtcFilesPath;
215     static protected String JavaDoc jahiaVarFilesPath;
216     static public String JavaDoc jahiaDatabaseScriptsPath;
217     static protected String JavaDoc jahiaBaseFilesPath = "";
218
219     static private String JavaDoc defaultMappingPattern = null;
220     static private String JavaDoc relativeServletURI = null;
221     static private String JavaDoc jahiaServletPath = null;
222     static private String JavaDoc jahiaContextPath = null;
223
224     static private String JavaDoc jahiaInitAdminServletPath = null;
225     static private String JavaDoc jahiaInitConfigServletPath = null;
226
227     static private License coreLicense = null;
228     static private LicensePackage jahiaLicensePackage = null;
229     static private ResourceMessage[] licenseErrorMessages = null;
230
231     static private String JavaDoc supportedJDKVersions = null;
232     static private boolean supportedJDKWarningAlreadyShowed = false;
233
234     static private ThreadLocal JavaDoc paramBeanThreadLocal = new ThreadLocal JavaDoc();
235     static private Pipeline authPipeline;
236
237     static private BeanFactory configBeanFactory = null;
238
239     //-------------------------------------------------------------------------
240
/**
241      * Default init inherited from HttpServlet.
242      *
243      * @param config Servlet configuration (inherited).
244      */

245     public void init (ServletConfig JavaDoc config)
246         throws ServletException JavaDoc {
247         super.init(config);
248         logger.debug("Initializing Jahia...");
249
250         String JavaDoc webinf_path;
251
252         mInitError = false;
253         runInstaller = false;
254         if (initTryCount < 5) {
255             initTryCount++;
256         }
257
258         JahiaConsole.setServlet(this);
259
260         // the first time display the welcome banner...
261
if (initTryCount == 1) {
262             JahiaConsole.startupWithTrust(BUILD_NUMBER);
263         }
264
265         // get servlet basic variables, like confid and context...
266
this.config = config;
267         staticServletConfig = config;
268         this.context = config.getServletContext();
269         this.pathResolver = new WebAppPathResolver(context);
270
271         /* old system, that doesn't work well when setting up Jahia in root
272            context
273         Jahia.jahiaContextPath = "/" + this.context.getServletContextName();
274         Jahia.jahiaServletPath = "/" + config.getServletName();
275         */

276
277         Jahia.jahiaContextPath = this.config.getInitParameter(INIT_PARAM_DEFAULT_CONTEXT_PATH);
278         Jahia.jahiaServletPath = this.config.getInitParameter(INIT_PARAM_DEFAULT_SERVLET_PATH);
279
280         // get some value from the web.xml file...
281
webinf_path = this.config.getInitParameter(INIT_PARAM_WEBINF_PATH);
282         String JavaDoc loggingLevelStr = this.config.getInitParameter(
283             INIT_PARAM_LOGGING_LEVEL);
284         supportedJDKVersions = this.config.getInitParameter(
285             INIT_PARAM_SUPPORTED_JDK_VERSIONS);
286         jahiaInitAdminServletPath = this.config.getInitParameter(
287             INIT_PARAM_ADMIN_SERVLET_PATH);
288         jahiaInitConfigServletPath = this.config.getInitParameter(
289             INIT_PARAM_CONFIG_SERVLET_PATH);
290         defaultMappingPattern = this.config.getInitParameter(INIT_PARAM_DEFAULT_MAPPING_PATTERN);
291
292         if (loggingLevelStr == null) {
293             JahiaConsole.setLoggingLevel(0);
294         } else {
295             int loggingLevel = Integer.parseInt(loggingLevelStr);
296             if ( (loggingLevel >= 0) &&
297                 (loggingLevel <= JahiaConsole.MAX_LOGGING_LEVEL)) {
298                 JahiaConsole.setLoggingLevel(loggingLevel);
299             }
300         }
301
302         /*
303                  // display all system's properties.......
304                  Properties xx = System.getProperties();
305                  Enumeration y = xx.propertyNames();
306                  while(y.hasMoreElements()) {
307             String p = (String) y.nextElement();
308             System.out.println(p+" : "+System.getProperty(p));
309                  }
310          */

311
312         if ( (!supportedJDKWarningAlreadyShowed) &&
313             (supportedJDKVersions != null)) {
314             Version currentJDKVersion = null;
315             try {
316                 currentJDKVersion = new Version(System.getProperty(
317                     "java.version"));
318                 if (!isSupportedJDKVersion(currentJDKVersion,
319                                            supportedJDKVersions)) {
320                     mInitWarning = true;
321                     StringBuffer JavaDoc jemsg = new StringBuffer JavaDoc();
322                     jemsg.append("WARNING<br/>\n");
323                     jemsg.append(
324                         "<b><font size=\"2\">You are using an unsupported JDK version\n");
325                     jemsg.append("or have an invalid " +
326                                  INIT_PARAM_SUPPORTED_JDK_VERSIONS +
327                                  " parameter string in \n");
328                     jemsg.append(
329                         "the deployment descriptor file web.xml.</font></b>\n");
330                     jemsg.append(
331                         "<br/><br/>Here is the range specified in the web.xml file : " +
332                         supportedJDKVersions + ".\n");
333                     jemsg.append(
334                         "<br/>If you want to disable this warning, remove the " +
335                         INIT_PARAM_SUPPORTED_JDK_VERSIONS + "\n");
336                     jemsg.append(
337                         "<br/>initialization parameter in the tomcat/webapps/jahia/WEB-INF/web.xml<br/>\n");
338                     jemsg.append("<br/><br/>Please note that if you deactivate this check or use unsupported versions<br/>\n");
339                     jemsg.append("<br/>You might run into serious problems and we cannot offer support for these.<br/>\n");
340                     jemsg.append("<br/>You may download a supported JDK from <a HREF=\"http://java.sun.com\" target=\"_newSunWindow\">http://java.sun.com</a>.");
341                     jemsg.append("<br/><br/>&nbsp;\n");
342                     initWarningException = new JahiaException(jemsg.toString(),
343                         "JDK version warning",
344                         JahiaException.INITIALIZATION_ERROR,
345                         JahiaException.WARNING_SEVERITY);
346                 }
347             } catch (NumberFormatException JavaDoc nfe) {
348                 logger.debug("Couldn't convert JDK version to internal version testing system, ignoring JDK version test...");
349             }
350             supportedJDKWarningAlreadyShowed = true;
351         }
352
353         if (Jahia.jahiaInitAdminServletPath == null) {
354             logger.debug("Error in web.xml for init parameter " +
355                          INIT_PARAM_ADMIN_SERVLET_PATH +
356                          ". Make sure it's set...Trying to use hardcoded /administration/ dispatching ...");
357             jahiaInitAdminServletPath = "/administration/";
358         }
359
360         if (Jahia.jahiaInitConfigServletPath == null) {
361             logger.debug("Error in web.xml for init parameter " +
362                          INIT_PARAM_CONFIG_SERVLET_PATH +
363                 ". Make sure it's set...Trying to use hardcoded /installation/ dispatching ...");
364             jahiaInitConfigServletPath = "/installation/";
365         }
366
367         jahiaEtcFilesPath = this.context.getRealPath(webinf_path + "/etc");
368         jahiaVarFilesPath = this.context.getRealPath(webinf_path + "/var");
369
370         // set default paths...
371
jahiaPropertiesPath = this.context.getRealPath(webinf_path +
372             "/etc/config/");
373         jahiaPropertiesFileName = jahiaPropertiesPath + File.separator +
374                                   PROPERTIES_FILENAME;
375         jahiaBasicFileName = jahiaPropertiesPath + File.separator +
376                              PROPERTIES_BASIC;
377         mLicenseFilename = jahiaPropertiesPath + File.separator +
378                            LICENSE_FILENAME;
379
380         jahiaBaseFilesPath = this.context.getRealPath(webinf_path + "/var");
381         jahiaTemplatesScriptsPath = jahiaBaseFilesPath + File.separator +
382                                     "templates";
383         jahiaDatabaseScriptsPath = jahiaBaseFilesPath + File.separator + "db";
384
385         // now let's preload some classes that have static initializations
386
// that need to be performed before we go further...
387
String JavaDoc preloadConfigurationFileName = jahiaPropertiesPath +
388                                               File.separator +
389                                               PRELOAD_CLASSES_FILENAME;
390         try {
391             // the constructor does everything, including loading the classes,
392
// so we don't need to do anything besides creating an instance that
393
// we can dispose of immediately after.
394
ClassesPreloadManager preloadManager = new ClassesPreloadManager(
395                 preloadConfigurationFileName);
396             preloadManager = null;
397         } catch (IOException JavaDoc ioe) {
398             logger.debug("IO exception raised while trying to load classes preload XML configuration file [" +
399                          preloadConfigurationFileName + "]", ioe);
400         } catch (SAXException JavaDoc saxe) {
401             logger.debug(
402                 "IO exception while trying to parse classes preload XML configuration file [" +
403                 preloadConfigurationFileName + "]", saxe);
404         } catch (ClassNotFoundException JavaDoc cnfe) {
405             logger.debug("Could not preload class because it couldn't be found",
406                          cnfe);
407         }
408         // none of the above exceptions are fatal, they just don't preload all
409
// the classes, but this might cause problems elsewhere !
410

411         // Check if the license file exists.
412
File JavaDoc licenseFile = new File JavaDoc(mLicenseFilename);
413         if (!licenseFile.exists()) {
414             logger.debug(
415                 "Could not find jahia.license file (was looking for it at " +
416                 licenseFile.toString() + ")");
417             mInitError = true;
418             return;
419         }
420
421         // Check the license file
422
mInitError = (checkLicense() == false);
423         if (mInitError) {
424             initException = new JahiaException("Invalid License",
425                 "Environement Initialization Exception",
426                 JahiaException.INITIALIZATION_ERROR,
427                 JahiaException.KISSYOURASSGOODBYE_SEVERITY);
428             return;
429         }
430
431         // we don't need the license file anymore, it was just to know if
432
// it existed.
433
licenseFile = null;
434
435         // check if there is a jahia.properties file...
436
File JavaDoc jahiaProperties = new File JavaDoc(jahiaPropertiesFileName);
437         boolean jahiaPropertiesExists = jahiaProperties.exists();
438
439         /* init the listener registry */
440         //JahiaListenersRegistry.getInstance().init( this.config );
441

442         // if the jahia properties file exists try to init...
443
if (!jahiaPropertiesExists) {
444             // jahia.properties don't exists, launch JahiaConfigurationWizard...
445
Jahia.runInstaller = true;
446             return;
447         }
448
449         try {
450             // create the jSettings object...
451
Jahia.jSettings = new SettingsBean(pathResolver,
452                 jahiaPropertiesFileName, mLicenseFilename, BUILD_NUMBER);
453             Jahia.jSettings.load();
454         } catch (NullPointerException JavaDoc npe) {
455             // error while reading jahia.properties, launch JahiaConfigurationWizard...
456
Jahia.runInstaller = true;
457             return;
458         } catch (NumberFormatException JavaDoc nfe) {
459             // error while reading jahia.properties, launch JahiaConfigurationWizard...
460
Jahia.runInstaller = true;
461             return;
462         }
463
464         try {
465             this.loadConfigBeanFactory();
466         } catch (JahiaException je) {
467             logger.debug("CRITICAL : Error loading config file!", je);
468             // init error, stop Jahia!
469
mInitError = true;
470             return;
471         }
472          
473         // check server type... and if it's tomcat, check the tomcat-users.xml file...
474
tomcatXMLRestart = TomcatUsersModifier.ensureValidity(
475             jahiaPropertiesFileName);
476
477         // Initialize all the registered services.
478
try {
479             ConnectionDispenser.init(Jahia.jSettings);
480             ConnectionDispenser.getConnection();
481             JahiaMBeanServer.getInstance().init(getSettings());
482             if (initServicesRegistry()) {
483                 try {
484                     EnginesRegistry.getInstance().init();
485                     JahiaFieldDefinitionsRegistry.getInstance().init();
486                     JahiaContainerDefinitionsRegistry.getInstance().
487                         init();
488                     JahiaListenersRegistry.getInstance().init(this.
489                         config);
490                     SharedTemplatePackagesRegistry.getInstance().init(Jahia.
491                         jSettings.getJahiaSharedTemplatesDiskPath(),
492                         Jahia.jSettings.getJahiaJspDiskPath());
493
494                     operations = new OperationManager(); // only called by Jahia servlet...
495
} catch (NullPointerException JavaDoc ex) {
496                     logger.debug(
497                         "CRITICAL : Error while initializing one of the needed services!", ex);
498
499                     // init error, stop Jahia!
500
mInitError = true;
501                     return;
502                 }
503                 // 30.01.2002 NK : Patch for old database with templates without ACL
504
ServicesRegistry.getInstance().
505                     getJahiaPageTemplateService().
506                     patchTemplateWithoutACL();
507
508             }
509
510             // Check the license file
511
mInitError = (checkLicenseLimit() == false);
512             if (mInitError) {
513                 String JavaDoc licenseErrors = processLicenseErrorMessages();
514                 if (licenseErrors == null) {
515                     initException = new JahiaException(
516                         "License Limit Violation",
517                         "Environement Initialization Exception",
518                         JahiaException.INITIALIZATION_ERROR,
519                         JahiaException.KISSYOURASSGOODBYE_SEVERITY);
520                 } else {
521                     initException = new JahiaException(
522                         licenseErrors,
523                         licenseErrors,
524                         JahiaException.INITIALIZATION_ERROR,
525                         JahiaException.KISSYOURASSGOODBYE_SEVERITY);
526                 }
527                 return;
528             }
529             // JahiaMBeanServer.getInstance().init(getSettings());
530

531             // Activate the JMS synchronization if needed
532
CacheFactory factory = CacheFactory.getInstance();
533             if (factory.isJMSEnabled()) {
534                 factory.enableJMSSynchronization();
535             }
536
537             CacheFactory.getHtmlCache().init(jSettings);
538
539             // let's set the URI generation default encoding according to
540
// the Jahia settings.
541
URICodec.setDefaultEncoding(jSettings.getDefaultURIEncoding());
542             URI.setDefaultEncoding(jSettings.getDefaultURIEncoding());
543
544             createAuthorizationPipeline(config);
545
546             ConnectionDispenser.terminateConnection();
547
548         } catch (JahiaException je) {
549             logger.error("Error during initialization of Jahia", je);
550             // init error, stop Jahia!
551
mInitError = true;
552             initException = je;
553             ConnectionDispenser.abortConnection();
554             return;
555         } catch (Exception JavaDoc ex) {
556             logger.error("Error during initialization of Jahia", ex);
557             ConnectionDispenser.abortConnection();
558         }
559
560         mInitiated = true;
561
562     } // end init
563

564     private void createAuthorizationPipeline (ServletConfig JavaDoc config) throws JahiaException {
565         try {
566             String JavaDoc pipelineClassName = jSettings.getAuthPipelineClassName();
567             Class JavaDoc pipelineClass = Class.forName(pipelineClassName);
568             authPipeline = (Pipeline) pipelineClass.newInstance();
569             File JavaDoc authPipelineFile = new File JavaDoc(config.getServletContext().getRealPath(jSettings.getAuthPipelineFileName()));
570             PipelineDescriptor descriptor;
571             XmlReader reader = new XmlReader(PipelineDescriptor.class);
572             descriptor = (PipelineDescriptor) reader.parse(new FileInputStream JavaDoc(authPipelineFile));
573             authPipeline.setDescriptor(descriptor);
574             authPipeline.initialize();
575         } catch (PipelineException e) {
576             Throwable JavaDoc t = e;
577             if (e.getNested() != null) {
578                 t = e.getNested();
579                 logger.error("Error while initializing authorization pipeline", t);
580             }
581             throw new JahiaException(
582                 "Error while initializing authorization pipeline",
583                 t.getMessage(), JahiaException.INITIALIZATION_ERROR,
584                 JahiaException.KISSYOURASSGOODBYE_SEVERITY, t);
585         } catch (Exception JavaDoc e) {
586             throw new JahiaException(
587                 "Error while initializing authorization pipeline",
588                 e.getMessage(), JahiaException.INITIALIZATION_ERROR,
589                 JahiaException.KISSYOURASSGOODBYE_SEVERITY, e);
590         }
591     }
592
593     public void destroy() {
594         ServicesRegistry.getInstance().shutdown();
595         org.jahia.services.database.ConnectionDispenser.terminateConnection();
596         try {
597             org.jahia.services.database.ConnectionDispenser.shutdown();
598         } catch (java.sql.SQLException JavaDoc sqle) {
599             logger.error("Error while trying to close database connection pool", sqle);
600         }
601         super.destroy();
602     }
603
604     /*
605      * Default service inherited from HttpServlet.
606      * @author Alexandre Kraft
607      * @author Fulco Houkes
608      *
609      * @param request Servlet request (inherited).
610      * @param response Servlet response (inherited).
611      */

612     public void service (HttpServletRequest JavaDoc request,
613                          HttpServletResponse JavaDoc response)
614         throws IOException JavaDoc,
615         ServletException JavaDoc {
616
617       if (logger.isDebugEnabled())
618       {
619         logger.debug("--------------------------------------------- NEW " +
620                      request.getMethod().toUpperCase() + " REQUEST ---");
621         logger.debug("New request, URL=[" + request.getRequestURI() +
622                      "], query=[" + request.getQueryString() +
623                      "] serverName=[" + request.getServerName() + "]");
624       }
625       
626         // start the chrono...
627
long startTime = JahiaChrono.getInstance().start();
628
629
630         /** @todo Can we put this someplace else, and furthermore can be only
631          * do this if we have a session variable set or something ?
632          */

633         // The following part is the most important part of the servlet, which makes sure
634
// we read all the encodings in UTF-8. This is documented in the Servlet API 2.3
635
// specification, under the SRV 4.9 section, page 37
636
// logger.debug("Character encoding passed: " + request.getCharacterEncoding() );
637
if (jSettings != null) {
638             if (jSettings.isUtf8Encoding()) {
639                 // bad browser, doesn't send character encoding :(
640
// we can force the encoding ONLY if we do this call before any
641
// getParameter() call is done !
642
request.setCharacterEncoding("UTF-8");
643             }
644         }
645
646         /**
647          * The following is done because the Jahia servlet has multiple mappings.
648          * We want to make sure that we store only the correct mapping because
649          * we will use this for URL generation and detection.
650          */

651         if (ServletURL.matchesServletPattern(defaultMappingPattern, request.getServletPath())) {
652             jahiaServletPath = request.getServletPath();
653         } else {
654             logger.debug("Default mapping not detected in request servlet path, ignoring...");
655         }
656
657         logger.debug("Character encoding set as: "
658                      + request.getCharacterEncoding());
659
660         copySessionCookieToRootContext(request, response);
661
662         HttpSession JavaDoc session = request.getSession(false);
663         if (session == null) {
664             // Session could be false because of new user, or missing JSESSIONID
665
// id for a non-cookie browser, or a false cookie maybe ?
666
logger.debug("Session is null");
667             session = request.getSession(true);
668             logger.debug("New session id=[" + session.getId() + "]");
669         }
670
671         if (Jahia.isInitiated() && !checkLockAccess(session)) {
672             logger.debug("Jahia is locked by the super admin !\n");
673             config.getServletContext().getRequestDispatcher(
674                     "/jsp/jahia/errors/locked.jsp").forward(request, response);
675             return;
676         }
677
678         // WEB APP ISSUE
679
// This session attribute is used to track that targeted application
680
// has been already processed or not.
681
String JavaDoc appid = request.getParameter("appid");
682         if ( appid != null ){
683             if ( "true".equals(request.getParameter("resetAppSession")) ){
684                 session.removeAttribute("org.jahia.services.applications.wasProcessed." + appid);
685             }
686         }
687
688         try {
689
690             if (jahiaContextPath == null) {
691                 jahiaContextPath = request.getContextPath();
692             }
693
694             if (Jahia.relativeServletURI == null) {
695                 String JavaDoc pathInfo = request.getPathInfo();
696
697                 if (pathInfo == null) {
698                     Jahia.relativeServletURI = request.getRequestURI();
699                 } else {
700                     Jahia.relativeServletURI = request.getRequestURI().substring(
701                             0, request.getRequestURI().indexOf(pathInfo));
702             }
703
704             }
705
706             // check witch action to do...
707
if (mInitWarning) { // init error, stop Jahia...
708
if (initWarningException != null) {
709                     JahiaErrorDisplay.DisplayException(request, response,
710                             getServletContext(), jSettings, initWarningException);
711                 }
712                 // we only display warnings once.
713
initWarningException = null;
714                 mInitWarning = false;
715                 return;
716
717             } else if (mInitError) { // init error, stop Jahia...
718
logger.debug("INIT ERROR. Jahia is not started.");
719                 if (initException != null) {
720                     JahiaErrorDisplay.DisplayException(request, response,
721                             getServletContext(), jSettings, initException);
722                 }
723
724                 return;
725
726             } else if (Jahia.runInstaller) { // run the installer...
727
logger.debug("Redirecting to Configuration Wizard...");
728                 Jahia.runInstaller = false;
729                 Jahia.reInit = true;
730                 jahiaLaunch(request, response, Jahia.jahiaInitConfigServletPath);
731
732                 return;
733
734             } else if (request.getAttribute(JAHIA_LAUNCH) != null) { // redirect on an another servlet...
735

736                 if (request.getAttribute(JAHIA_LAUNCH).equals("installation")) {
737                     logger.debug("Redirecting to Configuration Wizard...");
738                     jahiaLaunch(request, response,
739                                 Jahia.jahiaInitConfigServletPath);
740                     return;
741                     } else if (request.getAttribute(JAHIA_LAUNCH).equals(
742                             "administration")) {
743                         logger.debug("Redirecting to Administration...");
744                         jahiaLaunch(request, response,
745                                     Jahia.jahiaInitAdminServletPath);
746                         return;
747                     }
748
749             } else if (reInit) { // re-init Jahia...
750
logger.debug("Reinitializing Jahia...");
751                 Jahia.reInit = false;
752                 init(config);
753             }
754
755             // please restart tomcat... config has been modified...
756
if (tomcatXMLRestart) {
757                 session = request.getSession();
758                 if (session != null) {
759                     session.setAttribute(JahiaAdministration.CLASS_NAME +
760                             "jahiaDisplayMessage",
761                             "<b>Web applications are being deployed...<br/>" +
762                             "Please wait a few moments until it is done<br/>" +
763                             "and then shutdown and restart Jahia</b>");
764                 }
765             }
766
767             // all is okay, let's continue...
768
boolean exitAdminMode = false;
769             Integer JavaDoc I = (Integer JavaDoc) session.getAttribute(ParamBean.
770                     SESSION_JAHIA_RUNNING_MODE);
771
772             // get the main http method...
773
String JavaDoc requestMethod = request.getMethod();
774             int intRequestMethod = 0;
775
776             if (requestMethod.equals(GET_REQUEST)) {
777                 intRequestMethod = ParamBean.GET_METHOD;
778             } else if (requestMethod.equals(POST_REQUEST)) {
779                 intRequestMethod = ParamBean.POST_METHOD;
780             }
781
782             // create the parambean (jParams)...
783
ParamBean jParams = null;
784             try {
785
786                 if (request.getAttribute(JahiaConfigurationWizard.
787                         CLASS_NAME +
788                         ".finishedInstallation") != null) {
789                     // now we must login the root user.
790
String JavaDoc rootName = (String JavaDoc) request.getAttribute(
791                             JahiaConfigurationWizard.CLASS_NAME +
792                             ".rootName");
793                     String JavaDoc rootPass = (String JavaDoc) request.getAttribute(
794                             JahiaConfigurationWizard.CLASS_NAME +
795                             ".rootPass");
796                     JahiaUser rootUser = ServicesRegistry.getInstance().
797                             getJahiaUserManagerService().
798                             lookupUser(0, rootName);
799                     if (rootUser != null) {
800                         if (rootUser.verifyPassword(rootPass)) {
801                             session.setAttribute(ParamBean.SESSION_USER,
802                                     rootUser);
803                         } else {
804                             logger.error(
805                                     "Invalid password for root user, using guest user !");
806                         }
807                     } else {
808                         logger.error("Root user " + rootName +
809                                 " not found in database, installation error ?");
810                     }
811                 }
812                 /*
813                 String runningMode = request.getParameter("runningMode");
814                 if ( "administration".equals(runningMode) ){
815                     session.setAttribute(ParamBean.
816                             SESSION_JAHIA_RUNNING_MODE,
817                             new Integer(Jahia.ADMIN_MODE));
818                     JahiaAdministration.initAdminJahiaData(request,response,session);
819                     JahiaData jData = (JahiaData)request.getAttribute("org.jahia.data.JahiaData");
820                     jParams = jData.getParamBean();
821                     request.setAttribute("org.jahia.params.ParamBean",jParams);
822
823                     process(request, response);
824                     org.jahia.services.database.ConnectionDispenser.
825                             terminateConnection();
826                     return;
827                 } else {
828                     jParams = new ParamBean(request, response, context,
829                             jSettings, startTime,
830                             intRequestMethod);
831                 }*/

832                 jParams = new ParamBean(request, response, context,
833                         jSettings, startTime,
834                         intRequestMethod);
835
836                 if (jParams != null) {
837
838                     paramBeanThreadLocal.set(jParams);
839
840                     exitAdminMode = ( (I != null) &&
841                             (I.intValue() == ADMIN_MODE) &&
842                             jParams.getEngine().equals(ParamBean.
843                             CORE_ENGINE_NAME));
844
845                     // tell we are in Jahia Core mode
846
if (exitAdminMode) {
847                         session.setAttribute(ParamBean.
848                                 SESSION_JAHIA_RUNNING_MODE,
849                                 new Integer JavaDoc(Jahia.CORE_MODE));
850                         logger.debug("Switch to Jahia.CORE_MODE");
851                     }
852
853                     // NK : flush the page in cache if we were previously in ADMIN MODE
854
if (exitAdminMode && jParams.getUser() != null) {
855                         try {
856                             CacheFactory.getHtmlCache().invalidatePageEntries(Integer.toString(jParams.getPageID()));
857                         } catch (Throwable JavaDoc t) {
858                             logger.error("Error while flushing cache for page " + jParams.getPageID(), t);
859                         }
860                     }
861
862                     request.setAttribute("org.jahia.params.ParamBean",
863                             jParams);
864                     process(request, response);
865                     //operations.handleOperations (this,jParams, jSettings);
866
org.jahia.services.database.ConnectionDispenser.
867                             terminateConnection();
868                     CacheFactory.getInstance().syncCachesNow();
869                 }
870                 // display time
871
if (jParams.getUser() != null && logger.isInfoEnabled()) {
872                   logger.info(new StringBuffer JavaDoc(96)
873                     .append("Processed [").append(jParams.getRequest().getRequestURI())
874                     .append("] user=[").append(jParams.getUser().getUsername() )
875                     .append("] ip=[" ).append(jParams.getRequest().getRemoteAddr() )
876                     .append("] in [" ).append(JahiaChrono.getInstance().read(jParams.getStartTime()) )
877                     .append("ms]").toString());
878                 }
879                 jParams = null;
880
881             } catch (JahiaPageNotFoundException ex) {
882                 // PAGE NOT FOUND EXCEPTION
883
//logger.error(ex.getJahiaErrorMsg(), ex);
884
JahiaErrorDisplay.DisplayException(request, response,
885                         getServletContext(), jSettings, false, false, ex);
886                 org.jahia.services.database.ConnectionDispenser.
887                         abortConnection();
888             } catch (JahiaSecurityException ex) {
889                 // SECURITY EXCEPTION
890
logger.error("A Security error occured -> request ignored.",
891                              ex);
892                 JahiaErrorDisplay.DisplayException(request, response,
893                         getServletContext(), jSettings, ex);
894                 org.jahia.services.database.ConnectionDispenser.
895                         abortConnection();
896             } catch (JahiaSessionExpirationException ex) {
897                 // SESSION EXPIRATION
898
logger.error(
899                         "Null session -> session expiration -> request ignored.",
900                         ex);
901                 JahiaErrorDisplay.DisplayException(request, response,
902                         getServletContext(), jSettings, ex);
903                 org.jahia.services.database.ConnectionDispenser.
904                         abortConnection();
905             } catch (JahiaOperationNotAllowedException ex) {
906                 // OPERATION NOT ALLOWED
907
logger.error(ex.getJahiaErrorMsg(), ex);
908                 JahiaErrorDisplay.DisplayException(request, response,
909                         getServletContext(), jSettings, ex);
910                 org.jahia.services.database.ConnectionDispenser.
911                         abortConnection();
912             } catch (ServiceNotFoundException ex) {
913                 // SERVICE EXCEPTIONS
914
logger.error(ex.getJahiaErrorMsg(), ex);
915                 JahiaErrorDisplay.DisplayException(request, response,
916                         getServletContext(), jSettings, ex);
917                 org.jahia.services.database.ConnectionDispenser.
918                         abortConnection();
919             } catch (JahiaSiteNotFoundException snfex) {
920                 // VIRTUAL SITE NOT FOUND
921
//logger.error(snfex.getJahiaErrorMsg(), snfex);
922
JahiaErrorDisplay.DisplayException(request, response,
923                         getServletContext(), jSettings, false, false, snfex);
924                 org.jahia.services.database.ConnectionDispenser.
925                         abortConnection();
926             } catch (JahiaSiteAndPageIDMismatchException ex) {
927               // site key, resolved from request parameters (pageId,
928
// site key etc.) does not match the key, resolved by the host
929
// name
930
JahiaErrorDisplay.DisplayException(request, response,
931                       getServletContext(), jSettings, false, false, ex);
932               org.jahia.services.database.ConnectionDispenser.
933                       abortConnection();
934             } catch (JahiaForbiddenAccessException je) {
935                 JahiaErrorDisplay.DisplayException(request, response,
936                         getServletContext(), jSettings, false, false, je);
937                 org.jahia.services.database.ConnectionDispenser.
938                         abortConnection();
939             } catch (JahiaException je) {
940                 // ALL OTHER JAHIA EXCEPTIONS
941
logger.error("Error in " + requestMethod +
942                              " method -> BAILING OUT", je);
943                 // should redirect to an error page here
944
JahiaErrorDisplay.DisplayException(request, response,
945                         getServletContext(), jSettings, je);
946                 org.jahia.services.database.ConnectionDispenser.
947                         abortConnection();
948             }
949
950         } catch (Throwable JavaDoc t) {
951             logger.error("Throwable Exception caught in Jahia servlet : " + t,
952                          t);
953             JahiaErrorDisplay.DisplayException(request, response,
954                 getServletContext(), jSettings, t);
955             org.jahia.services.database.ConnectionDispenser.abortConnection();
956         } finally {
957             paramBeanThreadLocal.set(null);
958         }
959     } // end service
960

961     /**
962      * Helper method to copy JSESSION cookies from a non null context to a root
963      * context. Warning this MIGHT disrupt normal functioning of the servlet
964      * container.
965      * @param request the request object containing the cookies to read
966      * @param response the response object in which to copy the session cookie
967      * to the root context.
968      */

969     public static void copySessionCookieToRootContext (HttpServletRequest JavaDoc
970         request,
971         HttpServletResponse JavaDoc response) {
972
973         Cookie JavaDoc[] cookies = request.getCookies();
974         if (cookies != null) {
975             for (int i = 0; i < cookies.length; i++) {
976                 Cookie JavaDoc curCookie = cookies[i];
977                 if ("JSESSIONID".equals(curCookie.getName())) {
978                     String JavaDoc curPath = curCookie.getPath();
979                     if ( (curPath != null) && (! ("".equals(curPath)))) {
980                         // we found a session cookie that has a non null path,
981
// let's copy it to a null path.
982
logger.debug(
983                             "Copying non-root context cookie to root context");
984                         Cookie JavaDoc rootCookie = (Cookie JavaDoc) curCookie.clone();
985                         rootCookie.setPath("");
986                         response.addCookie(rootCookie);
987                     }
988                 }
989                 if (logger.isDebugEnabled())
990                   logger.debug("Cookie domain=[" + curCookie.getDomain() +
991                                "] path=[" + curCookie.getPath() +
992                                "] name=[" + curCookie.getName() +
993                                "] value=[" + curCookie.getValue() + "]");
994             }
995         } else {
996             logger.debug("No cookies found.");
997         }
998     }
999
1000    /* static accessors...
1001     */

1002    public static String JavaDoc getRelativeServletURI () {
1003        return relativeServletURI;
1004    }
1005
1006    public static String JavaDoc getJahiaPropertiesFileName () {
1007        return jahiaPropertiesFileName;
1008    }
1009
1010    public static String JavaDoc getServletPath () {
1011        return jahiaServletPath;
1012    }
1013
1014    public static String JavaDoc getContextPath () {
1015        return jahiaContextPath;
1016    }
1017
1018    public static String JavaDoc getInitAdminServletPath () {
1019        return jahiaInitAdminServletPath;
1020    }
1021
1022    public static String JavaDoc getInitConfigServletPath () {
1023        return jahiaInitConfigServletPath;
1024    }
1025
1026    public static ParamBean getThreadParamBean () {
1027        return (ParamBean) paramBeanThreadLocal.get();
1028    }
1029
1030    public static void setThreadParamBean(ParamBean paramBean) {
1031        paramBeanThreadLocal.set(paramBean);
1032    }
1033
1034    //-------------------------------------------------------------------------
1035
/**
1036     * Call the initialization of the services registry.
1037     *
1038     * @return Return <code>true</code> on success or <code>false</code> on any failure.
1039     */

1040    protected boolean initServicesRegistry ()
1041        throws JahiaException {
1042
1043        logger.debug("Start the Services Registry ...");
1044
1045        try {
1046            ServicesRegistry registry = ServicesRegistry.getInstance();
1047            if (registry != null) {
1048                registry.init(Jahia.jSettings);
1049                logger.debug("Services Registry is running...");
1050                return true;
1051            }
1052
1053            logger.debug(
1054                " -> ERROR : Could not get the Services Registry instance.");
1055            return false;
1056        } catch (JahiaException je) {
1057            throw new JahiaException(je.getJahiaErrorMsg(),
1058                "Service Registry Initialization Exception",
1059                JahiaException.INITIALIZATION_ERROR,
1060                JahiaException.KISSYOURASSGOODBYE_SEVERITY,
1061                je);
1062        }
1063    } // end initServicesRegistry
1064

1065    //-------------------------------------------------------------------------
1066
/**
1067         * Forward the flow to an another servlet. The name of the destination servlet
1068     * is defined on the <code>destination</code> parameter.
1069     *
1070     * @param request Servlet request.
1071     * @param response Servlet response.
1072     * @param destination Destination for requestDispatcher.forward().
1073     */

1074    private void jahiaLaunch (HttpServletRequest JavaDoc request,
1075                              HttpServletResponse JavaDoc response,
1076                              String JavaDoc destination)
1077        throws IOException JavaDoc,
1078        ServletException JavaDoc {
1079        try {
1080            getServletContext().getRequestDispatcher(destination).forward(
1081                request, response);
1082
1083        } catch (IOException JavaDoc ie) {
1084            logger.error("IOException on method jahiaLaunch.", ie);
1085        } catch (ServletException JavaDoc se) {
1086            logger.error("ServletException on method jahiaLaunch.",
1087                         JahiaErrorDisplay.getNestedException(se));
1088        }
1089    } // end jahiaLaunch
1090

1091    //-------------------------------------------------------------------------
1092
private final boolean checkLicense () {
1093
1094        if (coreLicense == null) {
1095
1096            try {
1097                LicenseManager licenseManager = LicenseManager.getInstance();
1098                licenseManager.load(mLicenseFilename);
1099                jahiaLicensePackage = licenseManager.getLicensePackage(LicenseConstants.JAHIA_PRODUCT_NAME);
1100                coreLicense = jahiaLicensePackage.getLicense(LicenseConstants.CORE_COMPONENT);
1101                InputStream JavaDoc keystoreIn =
1102                    Jahia.class.getResourceAsStream(
1103                        publicKeyStoreResourceName);
1104                if (keystoreIn != null) {
1105                    String JavaDoc keystorePassword = publicKeyStorePassword;
1106                    boolean signaturesOk =
1107                        licenseManager.verifyAllSignatures(keystoreIn,
1108                        keystorePassword);
1109                    if (signaturesOk) {
1110                        logger.debug("Signatures are valid");
1111                    } else {
1112                        logger.error("Invalid license signatures !");
1113                        coreLicense = null;
1114                    }
1115                } else {
1116                    logger.error("Error while loading public key store file [" + publicKeyStoreResourceName + "] from classpath");
1117                    coreLicense = null;
1118                }
1119
1120            } catch (IOException JavaDoc ioe) {
1121                coreLicense = null;
1122                logger.error("Error during license check ", ioe);
1123                return false;
1124            } catch (SAXException JavaDoc saxe) {
1125                coreLicense = null;
1126                logger.error("Error during license check ", saxe);
1127                return false;
1128            }
1129        }
1130
1131        return true;
1132    }
1133
1134    //-------------------------------------------------------------------------
1135
private final boolean checkLicenseLimit () {
1136
1137        if (coreLicense == null) {
1138
1139            if (checkLicense() == false) {
1140                return false;
1141            }
1142        }
1143
1144        if (coreLicense != null) {
1145            // could still be null if load failed.
1146
boolean result = coreLicense.checkLimits();
1147            if (!result) {
1148                licenseErrorMessages = coreLicense.getErrorMessages();
1149            }
1150            return result;
1151        } else {
1152            return false;
1153        }
1154
1155    }
1156
1157    private String JavaDoc processLicenseErrorMessages() {
1158        StringBuffer JavaDoc result = new StringBuffer JavaDoc();
1159        if (licenseErrorMessages == null) {
1160            return null;
1161        }
1162        for (int i=0; i < licenseErrorMessages.length; i++) {
1163            String JavaDoc resource = JahiaResourceBundle.getMessageResource(licenseErrorMessages[i].getResourceKey(), LanguageCodeConverters.languageCodeToLocale(getSettings().getDefaultLanguageCode()));
1164            if (resource != null) {
1165                String JavaDoc formatted = resource;
1166                if (licenseErrorMessages[i].getParameters() != null) {
1167                    formatted = MessageFormat.format(resource,
1168                        licenseErrorMessages[i].getParameters());
1169                }
1170                result.append(formatted);
1171                if (i < (licenseErrorMessages.length - 1)) {
1172                    result.append(",");
1173                }
1174            } else {
1175            logger.error("Could not find resource " + licenseErrorMessages[i].getResourceKey() + " in system resource bundle");
1176            }
1177        }
1178        return result.toString();
1179    }
1180
1181    //-------------------------------------------------------------------------
1182
/**
1183     * Return the private settings
1184     *
1185     * @return JahiaPrivateSettings
1186     */

1187    public static SettingsBean getSettings () {
1188        return jSettings;
1189    }
1190
1191    public static synchronized BeanFactory getConfigBeanFactory(){
1192        return configBeanFactory;
1193    }
1194
1195    //-------------------------------------------------------------------------
1196
/**
1197     * Return the License Key
1198     *
1199     */

1200    public static final License getCoreLicense () {
1201        if (coreLicense == null) {
1202            return null;
1203        }
1204        return coreLicense;
1205    }
1206
1207    public static final boolean checkCoreLimit(String JavaDoc limitName) {
1208        if (coreLicense == null) {
1209            return false;
1210        }
1211        Limit limit = coreLicense.getLimit(limitName);
1212        if (limit == null) {
1213            return true;
1214        }
1215        return limit.check();
1216    }
1217
1218    public static final boolean checkSiteLimit() {
1219        return checkCoreLimit(LicenseConstants.SITE_LIMIT_NAME);
1220    }
1221
1222    public static final boolean checkUserLimit() {
1223        return checkCoreLimit(LicenseConstants.USER_LIMIT_NAME);
1224    }
1225
1226    public static final boolean checkTemplateLimit() {
1227        return checkCoreLimit(LicenseConstants.TEMPLATE_LIMIT_NAME);
1228    }
1229
1230    public static final boolean checkPageLimit() {
1231        return checkCoreLimit(LicenseConstants.PAGE_LIMIT_NAME);
1232    }
1233
1234    public static int getCoreIntLimit(String JavaDoc limitName) {
1235        if (coreLicense == null) {
1236            return 0;
1237        }
1238        Limit limit = coreLicense.getLimit(limitName);
1239        if (limit == null) {
1240            return -1;
1241        }
1242        String JavaDoc valueStr = limit.getValueStr();
1243        return Integer.parseInt(valueStr);
1244    }
1245
1246    public static int getUserLimit() {
1247        return getCoreIntLimit(LicenseConstants.USER_LIMIT_NAME);
1248    }
1249
1250    public static int getSiteLimit() {
1251        return getCoreIntLimit(LicenseConstants.SITE_LIMIT_NAME);
1252    }
1253
1254    public static int getPageLimit() {
1255        return getCoreIntLimit(LicenseConstants.PAGE_LIMIT_NAME);
1256    }
1257
1258    public static int getTemplateLimit() {
1259        return getCoreIntLimit(LicenseConstants.TEMPLATE_LIMIT_NAME);
1260    }
1261
1262    //-------------------------------------------------------------------------
1263
/**
1264     * Return true if this class has been fully initiated
1265     *
1266     * @return boolean true if this class has been fully initaited
1267     */

1268    public static final boolean isInitiated () {
1269        return mInitiated;
1270    }
1271
1272    //-------------------------------------------------------------------------
1273
/**
1274     * Get the Jahia Lock.
1275     * Use this to force Jahia to ignore all requests except for those of the current session.
1276     *
1277     *
1278     * @param user the user must be a root admin
1279     * @param session the session
1280     * @return byte[] lock, the lock or null if the lock is not available.
1281     */

1282    public static final synchronized byte[] getLock (JahiaUser user,
1283        HttpSession JavaDoc session)
1284        throws JahiaException {
1285
1286        if (!isInitiated()) {
1287            return null;
1288        }
1289
1290        byte[] lock = null;
1291
1292        Hashtable JavaDoc lockParams = JahiaLocksRegistry.getInstance().getLock(
1293            JAHIA_LOCK_NAME);
1294
1295        if (!user.isAdminMember(0)) { // a super admin user
1296
throw new JahiaException(CLASS_NAME + ".getLock",
1297                                     "No rigth to get the lock on Jahia",
1298                                     JahiaException.LOCK_ERROR,
1299                                     JahiaException.ERROR_SEVERITY);
1300        }
1301
1302        if (lockParams == null) {
1303
1304            lock = MakeLock(user, session);
1305
1306        } else {
1307
1308            if (JahiaLocksRegistry.getInstance().isLockValid(JAHIA_LOCK_NAME)) {
1309
1310                // Check if the session is the one that locked Jahia.
1311
String JavaDoc sessionID = (String JavaDoc) lockParams.get(
1312                    JAHIA_LOCK_SESSION_ID);
1313                if (sessionID.equals(session.getId())) {
1314
1315                    // reset the timeout time
1316
JahiaLocksRegistry.getInstance().resetLockTimeout(
1317                        JAHIA_LOCK_NAME);
1318                    lock = (byte[]) lockParams.get(JAHIA_LOCK);
1319
1320                }
1321
1322            } else {
1323                // the lock has been timed out and is available.
1324
lock = MakeLock(user, session);
1325            }
1326        }
1327
1328        session.setAttribute(JAHIA_LOCK_NAME, lock);
1329
1330        return lock;
1331
1332    }
1333
1334    //-------------------------------------------------------------------------
1335
private static byte[] MakeLock (JahiaUser user, HttpSession JavaDoc session)
1336        throws
1337        JahiaSessionExpirationException {
1338        Hashtable JavaDoc lockParams = new Hashtable JavaDoc();
1339        byte[] lock = new byte[1];
1340        lockParams.put(JAHIA_LOCK_USER, user);
1341        lockParams.put(JAHIA_LOCK_SESSION_ID, session.getId());
1342        lockParams.put(JAHIA_LOCK, lock);
1343
1344        // create the lock in the registry.
1345
int timeout = session.getMaxInactiveInterval();
1346        JahiaLocksRegistry.getInstance().setLock(JAHIA_LOCK_NAME, lockParams,
1347                                                 timeout);
1348        return lock;
1349
1350    }
1351
1352    //-------------------------------------------------------------------------
1353
/**
1354         * To free the lock, you must give back the lock object stored in your session.
1355     * The JAHIA_LOCK attribute in session is set to null
1356     *
1357     * @param lock the original lock
1358     */

1359    public static final synchronized boolean releaseLock (byte[] lock) {
1360
1361        if (!isInitiated()) {
1362            return false;
1363        }
1364
1365        if (lock == null) {
1366            return false;
1367        }
1368
1369        Hashtable JavaDoc lockParams = JahiaLocksRegistry.getInstance().getLock(
1370            JAHIA_LOCK_NAME);
1371
1372        byte[] storedLock = (byte[]) lockParams.get(JAHIA_LOCK);
1373
1374        if (lock == storedLock) {
1375
1376            JahiaLocksRegistry.getInstance().removeLock(JAHIA_LOCK_NAME);
1377
1378            return true;
1379        }
1380
1381        return false;
1382
1383    }
1384
1385    //-------------------------------------------------------------------------
1386
/**
1387     * Check if Jahia is authorized to process request from current session
1388     *
1389     * @return boolean false if no access allowed
1390     */

1391    public static final synchronized boolean checkLockAccess (HttpSession JavaDoc
1392        session) {
1393
1394        if (!isInitiated()) {
1395            //logger.debug("Jahia is not initialized");
1396
return false;
1397        }
1398
1399        //logger.debug("Jahia is initialized");
1400

1401        Hashtable JavaDoc lockParams = JahiaLocksRegistry.getInstance().getLock(
1402            JAHIA_LOCK_NAME);
1403
1404        if (lockParams == null) {
1405
1406            //logger.debug("lock params in session is null");
1407
return true; // Jahia is not locked
1408

1409        } else {
1410
1411            if (JahiaLocksRegistry.getInstance().isLockValid(JAHIA_LOCK_NAME)) {
1412
1413                //logger.debug(JAHIA_LOCK_NAME + " lock is valid");
1414

1415                // Check if the session is the one that locked Jahia.
1416
String JavaDoc sessionID = (String JavaDoc) lockParams.get(
1417                    JAHIA_LOCK_SESSION_ID);
1418                if (sessionID.equals(session.getId())) {
1419                    // reset the timeout time
1420
JahiaLocksRegistry.getInstance().resetLockTimeout(
1421                        JAHIA_LOCK_NAME);
1422                    return true;
1423                }
1424
1425            } else {
1426
1427                //logger.debug(JAHIA_LOCK_NAME + " lock no more valid");
1428

1429                return true; // no more lock
1430
}
1431        }
1432
1433        return false;
1434    }
1435
1436    /**
1437     * Check if the current JDK we are running Jahia on is supported. The
1438     * supported JDK string is a specially encoded String that checks only
1439     * the versions.
1440     *
1441     * The accepted format is the following :
1442     * version <= x <= version
1443     * or
1444     * version < x < version
1445     * The "x" character is mandatory !
1446     *
1447     * @param currentJDKVersion the current JDK version we are using, this is
1448     * a valid version object.
1449     * @param supportedJDKString
1450     * @return
1451     */

1452    private boolean isSupportedJDKVersion (Version currentJDKVersion,
1453                                           String JavaDoc supportedJDKString) {
1454        if (supportedJDKString == null) {
1455            // we deactivate the check if we specify no supported JDKs
1456
return true;
1457        }
1458
1459        String JavaDoc workString = supportedJDKString.toLowerCase();
1460        int xPos = workString.indexOf("x");
1461
1462        if (xPos == -1) {
1463            logger.debug("Invalid supported_jdk_versions initialization " +
1464                         " parameter in web.xml, it MUST be in the " +
1465                         " following format : 1.2 < x <= 1.3 (the 'x' " +
1466                         "character is mandatory and was missing in " +
1467                         "this case : [" + supportedJDKString + "] )");
1468            return false;
1469        }
1470        String JavaDoc leftArg = workString.substring(0, xPos).trim();
1471        String JavaDoc rightArg = workString.substring(xPos + 1).trim();
1472
1473        if (leftArg.endsWith("<=")) {
1474            String JavaDoc leftVersionStr = leftArg.substring(0, leftArg.length() - 2).
1475                                    trim();
1476            Version lowerVersion = null;
1477            try {
1478                lowerVersion = new Version(leftVersionStr);
1479            } catch (NumberFormatException JavaDoc nfe) {
1480                logger.error("Error in lower version number conversion", nfe);
1481                return false;
1482            }
1483            if (lowerVersion.compareTo(currentJDKVersion) > 0) {
1484                return false;
1485            }
1486        } else if (leftArg.endsWith("<")) {
1487            String JavaDoc leftVersionStr = leftArg.substring(0, leftArg.length() - 1).
1488                                    trim();
1489            Version lowerVersion = null;
1490            try {
1491                lowerVersion = new Version(leftVersionStr);
1492            } catch (NumberFormatException JavaDoc nfe) {
1493                logger.error("Error in lower number conversion", nfe);
1494                return false;
1495            }
1496            if (lowerVersion.compareTo(currentJDKVersion) >= 0) {
1497                return false;
1498            }
1499        } else {
1500            logger.error("Invalid supported_jdk_versions initialization " +
1501                         " parameter in web.xml, it MUST be in the " +
1502                " following format : 1.2 < x <= 1.3. Current string : [" +
1503                supportedJDKString + "] )");
1504            return false;
1505        }
1506
1507        if (rightArg.startsWith("<=")) {
1508            String JavaDoc rightVersionStr = rightArg.substring(2).trim();
1509            Version upperVersion = null;
1510            try {
1511                upperVersion = new Version(rightVersionStr);
1512            } catch (NumberFormatException JavaDoc nfe) {
1513                logger.error("Error in upper number conversion", nfe);
1514                return false;
1515            }
1516            if (upperVersion.compareTo(currentJDKVersion) < 0) {
1517                return false;
1518            }
1519        } else if (rightArg.startsWith("<")) {
1520            String JavaDoc rightVersionStr = rightArg.substring(1).trim();
1521            Version upperVersion = null;
1522            try {
1523                upperVersion = new Version(rightVersionStr);
1524            } catch (NumberFormatException JavaDoc nfe) {
1525                logger.error("Error in upper number conversion", nfe);
1526                return false;
1527            }
1528            if (upperVersion.compareTo(currentJDKVersion) <= 0) {
1529                return false;
1530            }
1531        } else {
1532            logger.error("Invalid supported_jdk_versions initialization " +
1533                         " parameter in web.xml, it MUST be in the " +
1534                " following format : 1.2 < x <= 1.3. Current string : [" +
1535                supportedJDKString + "] )");
1536            return false;
1537        }
1538
1539        return true;
1540    }
1541
1542    /**
1543     *
1544     * @param request
1545     * @param response
1546     * @throws java.io.IOException
1547     * @throws javax.servlet.ServletException
1548     */

1549    public void process (javax.servlet.http.HttpServletRequest JavaDoc request,
1550                         javax.servlet.http.HttpServletResponse JavaDoc response)
1551        throws
1552        java.io.IOException JavaDoc, javax.servlet.ServletException JavaDoc {
1553
1554        try {
1555            ParamBean jParams =
1556                (ParamBean) request.getAttribute("org.jahia.params.ParamBean");
1557            // Create a JahiaData without loaded containers and fields
1558
JahiaData jData = new JahiaData(jParams, false);
1559            jParams.getRequest().setAttribute("org.jahia.data.JahiaData", jData);
1560            super.process(jParams.getRequest(), jParams.getResponse());
1561        } catch (JahiaException je) {
1562            logger.debug(je.getMessage(), je);
1563        }
1564
1565    }
1566
1567    //--------------------------------------------------------------------------
1568
// Struts purpose
1569
//--------------------------------------------------------------------------
1570
public String JavaDoc getInitParameter(String JavaDoc string) {
1571        return super.getInitParameter(string);
1572    }
1573
1574    public Enumeration JavaDoc getInitParameterNames() {
1575        return super.getInitParameterNames();
1576    }
1577    public ServletConfig JavaDoc getServletConfig() {
1578        logger.debug("ContentPath="+getContextPath());
1579        return super.getServletConfig();
1580    }
1581    public ServletContext JavaDoc getServletContext() {
1582        return super.getServletContext();
1583    }
1584    public String JavaDoc getServletInfo() {
1585        return super.getServletInfo();
1586    }
1587    public void init() throws ServletException JavaDoc {
1588        super.init();
1589    }
1590    public String JavaDoc getServletName() {
1591        return super.getServletName();
1592    }
1593
1594    // BEGIN [added by Pascal Aubry for CAS authentication]
1595
/**
1596     * Tell if Jahia is using Single Sign-On for authentication.
1597     * @return true if SSO should be used, false otherwise.
1598     */

1599    static public boolean usesSso() {
1600        return authPipeline.hasValveOfClass(SsoValve.class);
1601    }
1602    /**
1603     * Return the (first) SSO valve.
1604     * @return a SsoValve instance, or null if none.
1605     */

1606    static public SsoValve getSsoValve() {
1607        return (SsoValve) authPipeline.getFirstValveOfClass(SsoValve.class);
1608    }
1609    // END [added by Pascal Aubry for CAS authentication]
1610

1611    static public Pipeline getAuthPipeline() {
1612        return authPipeline;
1613    }
1614
1615    static public ServletConfig JavaDoc getStaticServletConfig() {
1616        return staticServletConfig;
1617    }
1618
1619    private void loadConfigBeanFactory() throws JahiaException {
1620
1621        // fileExtractors
1622
StringBuffer JavaDoc buff = new StringBuffer JavaDoc(jSettings.getJahiaEtcDiskPath());
1623        buff.append(File.separator);
1624        buff.append("config");
1625        buff.append(File.separator);
1626        buff.append("config.xml");
1627        java.io.InputStream JavaDoc is = null;
1628        try {
1629            is = new java.io.FileInputStream JavaDoc(buff.toString());
1630            configBeanFactory = new XmlBeanFactory(is);
1631        } catch (Throwable JavaDoc t) {
1632            throw new JahiaException("Error loading Config Bean Factory File",
1633                                     "Error loading Config Bean Factory File",
1634                                     JahiaException.CONFIG_ERROR,
1635                                     JahiaException.CONFIG_ERROR, t);
1636        }
1637    }
1638
1639
1640} // end Jahia
1641
Popular Tags