KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * File : $Source: /usr/local/cvs/opencms/src/org/opencms/main/OpenCmsServlet.java,v $
3  * Date : $Date: 2006/03/27 14:52:27 $
4  * Version: $Revision: 1.56 $
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.file.CmsFile;
35 import org.opencms.file.CmsObject;
36 import org.opencms.file.CmsResourceFilter;
37 import org.opencms.i18n.CmsMessageContainer;
38 import org.opencms.staticexport.CmsStaticExportData;
39 import org.opencms.staticexport.CmsStaticExportRequest;
40 import org.opencms.util.CmsRequestUtil;
41
42 import java.io.IOException JavaDoc;
43
44 import javax.servlet.ServletConfig JavaDoc;
45 import javax.servlet.ServletException JavaDoc;
46 import javax.servlet.http.HttpServlet JavaDoc;
47 import javax.servlet.http.HttpServletRequest JavaDoc;
48 import javax.servlet.http.HttpServletResponse JavaDoc;
49
50 import org.apache.commons.logging.Log;
51
52 /**
53  * This the main servlet of the OpenCms system.<p>
54  *
55  * From here, all operations that are results of HTTP requests are invoked.
56  * Any incoming request is handled in multiple steps:
57  *
58  * <ol><li>The requesting <code>{@link org.opencms.file.CmsUser}</code> is authenticated
59  * and a <code>{@link org.opencms.file.CmsObject}</code> with this users context information
60  * is created. This <code>{@link org.opencms.file.CmsObject}</code> is used to access all functions of OpenCms, limited by
61  * the authenticated users permissions. If the user is not identified, it is set to the default user, usually named "Guest".</li>
62  *
63  * <li>The requested <code>{@link org.opencms.file.CmsResource}</code> is loaded into OpenCms and depending on its type
64  * (and the users persmissions to display or modify it),
65  * it is send to one of the OpenCms <code>{@link org.opencms.loader.I_CmsResourceLoader}</code> implementations
66  * do be processed.</li>
67  *
68  * <li>
69  * The <code>{@link org.opencms.loader.I_CmsResourceLoader}</code> will then decide what to do with the
70  * contents of the requested <code>{@link org.opencms.file.CmsResource}</code>.
71  * In case of a JSP resource the JSP handling mechanism is invoked with the <code>{@link org.opencms.loader.CmsJspLoader}</code>,
72  * in case of an image (or another static resource) this will be returned by the <code>{@link org.opencms.loader.CmsDumpLoader}</code>
73  * etc.
74  * </li></ol>
75  *
76  * @author Alexander Kandzior
77  * @author Michael Emmerich
78  *
79  * @version $Revision: 1.56 $
80  *
81  * @since 6.0.0
82  *
83  * @see org.opencms.main.CmsShell
84  * @see org.opencms.file.CmsObject
85  * @see org.opencms.main.OpenCms
86  */

