KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opencms > main > OpenCmsCore


1 /*
2  * File : $Source: /usr/local/cvs/opencms/src/org/opencms/main/OpenCmsCore.java,v $
3  * Date : $Date: 2006/05/12 16:05:48 $
4  * Version: $Revision: 1.221 $
5  *
6  * This library is part of OpenCms -
7  * the Open Source Content Mananagement System
8  *
9  * Copyright (c) 2005 Alkacon Software GmbH (http://www.alkacon.com)
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  * Lesser General Public License for more details.
20  *
21  * For further information about Alkacon Software GmbH, please see the
22  * company website: http://www.alkacon.com
23  *
24  * For further information about OpenCms, please see the
25  * project website: http://www.opencms.org
26  *
27  * You should have received a copy of the GNU Lesser General Public
28  * License along with this library; if not, write to the Free Software
29  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30  */

31
32 package org.opencms.main;
33
34 import org.opencms.configuration.CmsConfigurationException;
35 import org.opencms.configuration.CmsConfigurationManager;
36 import org.opencms.configuration.CmsImportExportConfiguration;
37 import org.opencms.configuration.CmsModuleConfiguration;
38 import org.opencms.configuration.CmsSearchConfiguration;
39 import org.opencms.configuration.CmsSystemConfiguration;
40 import org.opencms.configuration.CmsVfsConfiguration;
41 import org.opencms.configuration.CmsWorkplaceConfiguration;
42 import org.opencms.db.CmsDbEntryNotFoundException;
43 import org.opencms.db.CmsDefaultUsers;
44 import org.opencms.db.CmsLoginManager;
45 import org.opencms.db.CmsSecurityManager;
46 import org.opencms.db.CmsSqlManager;
47 import org.opencms.file.CmsObject;
48 import org.opencms.file.CmsProject;
49 import org.opencms.file.CmsProperty;
50 import org.opencms.file.CmsPropertyDefinition;
51 import org.opencms.file.CmsRequestContext;
52 import org.opencms.file.CmsResource;
53 import org.opencms.file.CmsUser;
54 import org.opencms.file.CmsVfsResourceNotFoundException;
55 import org.opencms.flex.CmsFlexCache;
56 import org.opencms.flex.CmsFlexCacheConfiguration;
57 import org.opencms.flex.CmsFlexController;
58 import org.opencms.i18n.CmsEncoder;
59 import org.opencms.i18n.CmsI18nInfo;
60 import org.opencms.i18n.CmsLocaleManager;
61 import org.opencms.i18n.CmsMessageContainer;
62 import org.opencms.importexport.CmsImportExportManager;
63 import org.opencms.jsp.util.CmsErrorBean;
64 import org.opencms.loader.CmsResourceManager;
65 import org.opencms.loader.I_CmsFlexCacheEnabledLoader;
66 import org.opencms.lock.CmsLockManager;
67 import org.opencms.module.CmsModuleManager;
68 import org.opencms.monitor.CmsMemoryMonitor;
69 import org.opencms.monitor.CmsMemoryMonitorConfiguration;
70 import org.opencms.scheduler.CmsScheduleManager;
71 import org.opencms.search.CmsSearchManager;
72 import org.opencms.security.CmsRole;
73 import org.opencms.security.CmsRoleViolationException;
74 import org.opencms.security.CmsSecurityException;
75 import org.opencms.security.I_CmsPasswordHandler;
76 import org.opencms.security.I_CmsValidationHandler;
77 import org.opencms.site.CmsSite;
78 import org.opencms.site.CmsSiteManager;
79 import org.opencms.staticexport.CmsLinkManager;
80 import org.opencms.staticexport.CmsStaticExportManager;
81 import org.opencms.util.CmsFileUtil;
82 import org.opencms.util.CmsPropertyUtils;
83 import org.opencms.util.CmsRequestUtil;
84 import org.opencms.util.CmsStringUtil;
85 import org.opencms.util.CmsUUID;
86 import org.opencms.workplace.CmsWorkplace;
87 import org.opencms.workplace.CmsWorkplaceManager;
88 import org.opencms.xml.CmsXmlContentTypeManager;
89
90 import java.io.IOException JavaDoc;
91 import java.util.ArrayList JavaDoc;
92 import java.util.Collections JavaDoc;
93 import java.util.Date JavaDoc;
94 import java.util.HashMap JavaDoc;
95 import java.util.HashSet JavaDoc;
96 import java.util.Hashtable JavaDoc;
97 import java.util.Iterator JavaDoc;
98 import java.util.List JavaDoc;
99 import java.util.Locale JavaDoc;
100 import java.util.Map JavaDoc;
101 import java.util.Set JavaDoc;
102
103 import javax.servlet.ServletContext JavaDoc;
104 import javax.servlet.ServletException JavaDoc;
105 import javax.servlet.http.HttpServletRequest JavaDoc;
106 import javax.servlet.http.HttpServletResponse JavaDoc;
107 import javax.servlet.http.HttpSession JavaDoc;
108
109 import org.apache.commons.codec.binary.Base64;
110 import org.apache.commons.collections.ExtendedProperties;
111 import org.apache.commons.logging.Log;
112
113 /**
114  * The internal implementation of the core OpenCms "operating system" functions.<p>
115  *
116  * All access to this class must be done through the public static methods
117  * of the <code>{@link org.opencms.main.OpenCms}</code> object.
118  * Under no circumstances should you ever try to access this class directly.<p>
119  *
120  * This class is so OpenCms internal you should not even be reading this documentation ;-)<p>
121  *
122  * Any request to the <code>{@link org.opencms.main.OpenCmsServlet}</code> will be forwarded to this core class.
123  * The core will then try to map the request to a VFS (Virtual File System) URI,
124  * that is a <code>{@link org.opencms.file.CmsResource}</code> in the OpenCms database.
125  * If a resource is found, it will be read and forwarded to
126  * to the corresponding <code>{@link org.opencms.loader.I_CmsResourceLoader}</code>,
127  * which will then generate the output for the requested resource and return it to the requesting client.<p>
128  *
129  * There will be only one singleton instance of this object created for
130  * this core class. This means that in the default configuration, where
131  * OpenCms is accessed through a servlet context, there will be only one instance of
132  * the core in that servlet context.<p>
133  *
134  * @author Alexander Kandzior
135  *
136  * @version $Revision: 1.221 $
137  *
138  * @since 6.0.0
139  */

