KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > portlet > ManagedCocoonPortlet


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.cocoon.portlet;
17
18 import org.apache.avalon.excalibur.logger.LogKitLoggerManager;
19 import org.apache.avalon.framework.configuration.Configuration;
20 import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
21 import org.apache.avalon.framework.context.DefaultContext;
22 import org.apache.avalon.framework.logger.LogKitLogger;
23 import org.apache.avalon.framework.logger.Logger;
24
25 import org.apache.cocoon.Cocoon;
26 import org.apache.cocoon.CocoonAccess;
27 import org.apache.cocoon.ConnectionResetException;
28 import org.apache.cocoon.Constants;
29 import org.apache.cocoon.ResourceNotFoundException;
30 import org.apache.cocoon.components.notification.DefaultNotifyingBuilder;
31 import org.apache.cocoon.components.notification.Notifier;
32 import org.apache.cocoon.components.notification.Notifying;
33 import org.apache.cocoon.environment.Environment;
34 import org.apache.cocoon.environment.portlet.PortletContext;
35 import org.apache.cocoon.environment.portlet.PortletEnvironment;
36 import org.apache.cocoon.portlet.multipart.MultipartActionRequest;
37 import org.apache.cocoon.portlet.multipart.RequestFactory;
38
39 import org.apache.commons.lang.BooleanUtils;
40 import org.apache.log.ContextMap;
41 import org.apache.log.Hierarchy;
42 import org.apache.pluto.core.impl.PortletContextImpl;
43
44 import javax.portlet.ActionRequest;
45 import javax.portlet.ActionResponse;
46 import javax.portlet.GenericPortlet;
47 import javax.portlet.PortletConfig;
48 import javax.portlet.PortletException;
49 import javax.portlet.PortletSession;
50 import javax.portlet.RenderRequest;
51 import javax.portlet.RenderResponse;
52 import javax.portlet.PortletRequest;
53 import java.io.File JavaDoc;
54 import java.io.FileInputStream JavaDoc;
55 import java.io.IOException JavaDoc;
56 import java.io.InputStream JavaDoc;
57 import java.io.OutputStream JavaDoc;
58 import java.io.PrintStream JavaDoc;
59 import java.net.MalformedURLException JavaDoc;
60 import java.net.SocketException JavaDoc;
61 import java.net.URL JavaDoc;
62 import java.util.HashMap JavaDoc;
63
64 /**
65  * This is the entry point for Cocoon execution as an JSR-168 Portlet.
66  *
67  * <p>This implementation of the Portlet interface requires that someone will
68  * first create and initialize an instance of the Cocoon object, and this
69  * Portlet will use this instance to process requests.</p>
70  *
71  * @version CVS $Id: ManagedCocoonPortlet.java 325950 2005-10-17 18:26:07Z vgritsenko $
72  */