87 public class OpenCmsServlet extends HttpServlet JavaDoc implements I_CmsRequestHandler {
88
89     /** Name of the <code>DefaultWebApplication</code> parameter in the <code>web.xml</code> OpenCms servlet configuration. */
90     public static final String JavaDoc SERVLET_PARAM_DEFAULT_WEB_APPLICATION = "DefaultWebApplication";
91
92     /** Name of the <code>OpenCmsHome</code> parameter in the <code>web.xml</code> OpenCms servlet configuration. */
93     public static final String JavaDoc SERVLET_PARAM_OPEN_CMS_HOME = "OpenCmsHome";
94
95     /** Name of the <code>OpenCmsServlet</code> parameter in the <code>web.xml</code> OpenCms servlet configuration. */
96     public static final String JavaDoc SERVLET_PARAM_OPEN_CMS_SERVLET = "OpenCmsServlet";
97
98     /** Name of the <code>WebApplicationContext</code> parameter in the <code>web.xml</code> OpenCms servlet configuration. */
99     public static final String JavaDoc SERVLET_PARAM_WEB_APPLICATION_CONTEXT = "WebApplicationContext";
100
101     /** Handler prefix. */
102     private static final String JavaDoc HANDLE_PATH = "/handle";
103
104     /** Path to handler "error page" files in the VFS. */
105     private static final String JavaDoc HANDLE_VFS_PATH = "/system/handler" + HANDLE_PATH;
106
107     /** Handler "error page" file suffix. */
108     private static final String JavaDoc HANDLE_VFS_SUFFIX = ".html";
109
110     /** Handler implementation names. */
111     private static final String JavaDoc[] HANDLER_NAMES = {"404"};
112
113     /** The log object for this class. */
114     private static final Log LOG = CmsLog.getLog(OpenCmsServlet.class);
115
116     /** Serial version UID required for safe serialization. */
117     private static final long serialVersionUID = 4729951599966070050L;
118
119     /**
120      * OpenCms servlet main request handling method.<p>
121      *
122      * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
123      */

124     public void doGet(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res) throws IOException JavaDoc, ServletException JavaDoc {
125
126         // check to OpenCms runlevel
127
int runlevel = OpenCmsCore.getInstance().getRunLevel();
128
129         // write OpenCms server identification in the response header
130
res.setHeader(CmsRequestUtil.HEADER_SERVER, OpenCmsCore.getInstance().getSystemInfo().getVersion());
131
132         if (runlevel != OpenCms.RUNLEVEL_4_SERVLET_ACCESS) {
133             // not the "normal" servlet runlevel
134
if (runlevel == OpenCms.RUNLEVEL_3_SHELL_ACCESS) {
135                 // we have shell runlevel only, upgrade to servlet runlevel (required after setup wizard)
136
init(getServletConfig());
137             } else {
138                 // illegal runlevel, we can't process requests
139
// sending status code 403, indicating the server understood the request but refused to fulfill it
140
res.sendError(HttpServletResponse.SC_FORBIDDEN);
141                 // goodbye
142
return;
143             }
144         }
145         String JavaDoc path = req.getPathInfo();
146         if ((path != null) && path.startsWith(HANDLE_PATH)) {
147             // this is a request to an OpenCms handler URI
148
invokeHandler(req, res);
149         } else {
150             // standard request to a URI in the OpenCms VFS
151
OpenCmsCore.getInstance().showResource(req, res);
152         }
153     }
154
155     /**
156      * OpenCms servlet POST request handling method,
157      * will just call {@link #doGet(HttpServletRequest, HttpServletResponse)}.<p>
158      *
159      * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
160      */

161     public void doPost(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res) throws IOException JavaDoc, ServletException JavaDoc {
162
163         doGet(req, res);
164     }
165
166     /**
167      * @see org.opencms.main.I_CmsRequestHandler#getHandlerNames()
168      */

169     public String JavaDoc[] getHandlerNames() {
170
171         return HANDLER_NAMES;
172     }
173
174     /**
175      * @see org.opencms.main.I_CmsRequestHandler#handle(HttpServletRequest, HttpServletResponse, String)
176      */

177     public void handle(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res, String JavaDoc name)
178     throws IOException JavaDoc, ServletException JavaDoc {
179
180         int errorCode;
181         try {
182             errorCode = Integer.valueOf(name).intValue();
183         } catch (NumberFormatException JavaDoc nf) {
184             res.sendError(HttpServletResponse.SC_FORBIDDEN);
185             return;
186         }
187         switch (errorCode) {
188             case 404:
189                 String JavaDoc path = req.getPathInfo();
190                 CmsObject cms = null;
191                 CmsStaticExportData exportData = null;
192                 try {
193                     cms = OpenCms.initCmsObject(OpenCms.getDefaultUsers().getUserExport());
194                     exportData = OpenCms.getStaticExportManager().getExportData(req, cms);
195                 } catch (CmsException e) {
196                     // unlikely to happen
197
if (LOG.isWarnEnabled()) {
198                         LOG.warn(
199                             Messages.get().getBundle().key(Messages.LOG_INIT_CMSOBJECT_IN_HANDLER_2, name, path),
200                             e);
201                     }
202                 }
203                 if (exportData != null) {
204                     try {
205                         // generate a static export request wrapper
206
CmsStaticExportRequest exportReq = new CmsStaticExportRequest(req, exportData);
207                         // export the resource and set the response status according to the result
208
res.setStatus(OpenCms.getStaticExportManager().export(exportReq, res, cms, exportData));
209                     } catch (Throwable JavaDoc t) {
210                         if (LOG.isWarnEnabled()) {
211                             LOG.warn(Messages.get().getBundle().key(Messages.LOG_ERROR_EXPORT_1, exportData), t);
212                         }
213                         openErrorHandler(req, res, errorCode);
214                     }
215                 } else {
216                     openErrorHandler(req, res, errorCode);
217                 }
218                 break;
219             default:
220                 openErrorHandler(req, res, errorCode);
221         }
222     }
223
224     /**
225      * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)
226      */

227     public synchronized void init(ServletConfig JavaDoc config) throws ServletException JavaDoc {
228
229         super.init(config);
230         try {
231             // upgrade the runlevel
232
// usually this should have already been done by the context listener
233
// however, after a fresh install / setup this will be done from here
234
OpenCmsCore.getInstance().upgradeRunlevel(config.getServletContext());
235             // finalize OpenCms initialization
236
OpenCmsCore.getInstance().initServlet(this);
237         } catch (CmsInitException e) {
238             if (Messages.ERR_CRITICAL_INIT_WIZARD_0.equals(e.getMessageContainer().getKey())) {
239                 // if wizard is still enabled - allow retry of initialization (required for setup wizard)
240
// this means the servlet init() call must be terminated by an exception
241
throw new ServletException JavaDoc(e.getMessage());
242             }
243         } catch (Throwable JavaDoc t) {
244             LOG.error(Messages.get().getBundle().key(Messages.LOG_ERROR_GENERIC_0), t);
245         }
246     }
247
248     /**
249      * Manages requests to internal OpenCms request handlers.<p>
250      *
251      * @param req the current request
252      * @param res the current response
253      * @throws ServletException
254      * @throws ServletException in case an error occurs
255      * @throws IOException in case an error occurs
256      */

257     protected void invokeHandler(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res) throws IOException JavaDoc, ServletException JavaDoc {
258
259         String JavaDoc name = req.getPathInfo().substring(HANDLE_PATH.length());
260         I_CmsRequestHandler handler = OpenCmsCore.getInstance().getRequestHandler(name);
261         if (handler != null) {
262             handler.handle(req, res, name);
263         } else {
264             openErrorHandler(req, res, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
265         }
266     }
267
268     /**
269      * Displays an error code handler loaded from the OpenCms VFS,
270      * or if such a page does not exist,
271      * displays the default servlet container error code.<p>
272      *
273      * @param req the current request
274      * @param res the current response
275      * @param errorCode the error code to display
276      * @throws IOException if something goes wrong
277      * @throws ServletException if something goes wrong
278      */

279     protected void openErrorHandler(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res, int errorCode)
280     throws IOException JavaDoc, ServletException JavaDoc {
281
282         String JavaDoc handlerUri = (new StringBuffer JavaDoc(64)).append(HANDLE_VFS_PATH).append(errorCode).append(HANDLE_VFS_SUFFIX).toString();
283         CmsObject cms;
284         CmsFile file;
285         try {
286             // create OpenCms context
287
cms = OpenCms.initCmsObject(OpenCms.getDefaultUsers().getUserGuest());
288             cms.getRequestContext().setUri(handlerUri);
289             // read the error handler file
290
file = cms.readFile(handlerUri, CmsResourceFilter.IGNORE_EXPIRATION);
291         } catch (CmsException e) {
292             // unlikely to happen as the OpenCms "Guest" context can always be initialized
293
CmsMessageContainer container = Messages.get().container(
294                 Messages.LOG_INIT_CMSOBJECT_IN_HANDLER_2,
295                 new Integer JavaDoc(errorCode),
296                 handlerUri);
297             if (LOG.isWarnEnabled()) {
298                 LOG.warn(org.opencms.jsp.Messages.getLocalizedMessage(container, req), e);
299             }
300             // however, if it _does_ happen, then we really can't continue here
301
if (!res.isCommitted()) {
302                 // since the handler file is not accessible, display the default error page
303
res.sendError(errorCode, e.getLocalizedMessage());
304             }
305             return;
306         }
307         try {
308             // provide the original error code in a request attribute
309
req.setAttribute(CmsRequestUtil.ATTRIBUTE_ERRORCODE, new Integer JavaDoc(errorCode));
310             OpenCms.getResourceManager().loadResource(cms, file, req, res);
311         } catch (CmsException e) {
312             // unable to load error page handler VFS resource
313
CmsMessageContainer container = Messages.get().container(
314                 Messages.ERR_SHOW_ERR_HANDLER_RESOURCE_2,
315                 new Integer JavaDoc(errorCode),
316                 handlerUri);
317             throw new ServletException JavaDoc(org.opencms.jsp.Messages.getLocalizedMessage(container, req), e);
318         }
319     }
320 }
Popular Tags