140 public final class OpenCmsCore {
141
142     /** Lock object for synchronization. */
143     private static final Object JavaDoc LOCK = new Object JavaDoc();
144
145     /** The static log object for this class. */
146     private static final Log LOG = CmsLog.getLog(OpenCmsCore.class);
147
148     /** Indicates if the configuration was sucessfully finished or not. */
149     private static CmsMessageContainer m_errorCondition;
150
151     /** One instance to rule them all, one instance to find them... */
152     private static OpenCmsCore m_instance;
153
154     /** The configuration manager that contains the information from the XML configuration. */
155     private CmsConfigurationManager m_configurationManager;
156
157     /** List of configured directory default file names. */
158     private List JavaDoc m_defaultFiles;
159
160     /** The default user and group names. */
161     private CmsDefaultUsers m_defaultUsers;
162
163     /** The event manager for the event handling. */
164     private CmsEventManager m_eventManager;
165
166     /** The set of configured export points. */
167     private Set JavaDoc m_exportPoints;
168
169     /** The site manager contains information about the Cms import/export. */
170     private CmsImportExportManager m_importExportManager;
171
172     /** The link manager to resolve links in &lt;cms:link&gt; tags. */
173     private CmsLinkManager m_linkManager;
174
175     /** The locale manager used for obtaining the current locale. */
176     private CmsLocaleManager m_localeManager;
177
178     /** The lock manager used for the locking mechanism. */
179     private CmsLockManager m_lockManager;
180
181     /** The login manager. */
182     private CmsLoginManager m_loginManager;
183
184     /** The memory monitor for the collection of memory and runtime statistics. */
185     private CmsMemoryMonitor m_memoryMonitor;
186
187     /** The module manager. */
188     private CmsModuleManager m_moduleManager;
189
190     /** The password handler used to digest and validate passwords. */
191     private I_CmsPasswordHandler m_passwordHandler;
192
193     /** The configured request handlers that handle "special" requests, for example in the static export on demand. */
194     private Map JavaDoc m_requestHandlers;
195
196     /** Stores the resource init handlers that allow modification of the requested resource. */
197     private List JavaDoc m_resourceInitHandlers;
198
199     /** The resource manager. */
200     private CmsResourceManager m_resourceManager;
201
202     /** The runlevel of this OpenCmsCore object instance. */
203     private int m_runLevel;
204
205     /** The runtime properties allow storage of system wide accessible runtime information. */
206     private Map JavaDoc m_runtimeProperties;
207
208     /** The configured scheduler manager. */
209     private CmsScheduleManager m_scheduleManager;
210
211     /** The search manager provides indexing and searching. */
212     private CmsSearchManager m_searchManager;
213
214     /** The security manager to access the database and validate user permissions. */
215     private CmsSecurityManager m_securityManager;
216
217     /** The session manager. */
218     private CmsSessionManager m_sessionManager;
219
220     /** The site manager contains information about all configured sites. */
221     private CmsSiteManager m_siteManager;
222
223     /** The static export manager. */
224     private CmsStaticExportManager m_staticExportManager;
225
226     /** The system information container for "read only" system settings. */
227     private CmsSystemInfo m_systemInfo;
228
229     /** The thread store. */
230     private CmsThreadStore m_threadStore;
231
232     /** The runtime validation handler. */
233     private I_CmsValidationHandler m_validationHandler;
234
235     /** The workplace manager contains information about the global workplace settings. */
236     private CmsWorkplaceManager m_workplaceManager;
237
238     /** The XML content type manager that contains the initialized XML content types. */
239     private CmsXmlContentTypeManager m_xmlContentTypeManager;
240
241     /**
242      * Protected constructor that will initialize the singleton OpenCms instance
243      * with runlevel {@link OpenCms#RUNLEVEL_1_CORE_OBJECT}.<p>
244      *
245      * @throws CmsInitException in case of errors during the initialization
246      */

247     private OpenCmsCore()
248     throws CmsInitException {
249
250         synchronized (LOCK) {
251             if (m_instance != null && (m_instance.getRunLevel() > OpenCms.RUNLEVEL_0_OFFLINE)) {
252                 throw new CmsInitException(Messages.get().container(Messages.ERR_ALREADY_INITIALIZED_0));
253             }
254             initMembers();
255             m_instance = this;
256             setRunLevel(OpenCms.RUNLEVEL_1_CORE_OBJECT);
257         }
258     }
259
260     /**
261      * Returns the initialized OpenCms singleton instance.<p>
262      *
263      * @return the initialized OpenCms singleton instance
264      */

265     protected static OpenCmsCore getInstance() {
266
267         if (m_errorCondition != null) {
268             // OpenCms is not properly initialized
269
throw new CmsInitException(m_errorCondition, false);
270         }
271         if (m_instance == null) {
272             try {
273                 // create a new core object with runlevel 1
274
m_instance = new OpenCmsCore();
275             } catch (CmsInitException e) {
276                 // already initialized, this is all we need
277
}
278         }
279         return m_instance;
280     }
281
282     /**
283      * Sets the error condition.<p>
284      *
285      * @param errorCondition the error condition to set
286      */

287     protected static void setErrorCondition(CmsMessageContainer errorCondition) {
288
289         // init exceptions should only be thrown during setup process
290
if ((m_instance != null) && (m_instance.getRunLevel() < OpenCms.RUNLEVEL_3_SHELL_ACCESS)) {
291             if (!Messages.ERR_CRITICAL_INIT_WIZARD_0.equals(errorCondition.getKey())) {
292                 // if wizard is still enabled allow retry of initialization (for setup wizard)
293
m_errorCondition = errorCondition;
294                 // output an error message to the console
295
System.err.println(Messages.get().getBundle().key(
296                     Messages.LOG_INIT_FAILURE_MESSAGE_1,
297                     errorCondition.key()));
298             }
299             LOG.error(errorCondition.key());
300             m_instance = null;
301         } else if (m_instance != null) {
302             // OpenCms already was successfull initialized
303
LOG.warn(Messages.get().getBundle().key(
304                 Messages.LOG_INIT_INVALID_ERROR_2,
305                 new Integer JavaDoc(m_instance.getRunLevel()),
306                 errorCondition.key()));
307         }
308     }
309
310     /**
311      * Adds the specified request handler to the Map of OpenCms request handlers. <p>
312      *
313      * @param handler the handler to add
314      */

315     protected void addRequestHandler(I_CmsRequestHandler handler) {
316
317         if (handler == null) {
318             return;
319         }
320         String JavaDoc[] names = handler.getHandlerNames();
321         for (int i = 0; i < names.length; i++) {
322             String JavaDoc name = names[i];
323             if (m_requestHandlers.get(name) != null) {
324                 CmsLog.INIT.error(Messages.get().getBundle().key(Messages.LOG_DUPLICATE_REQUEST_HANDLER_1, name));
325                 continue;
326             }
327             m_requestHandlers.put(name, handler);
328             if (CmsLog.INIT.isInfoEnabled()) {
329                 CmsLog.INIT.info(Messages.get().getBundle().key(
330                     Messages.INIT_ADDED_REQUEST_HANDLER_2,
331                     name,
332                     handler.getClass().getName()));
333             }
334         }
335     }
336
337     /**
338      * Returns the initialized OpenCms configuration manager.<p>
339      *
340      * @return the initialized OpenCms configuration manager
341      */

342     protected CmsConfigurationManager getConfigurationManager() {
343
344         return m_configurationManager;
345     }
346
347     /**
348      * Returns the configured list of default directory file names.<p>
349      *
350      * Caution: This list can not be modified.<p>
351      *
352      * @return the configured list of default directory file names
353      */

354     protected List JavaDoc getDefaultFiles() {
355
356         return m_defaultFiles;
357     }
358
359     /**
360      * Returns the default user and group name configuration.<p>
361      *
362      * @return the default user and group name configuration
363      */

364     protected CmsDefaultUsers getDefaultUsers() {
365
366         return m_defaultUsers;
367     }
368
369     /**
370      * Returns the OpenCms event manager.<p>
371      *
372      * @return the OpenCms event manager
373      */

374     protected CmsEventManager getEventManager() {
375
376         return m_eventManager;
377     }
378
379     /**
380      * Returns the configured export points,
381      * the returned set being an unmodifiable set.<p>
382      *
383      * @return an unmodifiable set of the configured export points
384      */

385     protected Set JavaDoc getExportPoints() {
386
387         return m_exportPoints;
388     }
389
390     /**
391      * Returns the initialized import/export manager,
392      * which contains information about the Cms import/export.<p>
393      *
394      * @return the initialized import/export manager
395      */

396     protected CmsImportExportManager getImportExportManager() {
397
398         return m_importExportManager;
399     }
400
401     /**
402      * Returns the link manager to resolve links in &lt;link&gt; tags.<p>
403      *
404      * @return the link manager to resolve links in &lt;link&gt; tags
405      */

406     protected CmsLinkManager getLinkManager() {
407
408         return m_linkManager;
409     }
410
411     /**
412      * Returns the locale manager used for obtaining the current locale.<p>
413      *
414      * @return the locale manager
415      */

416     protected CmsLocaleManager getLocaleManager() {
417
418         return m_localeManager;
419     }
420
421     /**
422      * Returns the lock manager used for the locking mechanism.<p>
423      *
424      * @return the lock manager used for the locking mechanism
425      */

426     protected CmsLockManager getLockManager() {
427
428         return m_lockManager;
429     }
430
431     /**
432      * Returns the login manager used to check the validity of a login.<p>
433      *
434      * @return the login manager
435      */

436     protected CmsLoginManager getLoginManager() {
437
438         return m_loginManager;
439     }
440
441     /**
442      * Returns the memory monitor.<p>
443      *
444      * @return the memory monitor
445      */

446     protected CmsMemoryMonitor getMemoryMonitor() {
447
448         return m_memoryMonitor;
449     }
450
451     /**
452      * Returns the module manager.<p>
453      *
454      * @return the module manager
455      */

456     protected CmsModuleManager getModuleManager() {
457
458         return m_moduleManager;
459     }
460
461     /**
462      * Return the password handler.<p>
463      *
464      * @return the password handler
465      */

466     protected I_CmsPasswordHandler getPasswordHandler() {
467
468         return m_passwordHandler;
469     }
470
471     /**
472      * Returns the handler instance for the specified name,
473      * or null if the name does not match any handler name.<p>
474      *
475      * @param name the name of the handler instance to return
476      * @return the handler instance for the specified name
477      */

478     protected I_CmsRequestHandler getRequestHandler(String JavaDoc name) {
479
480         return (I_CmsRequestHandler)m_requestHandlers.get(name);
481     }
482
483     /**
484      * Returns the resource manager.<p>
485      *
486      * @return the resource manager
487      */

488     protected CmsResourceManager getResourceManager() {
489
490         return m_resourceManager;
491     }
492
493     /**
494      * Returns the runlevel of this OpenCmsCore object instance.<p>
495      *
496      * For a detailed description about the possible run levels,
497      * please see {@link OpenCms#getRunLevel()}.<p>
498      *
499      * @return the runlevel of this OpenCmsCore object instance
500      *
501      * @see OpenCms#getRunLevel()
502      */

503     protected int getRunLevel() {
504
505         return m_runLevel;
506     }
507
508     /**
509      * Looks up a value in the runtime property Map.<p>
510      *
511      * @param key the key to look up in the runtime properties
512      * @return the value for the key, or null if the key was not found
513      */

514     protected Object JavaDoc getRuntimeProperty(Object JavaDoc key) {
515
516         return m_runtimeProperties.get(key);
517     }
518
519     /**
520      * Returns the configured schedule manager.<p>
521      *
522      * @return the configured schedule manager
523      */

524     protected CmsScheduleManager getScheduleManager() {
525
526         return m_scheduleManager;
527     }
528
529     /**
530      * Returns the initialized search manager,
531      * which provides indexing and searching operations.<p>
532      *
533      * @return the initialized search manager
534      */

535     protected CmsSearchManager getSearchManager() {
536
537         return m_searchManager;
538     }
539
540     /**
541      * Returns the initialized OpenCms security manager.<p>
542      *
543      * @return the initialized OpenCms security manager
544      */

545     protected CmsSecurityManager getSecurityManager() {
546
547         return m_securityManager;
548     }
549
550     /**
551      * Returns the session manager.<p>
552      *
553      * @return the session manager
554      */

555     protected CmsSessionManager getSessionManager() {
556
557         return m_sessionManager;
558     }
559
560     /**
561      * Returns the initialized site manager,
562      * which contains information about all configured sites.<p>
563      *
564      * @return the initialized site manager
565      */

566     protected CmsSiteManager getSiteManager() {
567
568         return m_siteManager;
569     }
570
571     /**
572      * Returns an instance of the common sql manager.<p>
573      *
574      * @return an instance of the common sql manager
575      */

576     protected CmsSqlManager getSqlManager() {
577
578         return m_securityManager.getSqlManager();
579     }
580
581     /**
582      * Returns the properties for the static export.<p>
583      *
584      * @return the properties for the static export
585      */

586     protected CmsStaticExportManager getStaticExportManager() {
587
588         return m_staticExportManager;
589     }
590
591     /**
592      * Returns the system information storage.<p>
593      *
594      * @return the system information storage
595      */

596     protected CmsSystemInfo getSystemInfo() {
597
598         return m_systemInfo;
599     }
600
601     /**
602      * Returns the OpenCms Thread store.<p>
603      *
604      * @return the OpenCms Thread store
605      */

606     protected CmsThreadStore getThreadStore() {
607
608         return m_threadStore;
609     }
610
611     /**
612      * Returns the runtime validation handler.<p>
613      *
614      * @return the validation handler
615      */

616     protected I_CmsValidationHandler getValidationHandler() {
617
618         return m_validationHandler;
619     }
620
621     /**
622      * Returns the initialized workplace manager,
623      * which contains information about the global workplace settings.<p>
624      *
625      * @return the initialized workplace manager
626      */

627     protected CmsWorkplaceManager getWorkplaceManager() {
628
629         return m_workplaceManager;
630     }
631
632     /**
633      * Returns the XML content type manager.<p>
634      *
635      * @return the XML content type manager
636      */

637     protected CmsXmlContentTypeManager getXmlContentTypeManager() {
638
639         if (m_xmlContentTypeManager != null) {
640             return m_xmlContentTypeManager;
641         }
642         if (getRunLevel() == OpenCms.RUNLEVEL_1_CORE_OBJECT) {
643             // this is only to enable test cases to run
644
m_xmlContentTypeManager = CmsXmlContentTypeManager.createTypeManagerForTestCases();
645         }
646         return m_xmlContentTypeManager;
647     }
648
649     /**
650      * Returns an independent copy of the provided CmsObject.<p>
651      *
652      * This can be useful in case a permanent reference to a CmsObject is stored.
653      * Changing the request context values (for example project, siteroot) in the new CmsObject
654      * will have no side effects to the CmsObject it was copied form.<p>
655      *
656      * @param cms the CmsObject to create a copy of
657      *
658      * @return an independent copy of the provided CmsObject
659      *
660      * @throws CmsException in case the intialization failed
661      *
662      * @see OpenCms#initCmsObject(CmsObject)
663      * @see OpenCms#initCmsObject(CmsObject, CmsContextInfo)
664      * @see OpenCms#initCmsObject(String)
665      */

666     protected CmsObject initCmsObject(CmsObject cms) throws CmsException {
667
668         CmsContextInfo contextInfo = new CmsContextInfo(cms.getRequestContext());
669         return initCmsObject(contextInfo);
670     }
671
672     /**
673      * Returns an initialized CmsObject with the user and context initialized as provided.<p>
674      *
675      * Note: Only if the provided <code>adminCms</code> CmsObject has admin permissions,
676      * this method allows the creation a CmsObject for any existing user. Otherwise
677      * only the default users 'Guest' and 'Export' can initialized with
678      * this method, all other user names will throw an Exception.<p>
679      *
680      * @param adminCms must either be initialized with "Admin" permissions, or null
681      * @param contextInfo the context info to create a CmsObject for
682      *
683      * @return an initialized CmsObject with the given users permissions
684      *
685      * @throws CmsException if an invalid user name was provided
686      * @throws CmsRoleViolationException if the current user does not have the role permissions to create a context for the requested user
687      *
688      * @see org.opencms.db.CmsDefaultUsers#getUserGuest()
689      * @see org.opencms.db.CmsDefaultUsers#getUserExport()
690      * @see OpenCms#initCmsObject(CmsObject)
691      * @see OpenCms#initCmsObject(CmsObject, CmsContextInfo)
692      * @see OpenCms#initCmsObject(String)
693      */

694     protected CmsObject initCmsObject(CmsObject adminCms, CmsContextInfo contextInfo)
695     throws CmsRoleViolationException, CmsException {
696
697         String JavaDoc userName = contextInfo.getUserName();
698
699         if (adminCms == null || !adminCms.hasRole(CmsRole.ADMINISTRATOR)) {
700             if (!userName.equals(getDefaultUsers().getUserGuest())
701                 && !userName.equals(getDefaultUsers().getUserExport())) {
702
703                 // if no admin object is provided, only "Guest" or "Export" user can be generated
704
CmsMessageContainer message = Messages.get().container(
705                     Messages.ERR_INVALID_INIT_USER_2,
706                     userName,
707                     ((adminCms != null) ? (adminCms.getRequestContext().currentUser().getName()) : ""));
708                 if (LOG.isWarnEnabled()) {
709                     LOG.warn(message.key());
710                 }
711                 throw new CmsRoleViolationException(message);
712             }
713         }
714
715         return initCmsObject(contextInfo);
716     }
717
718     /**
719      * Returns an initialized CmsObject with the user initialized as provided,
720      * with the "Online" project selected and "/" set as the current site root.<p>
721      *
722      * Note: Only the default users 'Guest' and 'Export' can initialized with
723      * this method, all other user names will throw an Exception.<p>
724      *
725      * @param user the user name to initialize, can only be
726      * {@link org.opencms.db.CmsDefaultUsers#getUserGuest()} or
727      * {@link org.opencms.db.CmsDefaultUsers#getUserExport()}
728      *
729      * @return an initialized CmsObject with the given users permissions
730      *
731      * @throws CmsException if an invalid user name was provided, or if something else goes wrong
732      *
733      * @see org.opencms.db.CmsDefaultUsers#getUserGuest()
734      * @see org.opencms.db.CmsDefaultUsers#getUserExport()
735      * @see OpenCms#initCmsObject(String)
736      * @see #initCmsObject(CmsObject, CmsContextInfo)
737      */

738     protected CmsObject initCmsObject(String JavaDoc user) throws CmsException {
739
740         return initCmsObject(null, new CmsContextInfo(user));
741     }
742
743     /**
744      * Constructor to create a new OpenCms object.<p>
745      *
746      * It reads the configurations from the <code>opencms.properties</code>
747      * file in the <code>config/</code> subdirectory. With the information
748      * from this file is inits a ResourceBroker (Database access module),
749      * various caching systems and other options.<p>
750      *
751      * This will only be done once per accessing class.
752      *
753      * @param configuration the configurations from the <code>opencms.properties</code> file
754      * @throws CmsInitException in case OpenCms can not be initialized
755      */

756     protected synchronized void initConfiguration(ExtendedProperties configuration) throws CmsInitException {
757
758         String JavaDoc systemEncoding = null;
759         try {
760             systemEncoding = System.getProperty("file.encoding");
761         } catch (SecurityException JavaDoc se) {
762             // security manager is active, but we will try other options before giving up
763
}
764         if (CmsLog.INIT.isInfoEnabled()) {
765             CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_FILE_ENCODING_1, systemEncoding));
766         }
767
768         // read server ethernet address (MAC) and init UUID generator
769
String JavaDoc ethernetAddress = configuration.getString("server.ethernet.address", CmsUUID.getDummyEthernetAddress());
770         if (CmsLog.INIT.isInfoEnabled()) {
771             CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_ETHERNET_ADDRESS_1, ethernetAddress));
772         }
773         CmsUUID.init(ethernetAddress);
774
775         // set the server name
776
String JavaDoc serverName = configuration.getString("server.name", "OpenCmsServer");
777         getSystemInfo().setServerName(serverName);
778
779         // initialize the lock manager
780
m_lockManager = CmsLockManager.getInstance();
781
782         // check the installed Java SDK
783
try {
784             if (CmsLog.INIT.isInfoEnabled()) {
785                 String JavaDoc jdkinfo = System.getProperty("java.vm.name") + " ";
786                 jdkinfo += System.getProperty("java.vm.version") + " ";
787                 jdkinfo += System.getProperty("java.vm.info") + " ";
788                 jdkinfo += System.getProperty("java.vm.vendor") + " ";
789                 CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_JAVA_VM_1, jdkinfo));
790                 String JavaDoc osinfo = System.getProperty("os.name") + " ";
791                 osinfo += System.getProperty("os.version") + " ";
792                 osinfo += System.getProperty("os.arch") + " ";
793                 CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_OPERATING_SYSTEM_1, osinfo));
794             }
795         } catch (Exception JavaDoc e) {
796             throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_PROP_0), e);
797         }
798
799         // initialize the memory monitor
800
m_memoryMonitor = new CmsMemoryMonitor();
801
802         // create the configuration manager instance
803
m_configurationManager = new CmsConfigurationManager(getSystemInfo().getAbsoluteRfsPathRelativeToWebInf(
804             CmsSystemInfo.FOLDER_CONFIG));
805         // store the configuration read from "opencms.properties" in the configuration manager
806
m_configurationManager.setConfiguration(configuration);
807
808         // now load the XML configuration
809
try {
810             m_configurationManager.loadXmlConfiguration();
811         } catch (Exception JavaDoc e) {
812             throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_XML_0), e);
813         }
814
815         // get the system configuration
816
CmsSystemConfiguration systemConfiguration = (CmsSystemConfiguration)m_configurationManager.getConfiguration(CmsSystemConfiguration.class);
817
818         // get the event manager from the configuration and initialize it with the events already registered
819
CmsEventManager configuredEventManager = systemConfiguration.getEventManager();
820         configuredEventManager.initialize(m_eventManager);
821         m_eventManager = configuredEventManager;
822
823         // check if the encoding setting is valid
824
String JavaDoc setEncoding = systemConfiguration.getDefaultContentEncoding();
825         String JavaDoc defaultEncoding = CmsEncoder.lookupEncoding(setEncoding, null);
826         if (defaultEncoding == null) {
827             // we can not start without a valid encoding setting
828
throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_ENCODING_1, setEncoding));
829         }
830         if (CmsLog.INIT.isInfoEnabled()) {
831             CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_OPENCMS_ENCODING_1, defaultEncoding));
832         }
833         getSystemInfo().setDefaultEncoding(defaultEncoding);
834
835         // initialize the memory monitor
836
CmsMemoryMonitorConfiguration memoryMonitorConfiguration = systemConfiguration.getCmsMemoryMonitorConfiguration();
837         m_memoryMonitor.initialize(memoryMonitorConfiguration);
838
839         // set version history information
840
getSystemInfo().setVersionHistorySettings(
841             systemConfiguration.isVersionHistoryEnabled(),
842             systemConfiguration.getVersionHistoryMaxCount());
843         // set mail configuration
844
getSystemInfo().setMailSettings(systemConfiguration.getMailSettings());
845         // set HTTP authentication settings
846
getSystemInfo().setHttpAuthenticationSettings(systemConfiguration.getHttpAuthenticationSettings());
847
848         // set content notification settings
849
getSystemInfo().setNotificationTime(systemConfiguration.getNotificationTime());
850         getSystemInfo().setNotificationProject(systemConfiguration.getNotificationProject());
851         // set the scheduler manager
852
m_scheduleManager = systemConfiguration.getScheduleManager();
853         // set resource init classes
854
m_resourceInitHandlers = systemConfiguration.getResourceInitHandlers();
855         // register request handler classes
856
Iterator JavaDoc it = systemConfiguration.getRequestHandlers().iterator();
857         while (it.hasNext()) {
858             I_CmsRequestHandler handler = (I_CmsRequestHandler)it.next();
859             addRequestHandler(handler);
860             if (CmsLog.INIT.isInfoEnabled()) {
861                 CmsLog.INIT.warn(Messages.get().getBundle().key(
862                     Messages.INIT_REQUEST_HANDLER_CLASS_1,
863                     handler.getClass().getName()));
864             }
865         }
866
867         // read the default user configuration
868
m_defaultUsers = systemConfiguration.getCmsDefaultUsers();
869
870         try {
871             // initialize the group names for the system roles
872
CmsRole.initialize(m_defaultUsers);
873         } catch (CmsSecurityException e) {
874             // this should never happen
875
throw new CmsInitException(
876                 Messages.get().container(Messages.ERR_CRITICAL_INIT_GENERIC_1, e.getMessage()),
877                 e);
878         }
879
880         // get the site manager from the configuration
881
m_siteManager = systemConfiguration.getSiteManager();
882
883         // get the VFS / resource configuration
884
CmsVfsConfiguration vfsConfiguation = (CmsVfsConfiguration)m_configurationManager.getConfiguration(CmsVfsConfiguration.class);
885         m_resourceManager = vfsConfiguation.getResourceManager();
886         m_xmlContentTypeManager = vfsConfiguation.getXmlContentTypeManager();
887         m_defaultFiles = vfsConfiguation.getDefaultFiles();
888
889         // initialize translation engines
890
m_resourceManager.setTranslators(vfsConfiguation.getFolderTranslator(), vfsConfiguation.getFileTranslator());
891
892         // try to initialize the flex cache
893
CmsFlexCache flexCache = null;
894         try {
895             if (CmsLog.INIT.isInfoEnabled()) {
896                 CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_FLEX_CACHE_STARTING_0));
897             }
898             // get the flex cache configuration from the SystemConfiguration
899
CmsFlexCacheConfiguration flexCacheConfiguration = systemConfiguration.getCmsFlexCacheConfiguration();
900             // pass configuration to flex cache for initialization
901
flexCache = new CmsFlexCache(flexCacheConfiguration);
902             if (CmsLog.INIT.isInfoEnabled()) {
903                 CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_FLEX_CACHE_FINISHED_0));
904             }
905         } catch (Exception JavaDoc e) {
906             if (CmsLog.INIT.isWarnEnabled()) {
907                 CmsLog.INIT.warn(Messages.get().getBundle().key(Messages.INIT_FLEX_CACHE_ERROR_1, e.getMessage()));
908             }
909         }
910
911         if (flexCache != null) {
912             // check all reasource loaders if they require the Flex cache
913
Iterator JavaDoc i = m_resourceManager.getLoaders().iterator();
914             while (i.hasNext()) {
915                 Object JavaDoc o = i.next();
916                 if (o instanceof I_CmsFlexCacheEnabledLoader) {
917                     // this resource loader requires the Flex cache
918
((I_CmsFlexCacheEnabledLoader)o).setFlexCache(flexCache);
919                 }
920             }
921         }
922
923         // get the import/export configuration
924
CmsImportExportConfiguration importExportConfiguration = (CmsImportExportConfiguration)m_configurationManager.getConfiguration(CmsImportExportConfiguration.class);
925         m_importExportManager = importExportConfiguration.getImportExportManager();
926         m_staticExportManager = importExportConfiguration.getStaticExportManager();
927
928         // get the search configuration
929
CmsSearchConfiguration searchConfiguration = (CmsSearchConfiguration)m_configurationManager.getConfiguration(CmsSearchConfiguration.class);
930         m_searchManager = searchConfiguration.getSearchManager();
931
932         // get the workplace configuration
933
CmsWorkplaceConfiguration workplaceConfiguration = (CmsWorkplaceConfiguration)m_configurationManager.getConfiguration(CmsWorkplaceConfiguration.class);
934         m_workplaceManager = workplaceConfiguration.getWorkplaceManager();
935         // add the export points from the workplace
936
addExportPoints(m_workplaceManager.getExportPoints());
937
938         // get the module configuration
939
CmsModuleConfiguration moduleConfiguration = (CmsModuleConfiguration)m_configurationManager.getConfiguration(CmsModuleConfiguration.class);
940         m_moduleManager = moduleConfiguration.getModuleManager();
941
942         // get the password handler
943
m_passwordHandler = systemConfiguration.getPasswordHandler();
944
945         // get the validation handler
946
m_validationHandler = systemConfiguration.getValidationHandler();
947
948         // get the login manager
949
m_loginManager = systemConfiguration.getLoginManager();
950
951         // init the OpenCms security manager
952
m_securityManager = CmsSecurityManager.newInstance(
953             m_configurationManager,
954             systemConfiguration.getRuntimeInfoFactory());
955
956         // initialize the Thread store
957
m_threadStore = new CmsThreadStore();
958
959         // initialize the link manager
960
m_linkManager = new CmsLinkManager();
961
962         // store the runtime properties
963
m_runtimeProperties.putAll(systemConfiguration.getRuntimeProperties());
964
965         // get an Admin cms context object with site root set to "/"
966
CmsObject adminCms;
967         try {
968             adminCms = initCmsObject(null, null, getDefaultUsers().getUserAdmin(), null);
969         } catch (CmsException e) {
970             throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_ADMINCMS_0), e);
971         }
972
973         // now initialize the managers
974
try {
975             // initialize the scheduler
976
m_scheduleManager.initialize(initCmsObject(adminCms));
977
978             // initialize the locale manager
979
m_localeManager = systemConfiguration.getLocaleManager();
980             m_localeManager.initialize(initCmsObject(adminCms));
981
982             // initialize the site manager
983
m_siteManager.initialize(initCmsObject(adminCms));
984
985             // initialize the static export manager
986
m_staticExportManager.initialize(initCmsObject(adminCms));
987
988             // initialize the XML content type manager
989
m_xmlContentTypeManager.initialize(initCmsObject(adminCms));
990
991             // intialize the module manager
992
m_moduleManager.initialize(initCmsObject(adminCms), m_configurationManager);
993
994             // initialize the resource manager
995
m_resourceManager.initialize(initCmsObject(adminCms));
996
997             // initialize the search manager
998
m_searchManager.initialize(initCmsObject(adminCms));
999
1000            // initialize the workplace manager
1001
m_workplaceManager.initialize(initCmsObject(adminCms));
1002        } catch (CmsException e) {
1003            throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_MANAGERS_0), e);
1004        }
1005    }
1006
1007    /**
1008     * Initialization of the OpenCms runtime environment.<p>
1009     *
1010     * The connection information for the database is read
1011     * from the <code>opencms.properties</code> configuration file and all
1012     * driver manager are initialized via the initalizer,
1013     * which usually will be an instance of a <code>OpenCms</code> class.
1014     *
1015     * @param context configuration of OpenCms from <code>web.xml</code>
1016     * @throws CmsInitException in case OpenCms can not be initialized
1017     */