73 public class ManagedCocoonPortlet extends GenericPortlet {
74
75     // Processing time message
76
protected static final String JavaDoc PROCESSED_BY = "Processed by "
77             + Constants.COMPLETE_NAME + " in ";
78
79     // Used by "show-time"
80
static final float SECOND = 1000;
81     static final float MINUTE = 60 * SECOND;
82     static final float HOUR = 60 * MINUTE;
83
84     private Logger log;
85
86     /**
87      * Holds exception happened during initialization (if any)
88      */

89     protected Exception JavaDoc exception;
90
91
92     /**
93      * Allow adding processing time to the response
94      */

95     protected boolean showTime;
96
97     /**
98      * If true, processing time will be added as an HTML comment
99      */

100     protected boolean hiddenShowTime;
101
102
103     /**
104      * Default value for {@link #enableUploads} parameter (false)
105      */

106     private static final boolean ENABLE_UPLOADS = false;
107     private static final boolean SAVE_UPLOADS_TO_DISK = true;
108     private static final int MAX_UPLOAD_SIZE = 10000000; // 10Mb
109

110     /**
111      * Allow processing of upload requests (mime/multipart)
112      */

113     private boolean enableUploads;
114     private boolean autoSaveUploads;
115     private boolean allowOverwrite;
116     private boolean silentlyRename;
117     private int maxUploadSize;
118
119     private File JavaDoc uploadDir;
120     private File JavaDoc workDir;
121
122     private String JavaDoc containerEncoding;
123     private String JavaDoc defaultFormEncoding;
124
125     protected javax.portlet.PortletContext portletContext;
126     protected PortletContext envPortletContext;
127
128
129     /**
130      * If true or not set, this class will try to catch and handle all Cocoon exceptions.
131      * If false, it will rethrow them to the portlet container.
132      */

133     private boolean manageExceptions;
134
135     /**
136      * This is the path to the portlet context (or the result
137      * of calling getRealPath('/') on the PortletContext.
138      * Note, that this can be null.
139      */

140     protected String JavaDoc portletContextPath;
141
142     /**
143      * This is the url to the portlet context directory
144      */

145     protected String JavaDoc portletContextURL;
146
147     /**
148      * The RequestFactory is responsible for wrapping multipart-encoded
149      * forms and for handing the file payload of incoming requests
150      */

151     protected RequestFactory requestFactory;
152
153     /**
154      * Value to be used as servletPath in the request.
155      * Provided via configuration parameter, if missing, defaults to the
156      * '/portlets/' + portletName.
157      */

158     protected String JavaDoc servletPath;
159
160     /**
161      * Default scope for the session attributes, either
162      * {@link javax.portlet.PortletSession#PORTLET_SCOPE} or
163      * {@link javax.portlet.PortletSession#APPLICATION_SCOPE}.
164      * This corresponds to <code>default-session-scope</code>
165      * parameter, with default value <code>portlet</code>.
166      *
167      * @see org.apache.cocoon.environment.portlet.PortletSession
168      */

169     protected int defaultSessionScope;
170
171     /**
172      * Store pathInfo in session
173      */

174     protected boolean storeSessionPath;
175
176     /**
177      * Initialize this <code>CocoonPortlet</code> instance.
178      *
179      * <p>Uses the following parameters:
180      * portlet-logger
181      * enable-uploads
182      * autosave-uploads
183      * overwrite-uploads
184      * upload-max-size
185      * show-time
186      * container-encoding
187      * form-encoding
188      * manage-exceptions
189      * servlet-path
190      *
191      * @param conf The PortletConfig object from the portlet container.
192      * @throws PortletException
193      */

194     public void init(PortletConfig conf) throws PortletException {
195
196         super.init(conf);
197
198         String JavaDoc value;
199
200         this.portletContext = conf.getPortletContext();
201         this.envPortletContext = new PortletContext(this.portletContext);
202         this.portletContextPath = this.portletContext.getRealPath("/");
203
204         // first init the work-directory for the logger.
205
// this is required if we are running inside a war file!
206
final String JavaDoc workDirParam = getInitParameter("work-directory");
207         if (workDirParam != null) {
208             if (this.portletContextPath == null) {
209                 // No context path : consider work-directory as absolute
210
this.workDir = new File JavaDoc(workDirParam);
211             } else {
212                 // Context path exists : is work-directory absolute ?
213
File JavaDoc workDirParamFile = new File JavaDoc(workDirParam);
214                 if (workDirParamFile.isAbsolute()) {
215                     // Yes : keep it as is
216
this.workDir = workDirParamFile;
217                 } else {
218                     // No : consider it relative to context path
219
this.workDir = new File JavaDoc(portletContextPath, workDirParam);
220                 }
221             }
222         } else {
223             // TODO: Check portlet specification
224
this.workDir = (File JavaDoc) this.portletContext.getAttribute("javax.servlet.context.tempdir");
225             if (this.workDir == null) {
226                 this.workDir = new File JavaDoc(this.portletContext.getRealPath("/WEB-INF/work"));
227             }
228             this.workDir = new File JavaDoc(workDir, "cocoon-files");
229         }
230         this.workDir.mkdirs();
231
232         // Init logger
233
initLogger();
234
235         String JavaDoc path = this.portletContextPath;
236         if (getLogger().isDebugEnabled()) {
237             getLogger().debug("getRealPath for /: " + path);
238         }
239         if (path == null) {
240             // Try to figure out the path of the root from that of WEB-INF
241
try {
242                 path = this.portletContext.getResource("/WEB-INF").toString();
243             } catch (MalformedURLException JavaDoc me) {
244                 throw new PortletException("Unable to get resource 'WEB-INF'.", me);
245             }
246             if (getLogger().isDebugEnabled()) {
247                 getLogger().debug("getResource for /WEB-INF: " + path);
248             }
249             path = path.substring(0, path.length() - "WEB-INF".length());
250             if (getLogger().isDebugEnabled()) {
251                 getLogger().debug("Path for Root: " + path);
252             }
253         }
254
255         try {
256             if (path.indexOf(':') > 1) {
257                 this.portletContextURL = path;
258             } else {
259                 this.portletContextURL = new File JavaDoc(path).toURL().toExternalForm();
260             }
261         } catch (MalformedURLException JavaDoc me) {
262             // VG: Novell has absolute file names starting with the
263
// volume name which is easily more then one letter.
264
// Examples: sys:/apache/cocoon or sys:\apache\cocoon
265
try {
266                 this.portletContextURL = new File JavaDoc(path).toURL().toExternalForm();
267             } catch (MalformedURLException JavaDoc ignored) {
268                 throw new PortletException("Unable to determine portlet context URL.", me);
269             }
270         }
271         if (getLogger().isDebugEnabled()) {
272             getLogger().debug("URL for Root: " + this.portletContextURL);
273         }
274
275         final String JavaDoc uploadDirParam = conf.getInitParameter("upload-directory");
276         if (uploadDirParam != null) {
277             if (this.portletContextPath == null) {
278                 this.uploadDir = new File JavaDoc(uploadDirParam);
279             } else {
280                 // Context path exists : is upload-directory absolute ?
281
File JavaDoc uploadDirParamFile = new File JavaDoc(uploadDirParam);
282                 if (uploadDirParamFile.isAbsolute()) {
283                     // Yes : keep it as is
284
this.uploadDir = uploadDirParamFile;
285                 } else {
286                     // No : consider it relative to context path
287
this.uploadDir = new File JavaDoc(portletContextPath, uploadDirParam);
288                 }
289             }
290             if (getLogger().isDebugEnabled()) {
291                 getLogger().debug("Using upload-directory " + this.uploadDir);
292             }
293         } else {
294             this.uploadDir = new File JavaDoc(workDir, "upload-dir" + File.separator);
295             if (getLogger().isDebugEnabled()) {
296                 getLogger().debug("upload-directory was not set - defaulting to " + this.uploadDir);
297             }
298         }
299         this.uploadDir.mkdirs();
300
301         this.enableUploads = getInitParameterAsBoolean("enable-uploads", ENABLE_UPLOADS);
302         this.autoSaveUploads = getInitParameterAsBoolean("autosave-uploads", SAVE_UPLOADS_TO_DISK);
303
304         String JavaDoc overwriteParam = getInitParameter("overwrite-uploads", "rename");
305         // accepted values are deny|allow|rename - rename is default.
306
if ("deny".equalsIgnoreCase(overwriteParam)) {
307             this.allowOverwrite = false;
308             this.silentlyRename = false;
309         } else if ("allow".equalsIgnoreCase(overwriteParam)) {
310             this.allowOverwrite = true;
311             this.silentlyRename = false; // ignored in this case
312
} else {
313             // either rename is specified or unsupported value - default to rename.
314
this.allowOverwrite = false;
315             this.silentlyRename = true;
316         }
317
318         this.maxUploadSize = getInitParameterAsInteger("upload-max-size", MAX_UPLOAD_SIZE);
319
320         value = conf.getInitParameter("show-time");
321         this.showTime = BooleanUtils.toBoolean(value) || (this.hiddenShowTime = "hide".equals(value));
322         if (value == null) {
323             if (getLogger().isDebugEnabled()) {
324                 getLogger().debug("show-time was not set - defaulting to false");
325             }
326         }
327
328         this.containerEncoding = getInitParameter("container-encoding", "ISO-8859-1");
329         this.defaultFormEncoding = getInitParameter("form-encoding", "ISO-8859-1");
330
331         this.manageExceptions = getInitParameterAsBoolean("manage-exceptions", true);
332
333         this.requestFactory = new RequestFactory(this.autoSaveUploads,
334                                                  this.uploadDir,
335                                                  this.allowOverwrite,
336                                                  this.silentlyRename,
337                                                  this.maxUploadSize,
338                                                  this.defaultFormEncoding);
339
340         this.servletPath = getInitParameter("servlet-path", null);
341         if (this.servletPath != null) {
342             if (this.servletPath.startsWith("/")) {
343                 this.servletPath = this.servletPath.substring(1);
344             }
345             if (this.servletPath.endsWith("/")) {
346                 this.servletPath = servletPath.substring(0, servletPath.length() - 1);
347             }
348         }
349
350         final String JavaDoc sessionScopeParam = getInitParameter("default-session-scope", "portlet");
351         if ("application".equalsIgnoreCase(sessionScopeParam)) {
352             this.defaultSessionScope = javax.portlet.PortletSession.APPLICATION_SCOPE;
353         } else {
354             this.defaultSessionScope = javax.portlet.PortletSession.PORTLET_SCOPE;
355         }
356
357         this.storeSessionPath = getInitParameterAsBoolean("store-session-path", false);
358     }
359
360     public void processAction(ActionRequest req, ActionResponse res)
361     throws PortletException, IOException JavaDoc {
362
363         // remember when we started (used for timing the processing)
364
long start = System.currentTimeMillis();
365
366         // add the cocoon header timestamp
367
res.setProperty("X-Cocoon-Version", Constants.VERSION);
368
369         // get the request (wrapped if contains multipart-form data)
370
ActionRequest request;
371         try {
372             if (this.enableUploads) {
373                 request = requestFactory.getServletRequest(req);
374             } else {
375                 request = req;
376             }
377         } catch (Exception JavaDoc e) {
378             if (getLogger().isErrorEnabled()) {
379                 getLogger().error("Problem with Cocoon portlet", e);
380             }
381
382             manageException(req, res, null, null,
383                             "Problem in creating the Request", null, null, e);
384             return;
385         }
386
387         // Get the cocoon engine instance
388
Cocoon cocoon = getCocoon();
389
390         // Check if cocoon was initialized
391
if (cocoon == null) {
392             manageException(request, res, null, null,
393                             "Initialization Problem",
394                             null /* "Cocoon was not initialized" */,
395                             null /* "Cocoon was not initialized, cannot process request" */,
396                             this.exception);
397             return;
398         }
399
400         // We got it... Process the request
401
String JavaDoc servletPath = this.servletPath;
402         if (servletPath == null) {
403             servletPath = "portlets/" + getPortletConfig().getPortletName();
404         }
405         String JavaDoc pathInfo = getPathInfo(request);
406
407         String JavaDoc uri = servletPath;
408         if (pathInfo != null) {
409             uri += pathInfo;
410         }
411
412         ContextMap ctxMap = null;
413
414         Environment env;
415         try {
416             if (uri.charAt(0) == '/') {
417                 uri = uri.substring(1);
418             }
419             env = getEnvironment(servletPath, pathInfo, uri, request, res);
420         } catch (Exception JavaDoc e) {
421             if (getLogger().isErrorEnabled()) {
422                 getLogger().error("Problem with Cocoon portlet", e);
423             }
424
425             manageException(request, res, null, uri,
426                             "Problem in creating the Environment", null, null, e);
427             return;
428         }
429
430         try {
431             try {
432                 // Initialize a fresh log context containing the object model: it
433
// will be used by the CocoonLogFormatter
434
ctxMap = ContextMap.getCurrentContext();
435                 // Add thread name (default content for empty context)
436
String JavaDoc threadName = Thread.currentThread().getName();
437                 ctxMap.set("threadName", threadName);
438                 // Add the object model
439
ctxMap.set("objectModel", env.getObjectModel());
440                 // Add a unique request id (threadName + currentTime
441
ctxMap.set("request-id", threadName + System.currentTimeMillis());
442
443                 if (cocoon.process(env)) {
444                 } else {
445                     // We reach this when there is nothing in the processing change that matches
446
// the request. For example, no matcher matches.
447
getLogger().fatalError("The Cocoon engine failed to process the request.");
448                     manageException(request, res, env, uri,
449                                     "Request Processing Failed",
450                                     "Cocoon engine failed in process the request",
451                                     "The processing engine failed to process the request. This could be due to lack of matching or bugs in the pipeline engine.",
452                                     null);
453                     return;
454                 }
455             } catch (ResourceNotFoundException e) {
456                 if (getLogger().isDebugEnabled()) {
457                     getLogger().warn(e.getMessage(), e);
458                 } else if (getLogger().isWarnEnabled()) {
459                     getLogger().warn(e.getMessage());
460                 }
461
462                 manageException(request, res, env, uri,
463                                 "Resource Not Found",
464                                 "Resource Not Found",
465                                 "The requested portlet could not be found",
466                                 e);
467                 return;
468
469             } catch (ConnectionResetException e) {
470                 if (getLogger().isDebugEnabled()) {
471                     getLogger().debug(e.getMessage(), e);
472                 } else if (getLogger().isWarnEnabled()) {
473                     getLogger().warn(e.getMessage());
474                 }
475
476             } catch (IOException JavaDoc e) {
477                 // Tomcat5 wraps SocketException into ClientAbortException which extends IOException.
478
if (getLogger().isDebugEnabled()) {
479                     getLogger().debug(e.getMessage(), e);
480                 } else if (getLogger().isWarnEnabled()) {
481                     getLogger().warn(e.getMessage());
482                 }
483
484             } catch (Exception JavaDoc e) {
485                 if (getLogger().isErrorEnabled()) {
486                     getLogger().error("Internal Cocoon Problem", e);
487                 }
488
489                 manageException(request, res, env, uri,
490                                 "Internal Server Error", null, null, e);
491                 return;
492             }
493
494             long end = System.currentTimeMillis();
495             String JavaDoc timeString = processTime(end - start);
496             if (getLogger().isInfoEnabled()) {
497                 getLogger().info("'" + uri + "' " + timeString);
498             }
499             res.setProperty("X-Cocoon-Time", timeString);
500         } finally {
501             if (ctxMap != null) {
502                 ctxMap.clear();
503             }
504
505             try {
506                 if (request instanceof MultipartActionRequest) {
507                     if (getLogger().isDebugEnabled()) {
508                         getLogger().debug("Deleting uploaded file(s).");
509                     }
510                     ((MultipartActionRequest) request).cleanup();
511                 }
512             } catch (IOException JavaDoc e) {
513                 getLogger().error("Cocoon got an Exception while trying to cleanup the uploaded files.", e);
514             }
515         }
516     }
517
518     /**
519      * Process the specified <code>RenderRequest</code> producing output
520      * on the specified <code>RenderResponse</code>.
521      */

522     public void render(RenderRequest req, RenderResponse res)
523     throws PortletException, IOException JavaDoc {
524
525         // remember when we started (used for timing the processing)
526
long start = System.currentTimeMillis();
527
528         // add the cocoon header timestamp
529
res.setProperty("X-Cocoon-Version", Constants.VERSION);
530
531         // get the request (wrapped if contains multipart-form data)
532
RenderRequest request = req;
533
534         // Get the cocoon engine instance
535
Cocoon cocoon = getCocoon();
536
537         // Check if cocoon was initialized
538
if (cocoon == null) {
539             manageException(request, res, null, null,
540                             "Initialization Problem",
541                             null /* "Cocoon was not initialized" */,
542                             null /* "Cocoon was not initialized, cannot process request" */,
543                             this.exception);
544             return;
545         }
546
547         // We got it... Process the request
548
String JavaDoc servletPath = this.servletPath;
549         if (servletPath == null) {
550             servletPath = "portlets/" + getPortletConfig().getPortletName();
551         }
552         String JavaDoc pathInfo = getPathInfo(request);
553
554         String JavaDoc uri = servletPath;
555         if (pathInfo != null) {
556             uri += pathInfo;
557         }
558
559         String JavaDoc contentType = null;
560         ContextMap ctxMap = null;
561
562         Environment env;
563         try {
564             if (uri.charAt(0) == '/') {
565                 uri = uri.substring(1);
566             }
567             env = getEnvironment(servletPath, pathInfo, uri, request, res);
568         } catch (Exception JavaDoc e) {
569             if (getLogger().isErrorEnabled()) {
570                 getLogger().error("Problem with Cocoon portlet", e);
571             }
572
573             manageException(request, res, null, uri,
574                             "Problem in creating the Environment", null, null, e);
575             return;
576         }
577
578         try {
579             try {
580                 // Initialize a fresh log context containing the object model: it
581
// will be used by the CocoonLogFormatter
582
ctxMap = ContextMap.getCurrentContext();
583                 // Add thread name (default content for empty context)
584
String JavaDoc threadName = Thread.currentThread().getName();
585                 ctxMap.set("threadName", threadName);
586                 // Add the object model
587
ctxMap.set("objectModel", env.getObjectModel());
588                 // Add a unique request id (threadName + currentTime
589
ctxMap.set("request-id", threadName + System.currentTimeMillis());
590
591                 if (cocoon.process(env)) {
592                 } else {
593                     // We reach this when there is nothing in the processing change that matches
594
// the request. For example, no matcher matches.
595
getLogger().fatalError("The Cocoon engine failed to process the request.");
596                     manageException(request, res, env, uri,
597                                     "Request Processing Failed",
598                                     "Cocoon engine failed in process the request",
599                                     "The processing engine failed to process the request. This could be due to lack of matching or bugs in the pipeline engine.",
600                                     null);
601                     return;
602                 }
603             } catch (ResourceNotFoundException rse) {
604                 if (getLogger().isWarnEnabled()) {
605                     getLogger().warn("The resource was not found", rse);
606                 }
607
608                 manageException(request, res, env, uri,
609                                 "Resource Not Found",
610                                 "Resource Not Found",
611                                 "The requested portlet could not be found",
612                                 rse);
613                 return;
614
615             } catch (ConnectionResetException e) {
616                 if (getLogger().isDebugEnabled()) {
617                     getLogger().debug(e.getMessage(), e);
618                 } else if (getLogger().isWarnEnabled()) {
619                     getLogger().warn(e.getMessage());
620                 }
621
622             } catch (IOException JavaDoc e) {
623                 // Tomcat5 wraps SocketException into ClientAbortException which extends IOException.
624
if (getLogger().isDebugEnabled()) {
625                     getLogger().debug(e.getMessage(), e);
626                 } else if (getLogger().isWarnEnabled()) {
627                     getLogger().warn(e.getMessage());
628                 }
629
630             } catch (Exception JavaDoc e) {
631                 if (getLogger().isErrorEnabled()) {
632                     getLogger().error("Internal Cocoon Problem", e);
633                 }
634
635                 manageException(request, res, env, uri,
636                                 "Internal Server Error", null, null, e);
637                 return;
638             }
639
640             long end = System.currentTimeMillis();
641             String JavaDoc timeString = processTime(end - start);
642             if (getLogger().isInfoEnabled()) {
643                 getLogger().info("'" + uri + "' " + timeString);
644             }
645             res.setProperty("X-Cocoon-Time", timeString);
646
647             // FIXME: contentType is always null (see line 556)
648
if (contentType != null && contentType.equals("text/html")) {
649                 String JavaDoc showTime = request.getParameter(Constants.SHOWTIME_PARAM);
650                 boolean show = this.showTime;
651                 if (showTime != null) {
652                     show = !showTime.equalsIgnoreCase("no");
653                 }
654                 if (show) {
655                     boolean hide = this.hiddenShowTime;
656                     if (showTime != null) {
657                         hide = showTime.equalsIgnoreCase("hide");
658                     }
659                     PrintStream JavaDoc out = new PrintStream JavaDoc(res.getPortletOutputStream());
660                     out.print((hide) ? "<!-- " : "<p>");
661                     out.print(timeString);
662                     out.println((hide) ? " -->" : "</p>\n");
663                 }
664             }
665         } finally {
666             if (ctxMap != null) {
667                 ctxMap.clear();
668             }
669
670             /*
671              * Portlet Specification 1.0, PLT.12.3.2 Output Stream and Writer Objects:
672              * The termination of the render method of the portlet indicates
673              * that the portlet has satisfied the request and that the output
674              * object is to be closed.
675              *
676              * Portlet container will close the stream, no need to close it here.
677              */

678         }
679     }
680
681     private String JavaDoc getPathInfo(PortletRequest request) {
682         PortletSession session = null;
683
684         String JavaDoc pathInfo = request.getParameter(PortletEnvironment.PARAMETER_PATH_INFO);
685         if (storeSessionPath) {
686             session = request.getPortletSession(true);
687             if (pathInfo == null) {
688                 pathInfo = (String JavaDoc)session.getAttribute(PortletEnvironment.PARAMETER_PATH_INFO);
689             }
690         }
691
692         // Make sure it starts with or equals to '/'
693
if (pathInfo == null) {
694             pathInfo = "/";
695         } else if (!pathInfo.startsWith("/")) {
696             pathInfo = '/' + pathInfo;
697         }
698
699         if (storeSessionPath) {
700             session.setAttribute(PortletEnvironment.PARAMETER_PATH_INFO, pathInfo);
701         }
702         return pathInfo;
703     }
704
705     protected void manageException(ActionRequest req, ActionResponse res, Environment env,
706                                    String JavaDoc uri, String JavaDoc title, String JavaDoc message, String JavaDoc description,
707                                    Exception JavaDoc e)
708     throws PortletException {
709         throw new PortletException("Exception in CocoonPortlet", e);
710     }
711
712     protected void manageException(RenderRequest req, RenderResponse res, Environment env,
713                                    String JavaDoc uri, String JavaDoc title, String JavaDoc message, String JavaDoc description,
714                                    Exception JavaDoc e)
715     throws IOException JavaDoc, PortletException {
716         if (this.manageExceptions) {
717             if (env != null) {
718                 env.tryResetResponse();
719             } else {
720                 res.reset();
721             }
722
723             String JavaDoc type = Notifying.FATAL_NOTIFICATION;
724             HashMap JavaDoc extraDescriptions = null;
725
726             extraDescriptions = new HashMap JavaDoc(2);
727             extraDescriptions.put(Notifying.EXTRA_REQUESTURI, getPortletConfig().getPortletName());
728             if (uri != null) {
729                  extraDescriptions.put("Request URI", uri);
730             }
731
732             // Do not show exception stack trace when log level is WARN or above. Show only message.
733
if (!getLogger().isInfoEnabled()) {
734                 Throwable JavaDoc t = DefaultNotifyingBuilder.getRootCause(e);
735                 if (t != null) extraDescriptions.put(Notifying.EXTRA_CAUSE, t.getMessage());
736                 e = null;
737             }
738
739             Notifying n = new DefaultNotifyingBuilder().build(this,
740                                                               e,
741                                                               type,
742                                                               title,
743                                                               "Cocoon Portlet",
744                                                               message,
745                                                               description,
746                                                               extraDescriptions);
747
748             res.setContentType("text/html");
749             Notifier.notify(n, res.getPortletOutputStream(), "text/html");
750         } else {
751             res.flushBuffer();
752             throw new PortletException("Exception in CocoonPortlet", e);
753         }
754     }
755
756     /**
757      * Create the environment for the request
758      */

759     protected Environment getEnvironment(String JavaDoc servletPath,
760                                          String JavaDoc pathInfo,
761                                          String JavaDoc uri,
762                                          ActionRequest req,
763                                          ActionResponse res)
764     throws Exception JavaDoc {
765         PortletEnvironment env;
766
767         String JavaDoc formEncoding = req.getParameter("cocoon-form-encoding");
768         if (formEncoding == null) {
769             formEncoding = this.defaultFormEncoding;
770         }
771         env = new PortletEnvironment(servletPath,
772                                      pathInfo,
773                                      uri,
774                                      this.portletContextURL,
775                                      req,
776                                      res,
777                                      this.portletContext,
778                                      this.envPortletContext,
779                                      this.containerEncoding,
780                                      formEncoding,
781                                      this.defaultSessionScope);
782         env.enableLogging(getLogger());
783         return env;
784     }
785
786     /**
787      * Create the environment for the request
788      */

789     protected Environment getEnvironment(String JavaDoc servletPath,
790                                          String JavaDoc pathInfo,
791                                          String JavaDoc uri,
792                                          RenderRequest req,
793                                          RenderResponse res)
794     throws Exception JavaDoc {
795         PortletEnvironment env;
796
797         String JavaDoc formEncoding = req.getParameter("cocoon-form-encoding");
798         if (formEncoding == null) {
799             formEncoding = this.defaultFormEncoding;
800         }
801         env = new PortletEnvironment(servletPath,
802                                      pathInfo,
803                                      uri,
804                                      this.portletContextURL,
805                                      req,
806                                      res,
807                                      this.portletContext,
808                                      this.envPortletContext,
809                                      this.containerEncoding,
810                                      formEncoding,
811                                      this.defaultSessionScope);
812         env.enableLogging(getLogger());
813         return env;
814     }
815
816     private String JavaDoc processTime(long time) {
817         StringBuffer JavaDoc out = new StringBuffer JavaDoc(PROCESSED_BY);
818         if (time <= SECOND) {
819             out.append(time);
820             out.append(" milliseconds.");
821         } else if (time <= MINUTE) {
822             out.append(time / SECOND);
823             out.append(" seconds.");
824         } else if (time <= HOUR) {
825             out.append(time / MINUTE);
826             out.append(" minutes.");
827         } else {
828             out.append(time / HOUR);
829             out.append(" hours.");
830         }
831         return out.toString();
832     }
833
834     /**
835      * Gets the current cocoon object.
836      * Reload cocoon if configuration changed or we are reloading.
837      */

838     private Cocoon getCocoon() {
839         return new CocoonAccess() {
840             final Cocoon instance() {
841                 return super.getCocoon();
842             }
843         }.instance();
844     }
845
846     /**
847      * Get an initialisation parameter. The value is trimmed, and null is returned if the trimmed value
848      * is empty.
849      */

850     public String JavaDoc getInitParameter(String JavaDoc name) {
851         String JavaDoc result = super.getInitParameter(name);
852         if (result != null) {
853             result = result.trim();
854             if (result.length() == 0) {
855                 result = null;
856             }
857         }
858
859         return result;
860     }
861
862     /** Convenience method to access portlet parameters */
863     protected String JavaDoc getInitParameter(String JavaDoc name, String JavaDoc defaultValue) {
864         String JavaDoc result = getInitParameter(name);
865         if (result == null) {
866             if (getLogger() != null && getLogger().isDebugEnabled()) {
867                 getLogger().debug(name + " was not set - defaulting to '" + defaultValue + "'");
868             }
869             return defaultValue;
870         } else {
871             return result;
872         }
873     }
874
875     /** Convenience method to access boolean portlet parameters */
876     protected boolean getInitParameterAsBoolean(String JavaDoc name, boolean defaultValue) {
877         String JavaDoc value = getInitParameter(name);
878         if (value == null) {
879             if (getLogger() != null && getLogger().isDebugEnabled()) {
880                 getLogger().debug(name + " was not set - defaulting to '" + defaultValue + "'");
881             }
882             return defaultValue;
883         }
884
885         return BooleanUtils.toBoolean(value);
886     }
887
888     protected int getInitParameterAsInteger(String JavaDoc name, int defaultValue) {
889         String JavaDoc value = getInitParameter(name);
890         if (value == null) {
891             if (getLogger() != null && getLogger().isDebugEnabled()) {
892                 getLogger().debug(name + " was not set - defaulting to '" + defaultValue + "'");
893             }
894             return defaultValue;
895         } else {
896             return Integer.parseInt(value);
897         }
898     }
899
900     protected void initLogger() {
901         final String JavaDoc accesslogger = getInitParameter("portlet-logger", "cocoon");
902
903         final Hierarchy defaultHierarchy = Hierarchy.getDefaultHierarchy();
904
905         final Logger logger = new LogKitLogger(Hierarchy.getDefaultHierarchy().getLoggerFor(""));
906
907         final LogKitLoggerManager logKitLoggerManager = new LogKitLoggerManager(defaultHierarchy);
908         logKitLoggerManager.enableLogging(logger);
909
910         final DefaultContext subcontext = new DefaultContext();
911         subcontext.put(Constants.CONTEXT_WORK_DIR, workDir);
912         subcontext.put("portlet-context", this.portletContext);
913         if (this.portletContextPath == null) {
914             File JavaDoc logSCDir = new File JavaDoc(this.workDir, "log");
915             logSCDir.mkdirs();
916             if (getLogger().isWarnEnabled()) {
917                 getLogger().warn("Setting context-root for LogKit to " + logSCDir);
918             }
919             subcontext.put("context-root", logSCDir.toString());
920         } else {
921             subcontext.put("context-root", this.portletContextPath);
922         }
923         if ( this.portletContext instanceof PortletContextImpl ) {
924             subcontext.put("servlet-context", ((PortletContextImpl)this.portletContext).getServletContext());
925         }
926
927         try {
928             logKitLoggerManager.contextualize(subcontext);
929
930             //Configure the logkit management
931
String JavaDoc logkitConfig = getInitParameter("logkit-config", "/WEB-INF/logkit.xconf");
932
933             // test if this is a qualified url
934
InputStream JavaDoc is = null;
935             if (logkitConfig.indexOf(':') == -1) {
936                 is = this.portletContext.getResourceAsStream(logkitConfig);
937                 if (is == null) is = new FileInputStream JavaDoc(logkitConfig);
938             } else {
939                 URL JavaDoc logkitURL = new URL JavaDoc(logkitConfig);
940                 is = logkitURL.openStream();
941             }
942             final DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
943             final Configuration conf = builder.build(is);
944             logKitLoggerManager.configure(conf);
945         } catch (Exception JavaDoc e) {
946             e.printStackTrace();
947         }
948
949         if (accesslogger != null) {
950             this.log = logKitLoggerManager.getLoggerForCategory(accesslogger);
951         } else {
952             this.log = logKitLoggerManager.getLoggerForCategory("cocoon");
953         }
954     }
955
956     protected Logger getLogger() {
957         return this.log;
958     }
959 }
960
Popular Tags