Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Source code: com/opencms/core/OpenCmsHttpServlet.java


1   /*
2   * File   : $Source: /usr/local/cvs/opencms/src/com/opencms/core/Attic/OpenCmsHttpServlet.java,v $
3   * Date   : $Date: 2003/04/25 07:40:20 $
4   * Version: $Revision: 1.47 $
5   *
6   * This library is part of OpenCms -
7   * the Open Source Content Mananagement System
8   *
9   * Copyright (C) 2001  The OpenCms Group
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 OpenCms, please see the
22  * OpenCms Website: http://www.opencms.org
23  *
24  * You should have received a copy of the GNU Lesser General Public
25  * License along with this library; if not, write to the Free Software
26  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27  */
28  
29  package com.opencms.core;
30  
31  import com.opencms.boot.CmsBase;
32  import com.opencms.boot.CmsMain;
33  import com.opencms.boot.I_CmsLogChannels;
34  import com.opencms.file.CmsFile;
35  import com.opencms.file.CmsObject;
36  import com.opencms.util.Utils;
37  
38  import java.io.IOException;
39  import java.util.Date;
40  import java.util.Hashtable;
41  import java.util.Properties;
42  import java.util.StringTokenizer;
43  
44  import javax.servlet.ServletConfig;
45  import javax.servlet.ServletException;
46  import javax.servlet.http.HttpServlet;
47  import javax.servlet.http.HttpServletRequest;
48  import javax.servlet.http.HttpServletResponse;
49  import javax.servlet.http.HttpSession;
50  
51  import source.org.apache.java.util.Configurations;
52  import source.org.apache.java.util.ExtendedProperties;
53  
54  /**
55   * This the main servlet of the OpenCms system.<p>
56   * 
57   * From here, all other operations are invoked.
58   * Any incoming request is handled in multiple steps:
59   * 
60   * <ol><li>The requesting user is authenticated and a CmsObject with the user information
61   * is created. The CmsObject is used to access all functions of OpenCms, limited by
62   * the authenticated users permissions. If the user is not identified, it is set to the default (guest)
63   * user.</li>
64   * 
65   * <li>The requested document is loaded into OpenCms and depending on its type 
66   * (and the users persmissions to display or modify it), 
67   * it is send to one of the OpenCms launchers do be processed.</li>
68   * 
69   * <li>
70   * The loaded launcher will then decide what to do with the contents of the 
71   * requested document. In case of an XMLTemplate the template mechanism will 
72   * be started, in case of a JSP the JSP handling mechanism is invoked, 
73   * in case of an image (or other static file) this will simply be returned etc.
74   * </li></ol>
75   *
76   * @author Michael Emmerich
77   * @author Alexander Kandzior (a.kandzior@alkacon.com)
78   * 
79   * @version $Revision: 1.47 $ $Date: 2003/04/25 07:40:20 $
80   */
81  public class OpenCmsHttpServlet extends HttpServlet implements I_CmsConstants,I_CmsLogChannels {
82  
83      /**
84       * The name of the redirect entry in the configuration file.
85       */
86      static final String C_PROPERTY_REDIRECT = "redirect";
87  
88      /**
89       * The name of the redirect location entry in the configuration file.
90       */
91      static final String C_PROPERTY_REDIRECTLOCATION = "redirectlocation";
92  
93      /**
94       * The configuration for the OpenCms servlet.
95       */
96      private Configurations m_configurations;
97  
98      /**
99       * The session storage for all active users.
100      */
101     private CmsCoreSession m_sessionStorage;
102 
103     /**
104      * The reference to the OpenCms system.
105      */
106     private OpenCms m_opencms;
107 
108     /**
109      * Storage for the clusterurl.
110      */
111     private String m_clusterurl = null;
112     
113     /**
114      * Flag to indicate if basic or form based authentication is used.
115      */
116     private boolean m_UseBasicAuthentication;
117     
118     /**
119      * URI of the authentication form (read from properties).
120      */
121     private String m_AuthenticationFormURI;
122     
123     /**
124      * Flag for debugging.
125      */
126     private static final boolean DEBUG = false;
127     
128     /**
129      * Prefix for error messages for initialization errors.  
130      */
131     private static final String C_ERRORMSG = "OpenCms initialization error!\n\n";
132 
133     /**
134      * Prints the OpenCms copyright information to all log-files.<p>
135      */
136     private void printCopyrightInformation() {
137         String copy[] = C_COPYRIGHT;
138 
139         // log to error-stream
140         System.err.println("\n\nStarting OpenCms, version " + A_OpenCms.getVersionName());
141         for(int i = 0;i < copy.length;i++) {
142             System.err.println(copy[i]);
143         }
144 
145         // log with opencms-logger
146         if(C_LOGGING && A_OpenCms.isLogging(C_OPENCMS_INIT)) {
147             A_OpenCms.log(C_OPENCMS_INIT, ". OpenCms version " + A_OpenCms.getVersionName());
148             for(int i = 0;i < copy.length;i++) {
149                 A_OpenCms.log(C_OPENCMS_INIT, ". " + copy[i]);
150             }
151         }
152     }   
153     
154     /**
155      * Throws a servlet exception that is also logged and written to the error output console.<p>
156      * 
157      * @param cause the original Exception
158      * @throws ServletException the <code>cause</code> parameter
159      */
160     private void throwInitException(ServletException cause) throws ServletException {
161         String message = cause.getMessage();
162         if (message == null) message = cause.toString();
163         System.err.println("\n--------------------\nCritical error during OpenCms servlet init phase:\n" + message);
164         System.err.println("Giving up, unable to start OpenCms.\n--------------------");        
165         if(C_LOGGING && A_OpenCms.isLogging(C_OPENCMS_CRITICAL)) {
166             A_OpenCms.log(C_OPENCMS_CRITICAL, message);
167         }         
168         throw cause;
169     }
170         
171     /**
172      * Initialization of the OpenCms servlet (overloaded Servlet API method).<p>
173      *
174      * The connection information for the database is read 
175      * from the <code>opencms.properties</code> configuration file and all 
176      * resource brokers are initialized via the initalizer, 
177      * which usually will be an instance of a <code>OpenCms</code> class.
178      *
179      * @param config configuration of OpenCms from <code>web.xml</code>
180      * @throws ServletException when sevlet initalization fails
181      */
182     public void init(ServletConfig config) throws ServletException {
183         super.init(config);
184         A_OpenCms.initVersion(this);
185         
186         // Check for OpenCms home (base) directory path
187         String base = config.getInitParameter("opencms.home");
188         if (DEBUG) System.err.println("BASE: " + config.getServletContext().getRealPath("/"));
189         if (DEBUG) System.err.println("BASE2: " + System.getProperty("user.dir"));
190         if(base == null || "".equals(base)) {
191             if (DEBUG) System.err.println("No OpenCms home folder given. Trying to guess...");
192             base = CmsMain.searchBaseFolder(config.getServletContext().getRealPath("/"));
193             if(base == null || "".equals(base)) {
194                 throwInitException(new ServletException(C_ERRORMSG + "OpenCms base folder could not be guessed. Please define init parameter \"opencms.home\" in servlet engine configuration.\n\n"));
195             }
196         }
197         base = CmsBase.setBasePath(base);        
198         
199         String logFile;
200         ExtendedProperties extendedProperties = null;
201         
202         // Collect the configurations        
203         try {
204             extendedProperties = new ExtendedProperties(CmsBase.getPropertiesPath(true));
205         }
206         catch(Exception e) {
207             throwInitException(new ServletException(C_ERRORMSG + "Trouble reading property file " + CmsBase.getPropertiesPath(true) + ".\n\n", e));
208         }
209         
210         // Change path to log file, if given path is not absolute
211         logFile = (String)extendedProperties.get("log.file");
212         if(logFile != null) {
213             extendedProperties.put("log.file", CmsBase.getAbsolutePath(logFile));
214         }
215 
216         // Create the configurations object
217         m_configurations = new Configurations(extendedProperties);        
218 
219         // Initialize the logging
220         A_OpenCms.initializeServletLogging(m_configurations);
221         if(C_LOGGING && A_OpenCms.isLogging(C_OPENCMS_INIT)) {
222             A_OpenCms.log(C_OPENCMS_INIT, ".");        
223             A_OpenCms.log(C_OPENCMS_INIT, ".");        
224             A_OpenCms.log(C_OPENCMS_INIT, ".");        
225             A_OpenCms.log(C_OPENCMS_INIT, ".");
226             printCopyrightInformation();       
227             A_OpenCms.log(C_OPENCMS_INIT, ".                      ...............................................................");        
228             A_OpenCms.log(C_OPENCMS_INIT, ". Startup time         : " + (new Date(System.currentTimeMillis())));        
229             A_OpenCms.log(C_OPENCMS_INIT, ". Servlet container    : " + config.getServletContext().getServerInfo());        
230             A_OpenCms.log(C_OPENCMS_INIT, ". OpenCms version      : " + A_OpenCms.getVersionName()); 
231             A_OpenCms.log(C_OPENCMS_INIT, ". OpenCms base path    : " + CmsBase.getBasePath());        
232             A_OpenCms.log(C_OPENCMS_INIT, ". OpenCms property file: " + CmsBase.getPropertiesPath(true));        
233             A_OpenCms.log(C_OPENCMS_INIT, ". OpenCms logfile      : " + CmsBase.getAbsolutePath(logFile));        
234         }
235         
236         // check cluster configuration
237         m_clusterurl = (String)m_configurations.getString(C_CLUSTERURL, "");
238         if((! "".equals(m_clusterurl)) && C_LOGGING && A_OpenCms.isLogging(C_OPENCMS_INIT)) A_OpenCms.log(C_OPENCMS_INIT, ". Clusterurl           : " + m_clusterurl);                
239 
240         try {
241             // create the OpenCms object
242             m_opencms = new OpenCms(m_configurations);
243         } catch (CmsException cmsex) {
244             if (cmsex.getType() == CmsException.C_RB_INIT_ERROR) {
245                 throwInitException(new ServletException(C_ERRORMSG + "Could not connect to the database. Is the database up and running?\n\n", cmsex));                
246             }
247         } catch(Exception exc) {
248             throwInitException(new ServletException(C_ERRORMSG + "Trouble creating the com.opencms.core.CmsObject. Please check the root cause for more information.\n\n", exc));
249         }
250 
251         // initalize the session storage
252         m_sessionStorage = new CmsCoreSession();
253         if(C_LOGGING && A_OpenCms.isLogging(C_OPENCMS_INIT)) A_OpenCms.log(C_OPENCMS_INIT, ". Session storage      : initialized");
254              
255         // check if basic or form based authentication should be used      
256         this.m_UseBasicAuthentication = m_configurations.getBoolean( "auth.basic", true );        
257         this.m_AuthenticationFormURI = m_configurations.getString( "auth.form_uri" , "/system/workplace/action/authenticate.html" );
258     }
259 
260     /**
261      * Destroys all running threads before closing the VM.
262      */
263     public void destroy() {
264         if(C_LOGGING && A_OpenCms.isLogging(C_OPENCMS_INIT)) {
265             A_OpenCms.log(C_OPENCMS_INIT, "[OpenCmsServlet] Performing shutdown ...");
266         }
267         try {
268             m_opencms.destroy();
269         }catch(CmsException e) {
270             if(C_LOGGING && A_OpenCms.isLogging(C_OPENCMS_CRITICAL)) {
271                 A_OpenCms.log(C_OPENCMS_CRITICAL, "[OpenCmsServlet]" + e.toString());
272             }
273         }
274         try{
275             Utils.getModulShutdownMethods(OpenCms.getRegistry());
276         }catch (CmsException e){
277             // log exception since we are about to shutdown anyway
278             if(C_LOGGING && A_OpenCms.isLogging(C_OPENCMS_CRITICAL)) {
279                 A_OpenCms.log(C_OPENCMS_CRITICAL, "[OpenCmsServlet] Module shutdown exception: " + e);
280             }
281         }
282         if(C_LOGGING && A_OpenCms.isLogging(C_OPENCMS_INIT)) {
283             A_OpenCms.log(C_OPENCMS_INIT, "[OpenCmsServlet] ... shutdown completed.");
284         }
285     }
286 
287     /**
288      * Method invoked on each HTML GET request.
289      * <p>
290      * (Overloaded Servlet API method, requesting a document).
291      * Reads the URI received from the client and invokes the appropiate action.
292      *
293      * @param req   The clints request.
294      * @param res   The servlets response.
295      * @throws ServletException if request fails
296      * @throws IOException if the user authentication fails
297      */
298     public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException {         
299         CmsObject cms = null;
300         CmsRequestHttpServlet cmsReq = new CmsRequestHttpServlet(req, m_opencms.getFileTranslator());
301         CmsResponseHttpServlet cmsRes = new CmsResponseHttpServlet(req, res, m_clusterurl);
302         try {
303             m_opencms.initStartupClasses(req, res);
304             cms = initUser(cmsReq, cmsRes);
305             // no redirect was done - deliver the ressource normally
306             CmsFile file = m_opencms.initResource(cms);
307             if(file != null) {
308                 // a file was read, go on process it
309                 m_opencms.setResponse(cms, file);
310                 m_opencms.showResource(cms, file);
311                 updateUser(cms, cmsReq);
312             }
313         }
314         catch(CmsException e) {
315             errorHandling(cms, cmsReq, cmsRes, e);
316         }
317     }
318 
319     /**
320      * Method invoked on each HTML POST request.
321      * <p>
322      * (Overloaded Servlet API method, posting a document)
323      * The OpenCmsMultipartRequest is invoked to upload a new document into OpenCms.
324      *
325      * @param req   The clints request.
326      * @param res   The servlets response.
327      * @throws ServletException Thrown if request fails.
328      * @throws IOException Thrown if user autherization fails.
329      */
330     public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException {            
331         doGet(req, res);
332     }
333 
334     /**
335      * Generates a formated exception output. <br>
336      * Because the exception could be thrown while accessing the system files,
337      * the complete HTML code must be added here!
338      * @param e The caught CmsException.
339      * @return String containing the HTML code of the error message.
340      */
341     private String createErrorBox(CmsException e, CmsObject cms) {
342         StringBuffer output = new StringBuffer();
343         output.append(this.getErrormsg("C_ERRORPART_1"));
344         output.append(cms.getRequestContext().getRequest().getWebAppUrl());
345         output.append(this.getErrormsg("C_ERRORPART_2"));
346         output.append("\n\n");
347         output.append(Utils.getStackTrace(e));
348         output.append("\n\n");
349         output.append(this.getErrormsg("C_ERRORPART_3"));
350         return output.toString();
351     }
352     
353     /**
354      * This method performs the error handling for the OpenCms.
355      * All CmsExetions throns in the OpenCms are forwared to this method and are
356      * processed here.
357      *
358      * @param cms The CmsObject
359      * @param cmsReq   The clints request.
360      * @param cmsRes   The servlets response.
361      * @param e The CmsException to be processed.
362      */
363     private void errorHandling(CmsObject cms, I_CmsRequest cmsReq, I_CmsResponse cmsRes, CmsException e) {
364         int errorType = e.getType();
365         HttpServletRequest req = (HttpServletRequest)cmsReq.getOriginalRequest();
366         HttpServletResponse res = (HttpServletResponse)cmsRes.getOriginalResponse();
367         boolean canWrite = ((!cmsRes.isRedirected()) && (!cmsRes.isOutputWritten()));
368         try {
369             switch(errorType) {
370 
371               // access denied error - display login dialog
372               case CmsException.C_ACCESS_DENIED:
373                   if(canWrite) {
374                     if(C_LOGGING && A_OpenCms.isLogging(C_OPENCMS_INFO)) {
375                         A_OpenCms.log(C_OPENCMS_INFO, "[OpenCmsServlet] Access denied. " + e.getMessage());
376                     }
377                     requestAuthorization(req, res);
378                   }
379 
380                   break;
381 
382               // file not found - display 404 error.
383               case CmsException.C_NOT_FOUND:
384                   if(canWrite) {
385                     res.setContentType("text/HTML");
386 
387                     //res.getWriter().print(createErrorBox(e));
388                     res.sendError(HttpServletResponse.SC_NOT_FOUND);
389                   }
390                   break;
391 
392               case CmsException.C_SERVICE_UNAVAILABLE:
393                   if(canWrite) {
394                     res.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.toString());
395                   }
396                   break;
397 
398               // https page and http request - display 404 error.
399               case CmsException.C_HTTPS_PAGE_ERROR:
400                   if(canWrite) {
401                     if(C_LOGGING && A_OpenCms.isLogging(C_OPENCMS_INFO)) {
402                         A_OpenCms.log(C_OPENCMS_INFO, "[OpenCmsServlet] Trying to get a http page with a https request. "+e.getMessage());
403                     }
404                     res.setContentType("text/HTML");
405                     res.sendError(HttpServletResponse.SC_NOT_FOUND);
406                   }
407                   break;
408 
409               // https request and http page - display 404 error.
410               case CmsException.C_HTTPS_REQUEST_ERROR:
411                     if(C_LOGGING && A_OpenCms.isLogging(C_OPENCMS_INFO)) {
412                         A_OpenCms.log(C_OPENCMS_INFO, "[OpenCmsServlet] Trying to get a https page with a http request. "+e.getMessage());
413                     }
414                   if(canWrite) {
415                     res.setContentType("text/HTML");
416                     res.sendError(HttpServletResponse.SC_NOT_FOUND);
417                   }
418                   break;
419 
420               default:
421                   if(canWrite) {
422                     // send errorbox, but only if the request was not redirected
423                     res.setContentType("text/HTML");
424 
425                     // set some HTTP headers preventing proxy servers from caching the error box
426                     res.setHeader("Cache-Control", "no-cache");
427                     res.setHeader("Pragma", "no-cache");
428                     res.getWriter().print(createErrorBox(e, cms));
429                   }
430             //res.sendError(res.SC_INTERNAL_SERVER_ERROR);
431             }
432         }
433         catch(IOException ex) {
434 
435         }
436     }
437 
438     /**
439      * This method handled the user authentification for each request sent to the
440      * OpenCms. <p>
441      *
442      * User authentification is done in three steps:
443      * <ul>
444      * <li> Session Authentification: OpenCms stores all active sessions of authentificated
445      * users in an internal storage. During the session authetification phase, it is checked
446      * if the session of the active user is stored there. </li>
447      * <li> HTTP Autheification: If session authentification fails, it is checked if the current
448      * user has loged in using HTTP authentification. If this check is positive, the user account is
449      * checked. </li>
450      * <li> Default user: When both authentification methods fail, the current user is
451      * set to the default (guest) user. </li>
452      * </ul>
453      *
454      * @param req   The clints request.
455      * @param res   The servlets response.
456      * @return The CmsObject
457      * @throws IOException Thrown if user autherization fails.
458      */
459     private CmsObject initUser(I_CmsRequest cmsReq, I_CmsResponse cmsRes) throws IOException {
460         HttpSession session;
461         String user = null;
462         String group = null;
463         Integer project = null;
464         String loginParameter;
465 
466         // get the original ServletRequest and response
467         HttpServletRequest req = (HttpServletRequest)cmsReq.getOriginalRequest();
468         HttpServletResponse res = (HttpServletResponse)cmsRes.getOriginalResponse();
469         CmsObject cms = new CmsObject();
470 
471         //set up the default Cms object
472         try {
473             m_opencms.initUser(cms, cmsReq, cmsRes, C_USER_GUEST, C_GROUP_GUEST, C_PROJECT_ONLINE_ID, m_sessionStorage);
474 
475             // check if a parameter "opencms=login" was included in the request.
476             // this is used to force the HTTP-Authentification to appear.
477             loginParameter = cmsReq.getParameter("opencms");
478             if(loginParameter != null) {
479                 // do only show the authentication box if user is not already
480                 // authenticated.
481                 if(req.getHeader("Authorization") == null) {
482                     if(loginParameter.equals("login")) {
483                         requestAuthorization(req, res);
484                     }
485                 }
486             }
487 
488             // check for the clearcache parameter
489             loginParameter = cmsReq.getParameter("_clearcache");
490             if(loginParameter != null) {
491                 cms.clearcache();
492             }
493 
494             // get the actual session
495             session = req.getSession(false);
496 
497             // there is no session
498             if((session == null)) {
499                 // was there an old session-id?
500                 String oldSessionId = req.getRequestedSessionId();
501                 if(oldSessionId != null) {
502 
503                     // yes - try to load that session
504                     Hashtable sessionData = null;
505                     try {
506                         sessionData = m_opencms.restoreSession(oldSessionId);
507                     }
508                     catch(CmsException exc) {
509                         if(C_LOGGING && A_OpenCms.isLogging(C_OPENCMS_INFO)) {
510                             A_OpenCms.log(C_OPENCMS_INFO, "[OpenCmsServlet] cannot restore session: " + com.opencms.util.Utils.getStackTrace(exc));
511                         }
512                     }
513 
514                     // can the session be restored?
515                     if(sessionData != null) {
516 
517                         // create a new session first
518                         session = req.getSession(true);
519                         m_sessionStorage.putUser(session.getId(), sessionData);
520 
521                         // restore the session-data
522                         session.setAttribute(C_SESSION_DATA, sessionData.get(C_SESSION_DATA));
523                     }
524                 }
525             }
526 
527             // there was a session returned, now check if this user is already authorized
528             if(session != null) {
529                 // get the username
530                 user = m_sessionStorage.getUserName(session.getId());
531                 //check if a user was returned, i.e. the user is authenticated
532                 if(user != null) {
533                     group = m_sessionStorage.getCurrentGroup(session.getId());
534                     project = m_sessionStorage.getCurrentProject(session.getId());
535                     m_opencms.initUser(cms, cmsReq, cmsRes, user, group, project.intValue(), m_sessionStorage);
536                 }
537             }
538             else {
539                 // there was either no session returned or this session was not
540                 // found in the CmsCoreSession storage
541                 String auth = req.getHeader("Authorization");
542 
543                 // User is authenticated, check password
544                 if(auth != null) {
545 
546                     // only do basic authentification
547                     if(auth.toUpperCase().startsWith("BASIC ")) {
548 
549                         // Get encoded user and password, following after "BASIC "
550                         String userpassEncoded = auth.substring(6);
551 
552                         // Decode it, using any base 64 decoder
553                         sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
554                         String userstr = new String(dec.decodeBuffer(userpassEncoded));
555                         String username = null;
556                         String password = null;
557                         StringTokenizer st = new StringTokenizer(userstr, ":");
558                         if(st.hasMoreTokens()) {
559                             username = st.nextToken();
560                         }
561                         if(st.hasMoreTokens()) {
562                             password = st.nextToken();
563                         }
564                         // autheification in the DB
565                         try {
566                             try {
567                                 // try to login as a user first ...
568                                 user = cms.loginUser(username, password);
569                             } catch(CmsException exc) {
570                                 // login as user failed, try as webuser ...
571                                 user = cms.loginWebUser(username, password);
572                             }
573                             // authentification was successful create a session
574                             session = req.getSession(true);
575                             OpenCmsServletNotify notify = new OpenCmsServletNotify(session.getId(), m_sessionStorage);
576                             session.setAttribute("NOTIFY", notify);
577                         }
578                         catch(CmsException e) {
579                             if(e.getType() == CmsException.C_NO_ACCESS) {
580 
581                                 // authentification failed, so display a login screen
582                                 requestAuthorization(req, res);
583 
584                             }
585                             else {
586                                 throw e;
587                             }
588                         }
589                     }
590                 }
591             }
592         }
593         catch(CmsException e) {
594             errorHandling(cms, cmsReq, cmsRes, e);
595         }
596         
597         return cms;
598     }
599 
600     /**
601      * This method sends a request to the client to display a login form.
602      * It is needed for HTTP-Authentification.
603      *
604      * @param req   The clints request.
605      * @param res   The servlets response.
606      */
607     private void requestAuthorization(HttpServletRequest req, HttpServletResponse res) throws IOException {
608         String servletPath = null;
609         String redirectURL = null;
610         
611         if (this.m_UseBasicAuthentication) {
612             // HTTP basic authentication is used
613             res.setHeader("WWW-Authenticate", "BASIC realm=\"OpenCms\"");
614             res.setStatus(401);
615         }
616         else {
617             // form based authentication is used, redirect the user to
618             // a page with a form to enter his username and password
619             servletPath = req.getContextPath() + req.getServletPath();
620             redirectURL = servletPath + this.m_AuthenticationFormURI + "?requestedResource=" + req.getPathInfo();
621             res.sendRedirect( redirectURL );
622         }
623     }
624 
625     /**
626      * Updates the the user data stored in the CmsCoreSession after the requested document
627      * is processed.<p>
628      *
629      * This is required if the user data (current group or project) was changed in
630      * the requested document.<p>
631      *
632      * The user data is only updated if the user was authenticated to the system.
633      *
634      * @param cms the current CmsObject initialized with the user data
635      * @param cmsReq the current request
636      */
637     private void updateUser(CmsObject cms, I_CmsRequest cmsReq) throws IOException {
638         if (! cms.getRequestContext().isUpdateSessionEnabled()) {
639             return;
640         }
641         
642         HttpSession session = null;
643 
644         // get the original ServletRequest and response
645         HttpServletRequest req = (HttpServletRequest)cmsReq.getOriginalRequest();
646 
647         //get the session if it is there
648         session = req.getSession(false);
649 
650         // if the user was authenticated via sessions, update the information in the
651         // sesssion stroage
652         if((session != null)) {
653             if(!cms.getRequestContext().currentUser().getName().equals(C_USER_GUEST)) {
654 
655                 Hashtable sessionData = new Hashtable(4);
656                 sessionData.put(C_SESSION_USERNAME, cms.getRequestContext().currentUser().getName());
657                 sessionData.put(C_SESSION_CURRENTGROUP, cms.getRequestContext().currentGroup().getName());
658                 sessionData.put(C_SESSION_PROJECT, new Integer(cms.getRequestContext().currentProject().getId()));
659                 Hashtable oldData = (Hashtable)session.getAttribute(C_SESSION_DATA);
660                 if(oldData == null) {
661                     oldData = new Hashtable();
662                 }
663                 sessionData.put(C_SESSION_DATA, oldData);
664 
665                 // was there any change on current-user, current-group or current-project?
666                 boolean dirty = false;
667                 dirty = dirty || (!sessionData.get(C_SESSION_USERNAME).equals(m_sessionStorage.getUserName(session.getId())));
668                 dirty = dirty || (!sessionData.get(C_SESSION_CURRENTGROUP).equals(m_sessionStorage.getCurrentGroup(session.getId())));
669                 dirty = dirty || (!sessionData.get(C_SESSION_PROJECT).equals(m_sessionStorage.getCurrentProject(session.getId())));
670 
671                 // update the user-data
672                 m_sessionStorage.putUser(session.getId(), sessionData);
673 
674                 // was the session changed?
675                 if((session.getAttribute(C_SESSION_IS_DIRTY) != null) || dirty) {
676 
677                     // yes- store it to the database
678                     session.removeAttribute(C_SESSION_IS_DIRTY);
679                     try {
680                         m_opencms.storeSession(session.getId(), sessionData);
681                     }
682                     catch(CmsException exc) {
683                         if(C_LOGGING && A_OpenCms.isLogging(C_OPENCMS_INFO)) {
684                             A_OpenCms.log(C_OPENCMS_INFO, "[OpenCmsServlet] cannot store session: " + com.opencms.util.Utils.getStackTrace(exc));
685                         }
686                     }
687                 }
688 
689                 // check if the session notify is set, it is nescessary to remove the
690                 // session from the internal storage on its destruction.
691                 OpenCmsServletNotify notify = null;
692                 Object sessionValue = session.getAttribute("NOTIFY");
693                 if(sessionValue instanceof OpenCmsServletNotify) {
694                     notify = (OpenCmsServletNotify)sessionValue;
695                     if(notify == null) {
696                         notify = new OpenCmsServletNotify(session.getId(), m_sessionStorage);
697                         session.setAttribute("NOTIFY", notify);
698                     }
699                 }
700                 else {
701                     notify = new OpenCmsServletNotify(session.getId(), m_sessionStorage);
702                     session.setAttribute("NOTIFY", notify);
703                 }
704             }
705         }
706     }
707 
708 
709     /**
710      * Get the value for the property entry
711      *
712      * @param part the name of the property
713      * @return The value of the property
714      */
715     public String getErrormsg(String part){
716         Properties props = new Properties();
717         try {
718             props.load(getClass().getClassLoader().getResourceAsStream("com/opencms/core/errormsg.properties"));
719         } catch(NullPointerException exc) {
720             if(A_OpenCms.isLogging(C_OPENCMS_CRITICAL) && C_LOGGING) {
721                 A_OpenCms.log(C_OPENCMS_CRITICAL, "[OpenCmsHttpServlet] cannot get com/opencms/core/errormsg.properties");
722             }
723         } catch(java.io.IOException exc) {
724             if(A_OpenCms.isLogging(C_OPENCMS_CRITICAL) && C_LOGGING) {
725                 A_OpenCms.log(C_OPENCMS_CRITICAL, "[OpenCmsHttpServlet] cannot get com/opencms/core/errormsg.properties");
726             }
727         }
728         String value = props.getProperty(part);
729         return value;
730     }
731 
732 }
733