1018    protected synchronized void initContext(ServletContext JavaDoc context) throws CmsInitException {
1019
1020        // read the the OpenCms servlet mapping from the servlet context parameters
1021
String JavaDoc servletMapping = context.getInitParameter(OpenCmsServlet.SERVLET_PARAM_OPEN_CMS_SERVLET);
1022        if (servletMapping == null) {
1023            throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_SERVLET_0));
1024        }
1025
1026        // check for OpenCms home (base) directory path
1027
String JavaDoc webInfPath = context.getInitParameter(OpenCmsServlet.SERVLET_PARAM_OPEN_CMS_HOME);
1028        if (CmsStringUtil.isEmpty(webInfPath)) {
1029            webInfPath = CmsFileUtil.searchWebInfFolder(context.getRealPath("/"));
1030            if (CmsStringUtil.isEmpty(webInfPath)) {
1031                throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_FOLDER_0));
1032            }
1033        }
1034
1035        // read the the default context name from the servlet context parameters
1036
String JavaDoc defaultWebApplication = context.getInitParameter("DefaultWebApplication");
1037        if (defaultWebApplication == null) {
1038            // not set in web.xml, so we use "ROOT" which should usually work since it is the (de-facto) standard
1039
defaultWebApplication = "ROOT";
1040        }
1041
1042        // read the the webapp context name from the servlet context parameters
1043
// this is needed in case an application server specific deployment descriptor is used to changed the webapp context
1044
String JavaDoc webApplicationContext = context.getInitParameter(OpenCmsServlet.SERVLET_PARAM_WEB_APPLICATION_CONTEXT);
1045
1046        // now initialize the system info with the path and mapping information
1047
getSystemInfo().init(webInfPath, servletMapping, webApplicationContext, defaultWebApplication);
1048
1049        // Collect the configurations
1050
ExtendedProperties configuration = null;
1051        try {
1052            configuration = CmsPropertyUtils.loadProperties(getSystemInfo().getConfigurationFileRfsPath());
1053        } catch (Exception JavaDoc e) {
1054            throw new CmsInitException(Messages.get().container(
1055                Messages.ERR_CRITICAL_INIT_PROPFILE_1,
1056                getSystemInfo().getConfigurationFileRfsPath()), e);
1057        }
1058
1059        // check if the wizard is enabled, if so stop initialization
1060
if (configuration.getBoolean("wizard.enabled", true)) {
1061            throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_WIZARD_0));
1062        }
1063        // output startup message and copyright to STDERR
1064
System.err.println(Messages.get().getBundle().key(
1065            Messages.LOG_STARTUP_CONSOLE_NOTE_2,
1066            OpenCms.getSystemInfo().getVersionName(),
1067            getSystemInfo().getWebApplicationName()));
1068        for (int i = 0; i < Messages.COPYRIGHT_BY_ALKACON.length; i++) {
1069            System.err.println(Messages.COPYRIGHT_BY_ALKACON[i]);
1070        }
1071        System.err.println();
1072
1073        // output startup message to logfile
1074
if (CmsLog.INIT.isInfoEnabled()) {
1075            CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
1076            CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
1077            CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
1078            CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
1079            for (int i = 0; i < Messages.COPYRIGHT_BY_ALKACON.length; i++) {
1080                CmsLog.INIT.info(". " + Messages.COPYRIGHT_BY_ALKACON[i]);
1081            }
1082            CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_LINE_0));
1083            CmsLog.INIT.info(Messages.get().getBundle().key(
1084                Messages.INIT_STARTUP_TIME_1,
1085                new Date JavaDoc(System.currentTimeMillis())));
1086            CmsLog.INIT.info(Messages.get().getBundle().key(
1087                Messages.INIT_OPENCMS_VERSION_1,
1088                OpenCms.getSystemInfo().getVersionName()));
1089            CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_SERVLET_CONTAINER_1, context.getServerInfo()));
1090            CmsLog.INIT.info(Messages.get().getBundle().key(
1091                Messages.INIT_WEBAPP_NAME_1,
1092                getSystemInfo().getWebApplicationName()));
1093            CmsLog.INIT.info(Messages.get().getBundle().key(
1094                Messages.INIT_SERVLET_PATH_1,
1095                getSystemInfo().getServletPath()));
1096            CmsLog.INIT.info(Messages.get().getBundle().key(
1097                Messages.INIT_OPENCMS_CONTEXT_1,
1098                getSystemInfo().getOpenCmsContext()));
1099            CmsLog.INIT.info(Messages.get().getBundle().key(
1100                Messages.INIT_WEBINF_PATH_1,
1101                getSystemInfo().getWebInfRfsPath()));
1102            CmsLog.INIT.info(Messages.get().getBundle().key(
1103                Messages.INIT_PROPERTY_FILE_1,
1104                getSystemInfo().getConfigurationFileRfsPath()));
1105            CmsLog.INIT.info(Messages.get().getBundle().key(
1106                Messages.INIT_LOG_FILE_1,
1107                getSystemInfo().getLogFileRfsPath()));
1108        }
1109
1110        // initialize the configuration
1111
initConfiguration(configuration);
1112    }
1113
1114    /**
1115     * Initialize member variables.<p>
1116     */

1117    protected void initMembers() {
1118
1119        synchronized (LOCK) {
1120            m_resourceInitHandlers = new ArrayList JavaDoc();
1121            m_requestHandlers = new HashMap JavaDoc();
1122            m_systemInfo = new CmsSystemInfo();
1123            m_exportPoints = Collections.EMPTY_SET;
1124            m_defaultUsers = new CmsDefaultUsers();
1125            m_localeManager = new CmsLocaleManager(Locale.ENGLISH);
1126            m_sessionManager = new CmsSessionManager();
1127            m_runtimeProperties = new Hashtable JavaDoc();
1128            // the default event manager must be available because the configuration already registers events
1129
m_eventManager = new CmsEventManager();
1130        }
1131    }
1132
1133    /**
1134     * Reads the requested resource from the OpenCms VFS,
1135     * in case a directory name is requested, the default files of the
1136     * directory will be looked up and the first match is returned.<p>
1137     *
1138     * The resource that is returned is always a <code>{@link org.opencms.file.CmsFile}</code>,
1139     * even though the content will usually not be loaded in the result. Folders are never returned since
1140     * the point of this method is really to load the default file if just a folder name is requested.<p>
1141     *
1142     * The URI stored in the given OpenCms user context will be changed to the URI of the resource
1143     * that was found and returned.<p>
1144     *
1145     * Implementing and configuring an <code>{@link I_CmsResourceInit}</code> handler
1146     * allows to customize the process of default resource selection.<p>
1147     *
1148     * @param cms the current users OpenCms context
1149     * @param resourceName the path of the requested resource in the OpenCms VFS
1150     * @param req the current http request
1151     * @param res the current http response
1152     *
1153     * @return the requested resource read from the VFS
1154     *
1155     * @throws CmsException in case the requested file does not exist or the user has insufficient access permissions
1156     *
1157     * @see OpenCms#initResource(CmsObject, String, HttpServletRequest, HttpServletResponse)
1158     */

1159    protected CmsResource initResource(
1160        CmsObject cms,
1161        String JavaDoc resourceName,
1162        HttpServletRequest JavaDoc req,
1163        HttpServletResponse JavaDoc res) throws CmsException {
1164
1165        CmsResource resource = null;
1166        CmsException tmpException = null;
1167
1168        try {
1169            // try to read the requested resource
1170
resource = cms.readResource(resourceName);
1171            // resource exists, lets check if we have a file or a folder
1172
if (resource.isFolder()) {
1173                // the resource is a folder, check if PROPERTY_DEFAULT_FILE is set on folder
1174
try {
1175                    String JavaDoc defaultFileName = cms.readPropertyObject(
1176                        CmsResource.getFolderPath(cms.getSitePath(resource)),
1177                        CmsPropertyDefinition.PROPERTY_DEFAULT_FILE,
1178                        false).getValue();
1179                    if (defaultFileName != null) {
1180                        // property was set, so look up this file first
1181
String JavaDoc tmpResourceName = CmsResource.getFolderPath(cms.getSitePath(resource)) + defaultFileName;
1182                        resource = cms.readResource(tmpResourceName);
1183                        // no exception? so we have found the default file
1184
cms.getRequestContext().setUri(tmpResourceName);
1185                    }
1186                } catch (CmsSecurityException se) {
1187                    // permissions deny access to the resource
1188
throw se;
1189                } catch (CmsException e) {
1190                    // ignore all other exceptions and continue the lookup process
1191
}
1192                if (resource.isFolder()) {
1193                    // resource is (still) a folder, check default files specified in configuration
1194
for (int i = 0; i < m_defaultFiles.size(); i++) {
1195                        String JavaDoc tmpResourceName = CmsResource.getFolderPath(cms.getSitePath(resource))
1196                            + m_defaultFiles.get(i);
1197                        try {
1198                            resource = cms.readResource(tmpResourceName);
1199                            // no exception? So we have found the default file
1200
cms.getRequestContext().setUri(tmpResourceName);
1201                            // stop looking for default files
1202
break;
1203                        } catch (CmsSecurityException se) {
1204                            // permissions deny access to the resource
1205
throw se;
1206                        } catch (CmsException e) {
1207                            // ignore all other exceptions and continue the lookup process
1208
}
1209                    }
1210                }
1211            }
1212            if (resource.isFolder()) {
1213                // we only want files as a result for further processing
1214
resource = null;
1215            }
1216        } catch (CmsException e) {
1217            // file or folder with given name does not exist, store exception
1218
tmpException = e;
1219            resource = null;
1220        }
1221
1222        if (resource != null) {
1223            // test if this file is only available for internal access operations
1224
if ((resource.getFlags() & CmsResource.FLAG_INTERNAL) > 0) {
1225                throw new CmsException(Messages.get().container(
1226                    Messages.ERR_READ_INTERNAL_RESOURCE_1,
1227                    cms.getRequestContext().getUri()));
1228            }
1229
1230            // check online project
1231
if (cms.getRequestContext().currentProject().isOnlineProject()) {
1232                // check if resource is secure
1233
boolean secure = Boolean.valueOf(
1234                    cms.readPropertyObject(cms.getSitePath(resource), CmsPropertyDefinition.PROPERTY_SECURE, true).getValue()).booleanValue();
1235                if (secure) {
1236                    // resource is secure, check site config
1237
CmsSite site = CmsSiteManager.getCurrentSite(cms);
1238                    // check the secure url
1239
boolean usingSec = req.getRequestURL().toString().toUpperCase().startsWith(
1240                        site.getSecureUrl().toUpperCase());
1241                    if (site.isExclusiveUrl() && !usingSec) {
1242                        resource = null;
1243                        // secure resource without secure protocol, check error config
1244
if (site.isExclusiveError()) {
1245                            // trigger 404 error
1246
throw new CmsVfsResourceNotFoundException(Messages.get().container(
1247                                Messages.ERR_REQUEST_SECURE_RESOURCE_0));
1248                        } else {
1249                            // redirect
1250
String JavaDoc uri = req.getRequestURL().toString();
1251                            String JavaDoc target = site.getSecureUrl()
1252                                + uri.substring(uri.indexOf("/", uri.indexOf("//") + 2));
1253                            try {
1254                                res.sendRedirect(target);
1255                            } catch (Exception JavaDoc e) {
1256                                // ignore, but should never happen
1257
}
1258                        }
1259                    }
1260                }
1261            }
1262        }
1263
1264        // test if this file has to be checked or modified
1265
Iterator JavaDoc i = m_resourceInitHandlers.iterator();
1266        while (i.hasNext()) {
1267            try {
1268                resource = ((I_CmsResourceInit)i.next()).initResource(resource, cms, req, res);
1269                // the loop has to be interrupted when the exception is thrown!
1270
} catch (CmsResourceInitException e) {
1271                break;
1272            }
1273        }
1274
1275        // file is still null and not found exception was thrown, so throw original exception
1276
if (resource == null && tmpException != null) {
1277            throw tmpException;
1278        }
1279
1280        // return the resource read from the VFS
1281
return resource;
1282    }
1283
1284    /**
1285     * Initializes the system with the OpenCms servlet.<p>
1286     *
1287     * This is the final step that is called on the servlets "init()" method.
1288     * It registers the servlets request handler and also outputs the final
1289     * startup message. The servlet should auto-load since the &ltload-on-startup&gt;
1290     * parameter is set in the 'web.xml' by default.<p>
1291     *
1292     * @param servlet the OpenCms servlet
1293     */

1294    protected void initServlet(OpenCmsServlet servlet) {
1295
1296        synchronized (LOCK) {
1297            // add the servlets request handler
1298
addRequestHandler(servlet);
1299            // output the final 'startup is finished' message
1300
if (CmsLog.INIT.isInfoEnabled()) {
1301                CmsLog.INIT.info(Messages.get().getBundle().key(
1302                    Messages.INIT_SYSTEM_RUNNING_1,
1303                    CmsStringUtil.formatRuntime(getSystemInfo().getRuntime())));
1304                CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_LINE_0));
1305                CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
1306            }
1307        }
1308    }
1309
1310    /**
1311     * This method adds an Object to the OpenCms runtime properties.
1312     * The runtime properties can be used to store Objects that are shared
1313     * in the whole system.<p>
1314     *
1315     * @param key the key to add the Object with
1316     * @param value the value of the Object to add
1317     */

1318    protected void setRuntimeProperty(Object JavaDoc key, Object JavaDoc value) {
1319
1320        m_runtimeProperties.put(key, value);
1321    }
1322
1323    /**
1324     * Sets the session manager.<p>
1325     *
1326     * @param sessionManager the session manager to set
1327     */

1328    protected void setSessionManager(CmsSessionManager sessionManager) {
1329
1330        m_sessionManager = sessionManager;
1331    }
1332
1333    /**
1334     * Displays a resource from the OpenCms by writing the result to the provided
1335     * Servlet response output stream.<p>
1336     *
1337     * @param req the current servlet request
1338     * @param res the current servlet response
1339     */

1340    protected void showResource(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res) {
1341
1342        CmsObject cms = null;
1343        try {
1344            cms = initCmsObject(req, res);
1345            // user is initialized, now deliver the requested resource
1346
CmsResource resource = initResource(cms, cms.getRequestContext().getUri(), req, res);
1347            if (resource != null) {
1348                // a file was read, go on process it
1349
m_resourceManager.loadResource(cms, resource, req, res);
1350                updateUserSessionData(cms, req);
1351            }
1352
1353        } catch (Throwable JavaDoc t) {
1354            errorHandling(cms, req, res, t);
1355        }
1356    }
1357
1358    /**
1359     * Destroys this OpenCms instance, called if the servlet (or shell) is shut down.<p>
1360     */

1361    protected void shutDown() {
1362
1363        synchronized (LOCK) {
1364            if (getRunLevel() > OpenCms.RUNLEVEL_0_OFFLINE) {
1365
1366                System.err.println(Messages.get().getBundle().key(
1367                    Messages.LOG_SHUTDOWN_CONSOLE_NOTE_2,
1368                    getSystemInfo().getVersionName(),
1369                    getSystemInfo().getWebApplicationName()));
1370                if (CmsLog.INIT.isInfoEnabled()) {
1371                    CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
1372                    CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
1373                    CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_LINE_0));
1374                    CmsLog.INIT.info(Messages.get().getBundle().key(
1375                        Messages.INIT_SHUTDOWN_START_1,
1376                        getSystemInfo().getVersionName()));
1377                    CmsLog.INIT.info(Messages.get().getBundle().key(
1378                        Messages.INIT_CURRENT_RUNLEVEL_1,
1379                        new Integer JavaDoc(getRunLevel())));
1380                    CmsLog.INIT.info(Messages.get().getBundle().key(
1381                        Messages.INIT_SHUTDOWN_TIME_1,
1382                        new Date JavaDoc(System.currentTimeMillis())));
1383                }
1384
1385                // take the system offline
1386
setRunLevel(OpenCms.RUNLEVEL_0_OFFLINE);
1387
1388                if (LOG.isDebugEnabled()) {
1389                    // log exception to see which method did call the shutdown
1390
LOG.debug(Messages.get().getBundle().key(Messages.LOG_SHUTDOWN_TRACE_0), new Exception JavaDoc());
1391                }
1392
1393                try {
1394                    if (m_staticExportManager != null) {
1395                        m_staticExportManager.shutDown();
1396                    }
1397                } catch (Throwable JavaDoc e) {
1398                    CmsLog.INIT.error(Messages.get().getBundle().key(
1399                        Messages.LOG_ERROR_EXPORT_SHUTDOWN_1,
1400                        e.getMessage()), e);
1401                }
1402                try {
1403                    if (m_moduleManager != null) {
1404                        m_moduleManager.shutDown();
1405                    }
1406                } catch (Throwable JavaDoc e) {
1407                    CmsLog.INIT.error(Messages.get().getBundle().key(
1408                        Messages.LOG_ERROR_MODULE_SHUTDOWN_1,
1409                        e.getMessage()), e);
1410                }
1411                try {
1412                    if (m_scheduleManager != null) {
1413                        m_scheduleManager.shutDown();
1414                    }
1415                } catch (Throwable JavaDoc e) {
1416                    CmsLog.INIT.error(Messages.get().getBundle().key(
1417                        Messages.LOG_ERROR_SCHEDULE_SHUTDOWN_1,
1418                        e.getMessage()), e);
1419                }
1420                try {
1421                    if (m_resourceManager != null) {
1422                        m_resourceManager.shutDown();
1423                    }
1424                } catch (Throwable JavaDoc e) {
1425                    CmsLog.INIT.error(Messages.get().getBundle().key(
1426                        Messages.LOG_ERROR_RESOURCE_SHUTDOWN_1,
1427                        e.getMessage()), e);
1428                }
1429                try {
1430                    if (m_securityManager != null) {
1431                        m_securityManager.destroy();
1432                    }
1433                } catch (Throwable JavaDoc e) {
1434                    CmsLog.INIT.error(Messages.get().getBundle().key(
1435                        Messages.LOG_ERROR_SECURITY_SHUTDOWN_1,
1436                        e.getMessage()), e);
1437                }
1438                try {
1439                    if (m_threadStore != null) {
1440                        m_threadStore.shutDown();
1441                    }
1442                } catch (Throwable JavaDoc e) {
1443                    CmsLog.INIT.error(Messages.get().getBundle().key(
1444                        Messages.LOG_ERROR_THREAD_SHUTDOWN_1,
1445                        e.getMessage()), e);
1446                }
1447                String JavaDoc runtime = CmsStringUtil.formatRuntime(getSystemInfo().getRuntime());
1448                if (CmsLog.INIT.isInfoEnabled()) {
1449                    CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_OPENCMS_STOPPED_1, runtime));
1450                    CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_LINE_0));
1451                    CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
1452                    CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
1453                }
1454                System.err.println(Messages.get().getBundle().key(Messages.LOG_CONSOLE_TOTAL_RUNTIME_1, runtime));
1455
1456            }
1457            m_instance = null;
1458        }
1459    }
1460
1461    /**
1462     * Upgrades to runlevel {@link OpenCms#RUNLEVEL_3_SHELL_ACCESS},
1463     * this is shell access to the database but no Servlet context.<p>
1464     *
1465     * To upgrade the runlevel, the system must be in runlevel {@link OpenCms#RUNLEVEL_1_CORE_OBJECT},
1466     * otherwise an exception is thrown.<p>
1467     *
1468     * @param configuration the configuration
1469     * @throws CmsInitException in case OpenCms can not be initialized
1470     * @return the initialized OpenCmsCore
1471     */

1472    protected OpenCmsCore upgradeRunlevel(ExtendedProperties configuration) throws CmsInitException {
1473
1474        synchronized (LOCK) {
1475            if ((m_instance != null) && (getRunLevel() >= OpenCms.RUNLEVEL_2_INITIALIZING)) {
1476                // instance already in runlevel 3 or 4
1477
return m_instance;
1478            }
1479            if (getRunLevel() != OpenCms.RUNLEVEL_1_CORE_OBJECT) {
1480                CmsLog.INIT.error(Messages.get().getBundle().key(
1481                    Messages.LOG_WRONG_INIT_SEQUENCE_2,
1482                    new Integer JavaDoc(3),
1483                    new Integer JavaDoc(getRunLevel())));
1484                return m_instance;
1485            }
1486
1487            // set the runlevel to "initializing OpenCms"
1488
setRunLevel(OpenCms.RUNLEVEL_2_INITIALIZING);
1489            // initialize the configuration
1490
m_instance.initConfiguration(configuration);
1491            // upgrade the runlevel - OpenCms shell is available
1492
setRunLevel(OpenCms.RUNLEVEL_3_SHELL_ACCESS);
1493
1494            return m_instance;
1495        }
1496    }
1497
1498    /**
1499     * Upgrades to runlevel {@link OpenCms#RUNLEVEL_4_SERVLET_ACCESS},
1500     * this is the final runlevel with an initialized database and Servlet context.<p>
1501     *
1502     * To upgrade the runlevel, the system must be in runlevel {@link OpenCms#RUNLEVEL_1_CORE_OBJECT},
1503     * otherwise an exception is thrown.<p>
1504     *
1505     * @param context the current servlet context
1506     * @throws CmsInitException in case OpenCms can not be initialized
1507     * @return the initialized OpenCmsCore
1508     */

1509    protected OpenCmsCore upgradeRunlevel(ServletContext JavaDoc context) throws CmsInitException {
1510
1511        synchronized (LOCK) {
1512            if ((m_instance != null) && (getRunLevel() >= OpenCms.RUNLEVEL_4_SERVLET_ACCESS)) {
1513                // instance already in runlevel 5 or 6
1514
return m_instance;
1515            }
1516            if (getRunLevel() != OpenCms.RUNLEVEL_1_CORE_OBJECT) {
1517                CmsLog.INIT.error(Messages.get().getBundle().key(
1518                    Messages.LOG_WRONG_INIT_SEQUENCE_2,
1519                    new Integer JavaDoc(4),
1520                    new Integer JavaDoc(getRunLevel())));
1521                return m_instance;
1522            }
1523
1524            // set the runlevel to "initializing OpenCms"
1525
setRunLevel(OpenCms.RUNLEVEL_2_INITIALIZING);
1526            // initialize the servlet context
1527
m_instance.initContext(context);
1528            // initialization successfully finished - OpenCms servlet is online
1529
// the runlevel will change from 2 directly to 4, this is on purpose
1530
setRunLevel(OpenCms.RUNLEVEL_4_SERVLET_ACCESS);
1531
1532            return m_instance;
1533        }
1534    }
1535
1536    /**
1537     * Writes the XML configuration for the provided configuration class.<p>
1538     *
1539     * @param clazz the configuration class to write the XML for
1540     */

1541    protected void writeConfiguration(Class JavaDoc clazz) {
1542
1543        // exception handling is provided here to ensure identical log messages
1544
try {
1545            m_configurationManager.writeConfiguration(clazz);
1546        } catch (IOException JavaDoc e) {
1547            CmsLog.getLog(CmsConfigurationManager.class).error(
1548                Messages.get().getBundle().key(Messages.LOG_ERROR_WRITING_CONFIG_1, clazz.getName()),
1549                e);
1550        } catch (CmsConfigurationException e) {
1551            CmsLog.getLog(CmsConfigurationManager.class).error(
1552                Messages.get().getBundle().key(Messages.LOG_ERROR_WRITING_CONFIG_1, clazz.getName()),
1553                e);
1554        }
1555    }
1556
1557    /**
1558     * Adds the given set of export points to the list of all configured export points.<p>
1559     *
1560     * @param exportPoints the export points to add
1561     */

1562    private void addExportPoints(Set JavaDoc exportPoints) {
1563
1564        // create a new immutable set of export points
1565
HashSet JavaDoc newSet = new HashSet JavaDoc(m_exportPoints.size() + exportPoints.size());
1566        newSet.addAll(exportPoints);
1567        newSet.addAll(m_exportPoints);
1568        m_exportPoints = Collections.unmodifiableSet(newSet);
1569    }
1570
1571    /**
1572     * Checks if the current request contains http basic authentication information in
1573     * the headers, if so tries to log in the user identified.<p>
1574     *
1575     * @param cms the current cms context
1576     * @param req the current http request
1577     * @param res the current http response
1578     * @throws IOException in case of errors reading from the streams
1579     */

1580    private void checkBasicAuthorization(CmsObject cms, HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res)
1581    throws IOException JavaDoc {
1582
1583        // no user identified from the session and basic authentication is enabled
1584
String JavaDoc auth = req.getHeader("Authorization");
1585
1586        // user is authenticated, check password
1587
if (auth != null) {
1588
1589            // only do basic authentification
1590
if (auth.toUpperCase().startsWith("BASIC ")) {
1591
1592                // get encoded user and password, following after "BASIC "
1593
String JavaDoc base64Token = auth.substring(6);
1594
1595                // decode it, using base 64 decoder
1596
String JavaDoc token = new String JavaDoc(Base64.decodeBase64(base64Token.getBytes()));
1597                String JavaDoc username = null;
1598                String JavaDoc password = null;
1599                int pos = token.indexOf(":");
1600                if (pos != -1) {
1601                    username = token.substring(0, pos);
1602                    password = token.substring(pos + 1);
1603                }
1604                // authentication in the DB
1605
try {
1606                    try {
1607                        // try to login as a user first ...
1608
cms.loginUser(username, password);
1609                    } catch (CmsException exc) {
1610                        // login as user failed, try as webuser ...
1611
cms.loginWebUser(username, password);
1612                    }
1613                    // authentification was successful create a session
1614
req.getSession(true);
1615                } catch (CmsException e) {
1616                    // authentification failed, so display a login screen
1617
requestAuthorization(req, res);
1618                }
1619            }
1620        }
1621    }
1622
1623    /**
1624     * Generates a formated exception output.<p>
1625     *
1626     * Because the exception could be thrown while accessing the system files,
1627     * the complete HTML code must be added here!<p>
1628     *
1629     * @param t the caught Exception
1630     * @param request the servlet request
1631     * @param cms the CmsObject
1632     * @return String containing the HTML code of the error message
1633     */

1634    private String JavaDoc createErrorBox(Throwable JavaDoc t, HttpServletRequest JavaDoc request, CmsObject cms) {
1635
1636        String JavaDoc errorUri = CmsFlexController.getThrowableResourceUri(request);
1637        if (errorUri == null) {
1638            errorUri = cms.getRequestContext().getUri();
1639        }
1640        // try to get the exception root cause
1641
Throwable JavaDoc cause = CmsFlexController.getThrowable(request);
1642        if (cause == null) {
1643            cause = t;
1644        }
1645        CmsErrorBean errorBean = new CmsErrorBean(cms, cause);
1646        errorBean.setParamAction(errorUri);
1647        return errorBean.toHtml();
1648    }
1649
1650    /**
1651     * This method performs the error handling for OpenCms.<p>
1652     *
1653     * @param cms the current cms context, might be null !
1654     * @param req the client request
1655     * @param res the client response
1656     * @param t the exception that occured
1657     */

1658    private void errorHandling(CmsObject cms, HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res, Throwable JavaDoc t) {
1659
1660        // remove the controller attribute from the request
1661
CmsFlexController.removeController(req);
1662
1663        boolean canWrite = !res.isCommitted() && !res.containsHeader("Location");
1664        int status = -1;
1665        boolean isNotGuest = false;
1666
1667        if (t instanceof ServletException JavaDoc) {
1668            ServletException JavaDoc s = (ServletException JavaDoc)t;
1669            if (s.getRootCause() != null) {
1670                t = s.getRootCause();
1671            }
1672        } else if (t instanceof CmsSecurityException) {
1673            // access error - display login dialog
1674
if (canWrite) {
1675                try {
1676                    requestAuthorization(req, res);
1677                } catch (IOException JavaDoc ioe) {
1678                    // there is nothing we can do about this
1679
}
1680                return;
1681            }
1682        } else if (t instanceof CmsDbEntryNotFoundException) {
1683            // user or group does not exist
1684
status = HttpServletResponse.SC_SERVICE_UNAVAILABLE;
1685            isNotGuest = true;
1686        } else if (t instanceof CmsVfsResourceNotFoundException) {
1687            // file not found - display 404 error.
1688
status = HttpServletResponse.SC_NOT_FOUND;
1689        } else if (t instanceof CmsException) {
1690            if (t.getCause() != null) {
1691                t = t.getCause();
1692            }
1693        }
1694
1695        if (status < 1) {
1696            // error code not set - set "internal server error" (500)
1697
status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
1698        }
1699        res.setStatus(status);
1700
1701        try {
1702            isNotGuest = isNotGuest
1703                || (cms != null
1704                    && cms.getRequestContext().currentUser() != null
1705                    && (!OpenCms.getDefaultUsers().getUserGuest().equals(
1706                        cms.getRequestContext().currentUser().getName())) && ((cms.userInGroup(
1707                    cms.getRequestContext().currentUser().getName(),
1708                    OpenCms.getDefaultUsers().getGroupUsers()))
1709                    || (cms.userInGroup(
1710                        cms.getRequestContext().currentUser().getName(),
1711                        OpenCms.getDefaultUsers().getGroupProjectmanagers())) || (cms.userInGroup(
1712                    cms.getRequestContext().currentUser().getName(),
1713                    OpenCms.getDefaultUsers().getGroupAdministrators()))));
1714        } catch (CmsException e) {
1715            // result is false
1716
}
1717
1718        if (canWrite) {
1719            res.setContentType("text/html");
1720            CmsRequestUtil.setNoCacheHeaders(res);
1721            if (isNotGuest && cms != null && !cms.getRequestContext().currentProject().isOnlineProject()) {
1722                try {
1723                    res.setStatus(HttpServletResponse.SC_OK);
1724                    res.getWriter().print(createErrorBox(t, req, cms));
1725                } catch (IOException JavaDoc e) {
1726                    // can be ignored
1727
}
1728            } else {
1729                try {
1730                    res.sendError(status, t.toString());
1731                } catch (IOException JavaDoc e) {
1732                    // can be ignored
1733
}
1734            }
1735        }
1736    }
1737
1738    /**
1739     * Initializes a CmsObject with the given context information.<p>
1740     *
1741     * @param contextInfo the information for the CmsObject context to create
1742     *
1743     * @return the initialized CmsObject
1744     *
1745     * @throws CmsException if something goes wrong
1746     */

1747    private CmsObject initCmsObject(CmsContextInfo contextInfo) throws CmsException {
1748
1749        CmsUser user = contextInfo.getUser();
1750        if (user == null) {
1751            user = m_securityManager.readUser(contextInfo.getUserName());
1752        }
1753
1754        CmsProject project = contextInfo.getProject();
1755        if (project == null) {
1756            project = m_securityManager.readProject(contextInfo.getProjectName());
1757        }
1758
1759        // first create the request context
1760
CmsRequestContext context = new CmsRequestContext(
1761            user,
1762            project,
1763            contextInfo.getRequestedUri(),
1764            contextInfo.getSiteRoot(),
1765            contextInfo.getLocale(),
1766            contextInfo.getEncoding(),
1767            contextInfo.getRemoteAddr(),
1768            m_resourceManager.getFolderTranslator(),
1769            m_resourceManager.getFileTranslator());
1770
1771        // now initialize and return the CmsObject
1772
CmsObject cms = new CmsObject(m_securityManager, context);
1773        return cms;
1774    }
1775
1776    /**
1777     * This method handled the user authentification for each request sent to the
1778     * OpenCms. <p>
1779     *
1780     * User authentification is done in three steps:
1781     * <ol>
1782     * <li> Session authentification: OpenCms stores information of all authentificated
1783     * users in an internal storage based on the users session.</li>
1784     * <li> HTTP authentification: If the session authentification fails, it is checked if the current
1785     * user is providing data for HTTP BASIC authentification. If this check is positive, the user
1786     * is tried to log in with this data, and on success a session is generated.</li>
1787     * <li> Default user: When both authentification methods fail, the user is
1788     * set to the default (Guest) user. </li>
1789     * </ol>
1790     *
1791     * @param req the current http request
1792     * @param res the current http response
1793     * @return the initialized cms context
1794     * @throws IOException if user authentication fails
1795     * @throws CmsException in case something goes wrong
1796     */

1797    private CmsObject initCmsObject(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res) throws IOException JavaDoc, CmsException {
1798
1799        CmsObject cms;
1800
1801        // try to get the current session
1802
HttpSession JavaDoc session = req.getSession(false);
1803        String JavaDoc sessionId;
1804
1805        // check if there is user data already stored in the session manager
1806
if (session != null) {
1807            // session exists, try to reuse the user from the session
1808
sessionId = session.getId();
1809        } else {
1810            // special case for acessing a session from "outside" requests (e.g. upload applet)
1811
sessionId = req.getHeader(CmsRequestUtil.HEADER_JSESSIONID);
1812        }
1813        CmsSessionInfo sessionInfo = null;
1814        if (sessionId != null) {
1815            sessionInfo = m_sessionManager.getSessionInfo(sessionId);
1816        }
1817
1818        // initialize the requested site root
1819
CmsSite site = getSiteManager().matchRequest(req);
1820
1821        if (sessionInfo != null) {
1822            // a user name is found in the session manager, reuse this user information
1823
int project = sessionInfo.getProject();
1824
1825            // initialize site root from request
1826
String JavaDoc siteroot = null;
1827            // a dedicated workplace site is configured
1828
if ((getSiteManager().getWorkplaceSiteMatcher().equals(site.getSiteMatcher()))) {
1829                // if no dedicated workplace site is configured,
1830
// or for the dedicated workplace site, use the site root from the session attribute
1831
siteroot = sessionInfo.getSiteRoot();
1832            }
1833            if (siteroot == null) {
1834                siteroot = site.getSiteRoot();
1835            }
1836            cms = initCmsObject(req, sessionInfo.getUser().getName(), siteroot, project);
1837        } else {
1838            // no user name found in session or no session, login the user as guest user
1839
cms = initCmsObject(
1840                req,
1841                OpenCms.getDefaultUsers().getUserGuest(),
1842                site.getSiteRoot(),
1843                CmsProject.ONLINE_PROJECT_ID);
1844            // check if "basic" authentification data is provided
1845
checkBasicAuthorization(cms, req, res);
1846        }
1847
1848        // return the initialized cms user context object
1849
return cms;
1850    }
1851
1852    /**
1853     * Returns an initialized CmsObject with the given users permissions.<p>
1854     *
1855     * In case the password is <code>null</code>, or the user is the <code>Guest</code> user,
1856     * no password check is done. Therefore you can initialize all users without knowing their passwords
1857     * by just supplying <code>null</code> as password. This is intended only for
1858     * internal operation in the core.<p>
1859     *
1860     * @param req the current request
1861     * @param res the current response
1862     * @param user the user to initialize the CmsObject with
1863     * @param password the password of the user
1864     * @return a cms context that has been initialized with "Guest" permissions
1865     * @throws CmsException in case the CmsObject could not be initialized
1866     */

1867    private CmsObject initCmsObject(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res, String JavaDoc user, String JavaDoc password)
1868    throws CmsException {
1869
1870        String JavaDoc siteroot = null;
1871        // gather information from request / response if provided
1872
if ((req != null) && (res != null)) {
1873            siteroot = OpenCms.getSiteManager().matchRequest(req).getSiteRoot();
1874        }
1875        // initialize the user
1876
if (user == null) {
1877            user = getDefaultUsers().getUserGuest();
1878        }
1879        if (siteroot == null) {
1880            siteroot = "/";
1881        }
1882        CmsObject cms = initCmsObject(req, user, siteroot, CmsProject.ONLINE_PROJECT_ID);
1883        // login the user if different from Guest and password was provided
1884
if ((password != null) && !getDefaultUsers().getUserGuest().equals(user)) {
1885            cms.loginUser(user, password, CmsContextInfo.LOCALHOST);
1886        }
1887        return cms;
1888    }
1889
1890    /**
1891     * Inits a CmsObject with the given users information.<p>
1892     *
1893     * @param req the current http request (or null)
1894     * @param userName the name of the user to init
1895     * @param currentSite the users current site
1896     * @param projectId the id of the users current project
1897     * @return the initialized CmsObject
1898     * @throws CmsException in case something goes wrong
1899     */

1900    private CmsObject initCmsObject(HttpServletRequest JavaDoc req, String JavaDoc userName, String JavaDoc currentSite, int projectId)
1901    throws CmsException {
1902
1903        CmsUser user = m_securityManager.readUser(userName);
1904        CmsProject project = null;
1905        try {
1906            project = m_securityManager.readProject(projectId);
1907        } catch (CmsDbEntryNotFoundException e) {
1908            // project not found, switch to online project
1909
project = m_securityManager.readProject(CmsProject.ONLINE_PROJECT_ID);
1910        }
1911
1912        // get requested resource uri
1913
String JavaDoc requestedResource = null;
1914        if (req != null) {
1915            requestedResource = req.getPathInfo();
1916        }
1917        if (requestedResource == null) {
1918            // path info can be null, so no 'else'
1919
requestedResource = "/";
1920        }
1921
1922        // get remote IP address
1923
String JavaDoc remoteAddr;
1924        if (req != null) {
1925            remoteAddr = req.getHeader(CmsRequestUtil.HEADER_X_FORWARDED_FOR);
1926            if (remoteAddr == null) {
1927                remoteAddr = req.getRemoteAddr();
1928            }
1929        } else {
1930            remoteAddr = CmsContextInfo.LOCALHOST;
1931        }
1932
1933        // get locale and encoding
1934
CmsI18nInfo i18nInfo;
1935        if (m_localeManager.isInitialized()) {
1936            // locale manager is initialized
1937
// resolve locale and encoding
1938
String JavaDoc resourceName;
1939            if (requestedResource.startsWith(CmsWorkplace.VFS_PATH_SYSTEM)) {
1940                // add site root only if resource name does not start with "/system"
1941
resourceName = requestedResource;
1942            } else {
1943                resourceName = currentSite.concat(requestedResource);
1944            }
1945            i18nInfo = m_localeManager.getI18nInfo(req, user, project, resourceName);
1946        } else {
1947            // locale manager not initialized, this will be true _only_ during system startup
1948
// the values set does not matter, no locale information form VFS is used on system startup
1949
// this is just to protect against null pointer exceptions
1950
i18nInfo = new CmsI18nInfo(Locale.ENGLISH, getSystemInfo().getDefaultEncoding());
1951        }
1952
1953        // decode the requested resource, always using UTF-8
1954
requestedResource = CmsEncoder.decode(requestedResource);
1955
1956        // initialize the context info
1957
CmsContextInfo contextInfo = new CmsContextInfo(
1958            user,
1959            project,
1960            requestedResource,
1961            currentSite,
1962            i18nInfo.getLocale(),
1963            i18nInfo.getEncoding(),
1964            remoteAddr);
1965
1966        // now generate and return the CmsObject
1967
return initCmsObject(contextInfo);
1968    }
1969
1970    /**
1971     * This method sends a request to the client to display a login form,
1972     * it is needed for HTTP-Authentification.<p>
1973     *
1974     * @param req the client request
1975     * @param res the response
1976     * @throws IOException if something goes wrong
1977     */

1978    private void requestAuthorization(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res) throws IOException JavaDoc {
1979
1980        // this will create an admin user with the "right" site root already set
1981
CmsObject adminCms;
1982        try {
1983            adminCms = initCmsObject(req, res, getDefaultUsers().getUserAdmin(), null);
1984        } catch (CmsException e) {
1985            // this should never happen, if it does we can't continue
1986
throw new IOException JavaDoc(Messages.get().getBundle().key(
1987                Messages.ERR_INVALID_INIT_USER_2,
1988                getDefaultUsers().getUserAdmin(),
1989                null));
1990        }
1991        // get the requested resource
1992
String JavaDoc path = adminCms.getRequestContext().getUri();
1993        CmsProperty propertyLoginForm = null;
1994        String JavaDoc redirectURL = null;
1995        try {
1996            propertyLoginForm = adminCms.readPropertyObject(path, CmsPropertyDefinition.PROPERTY_LOGIN_FORM, true);
1997        } catch (Throwable JavaDoc t) {
1998            if (LOG.isWarnEnabled()) {
1999                LOG.warn(Messages.get().getBundle().key(
2000                    Messages.LOG_ERROR_READING_AUTH_PROP_2,
2001                    CmsPropertyDefinition.PROPERTY_LOGIN_FORM,
2002                    path), t);
2003            }
2004        }
2005
2006        CmsHttpAuthenticationSettings httpAuthenticationSettings = getSystemInfo().getHttpAuthenticationSettings();
2007        String JavaDoc pathWithParams = CmsRequestUtil.encodeParamsWithUri(path, req);
2008        if (propertyLoginForm != null
2009            && propertyLoginForm != CmsProperty.getNullProperty()
2010            && CmsStringUtil.isNotEmpty(propertyLoginForm.getValue())) {
2011            // login form property value was found
2012
// build a redirect URL using the value of the property
2013
// "__loginform" is a dummy request parameter that could be used in a JSP template to trigger
2014
// if the template should display a login formular or not
2015
redirectURL = propertyLoginForm.getValue()
2016                + "?__loginform=true&"
2017                + CmsWorkplaceManager.PARAM_LOGIN_REQUESTED_RESOURCE
2018                + "="
2019                + pathWithParams;
2020        } else if (!httpAuthenticationSettings.useBrowserBasedHttpAuthentication()
2021            && CmsStringUtil.isNotEmpty(httpAuthenticationSettings.getFormBasedHttpAuthenticationUri())) {
2022            // login form property value not set, but form login set in configuration
2023
// build a redirect URL to the default login form URI configured in opencms.properties
2024
redirectURL = httpAuthenticationSettings.getFormBasedHttpAuthenticationUri()
2025                + "?"
2026                + CmsWorkplaceManager.PARAM_LOGIN_REQUESTED_RESOURCE
2027                + "="
2028                + pathWithParams;
2029        }
2030
2031        if (redirectURL == null) {
2032            // HTTP basic authentication is used
2033
res.setHeader(CmsRequestUtil.HEADER_WWW_AUTHENTICATE, "BASIC realm=\""
2034                + getSystemInfo().getOpenCmsContext()
2035                + "\"");
2036            res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
2037        } else {
2038            // resolve the login form link using the link manager
2039
redirectURL = m_linkManager.substituteLink(adminCms, redirectURL, null, true);
2040            if (LOG.isDebugEnabled()) {
2041                LOG.debug(Messages.get().getBundle().key(Messages.LOG_AUTHENTICATE_PROPERTY_2, redirectURL, path));
2042            }
2043            // finally redirect to the login form
2044
res.sendRedirect(redirectURL);
2045        }
2046    }
2047
2048    /**
2049     * Sets the init level of this OpenCmsCore object instance.<p>
2050     *
2051     * For a detailed description about the possible run levels,
2052     * please see {@link OpenCms#getRunLevel()}.<p>
2053     *
2054     * @param level the level to set
2055     */

2056    private void setRunLevel(int level) {
2057
2058        if (m_instance != null) {
2059            if (m_instance.m_runLevel >= OpenCms.RUNLEVEL_1_CORE_OBJECT) {
2060                // otherwise the log is not available
2061
if (CmsLog.INIT.isInfoEnabled()) {
2062                    CmsLog.INIT.info(Messages.get().getBundle().key(
2063                        Messages.INIT_RUNLEVEL_CHANGE_2,
2064                        new Integer JavaDoc(m_instance.m_runLevel),
2065                        new Integer JavaDoc(level)));
2066                }
2067            }
2068            m_instance.m_runLevel = level;
2069        }
2070    }
2071
2072    /**
2073     * Updates the the user data stored in the CmsSessionInfoManager after the requested document
2074     * is processed.<p>
2075     *
2076     * This is required if the user data (current group or project) was changed in
2077     * the requested document.<p>
2078     *
2079     * The user data is only updated if the user was authenticated to the system.
2080     *
2081     * @param cms the current CmsObject initialized with the user data
2082     * @param req the current request
2083     */

2084    private void updateUserSessionData(CmsObject cms, HttpServletRequest JavaDoc req) {
2085
2086        if (!cms.getRequestContext().isUpdateSessionEnabled()) {
2087            // this request must not update the user session info
2088
// this is true for long running "thread" requests, e.g. during project publish
2089
return;
2090        }
2091        // get the session if it is available
2092
HttpSession JavaDoc session = req.getSession(false);
2093        // if the user was authenticated via sessions,
2094
// update the information in the session info manager
2095
if (session != null) {
2096            if (!cms.getRequestContext().currentUser().isGuestUser()) {
2097                // get the session info object for the user
2098
CmsSessionInfo sessionInfo = m_sessionManager.getSessionInfo(session.getId());
2099                if (sessionInfo != null) {
2100                    // update the users session information
2101
sessionInfo.update(cms.getRequestContext());
2102                } else {
2103                    // create a new session info for the user
2104
sessionInfo = new CmsSessionInfo(
2105                        cms.getRequestContext(),
2106                        session.getId(),
2107                        session.getMaxInactiveInterval());
2108                    // update the session info user data
2109
m_sessionManager.addSessionInfo(sessionInfo);
2110                }
2111            }
2112        }
2113    }
2114}
Popular Tags