cocoon-cvs mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From dani...@apache.org
Subject svn commit: r418292 - in /cocoon/trunk/core/cocoon-core/src/main/java/org/apache/cocoon/servlet: RequestProcessor.java multipart/MultipartFilter.java
Date Fri, 30 Jun 2006 14:16:40 GMT
Author: danielf
Date: Fri Jun 30 07:16:40 2006
New Revision: 418292

URL: http://svn.apache.org/viewvc?rev=418292&view=rev
Log:
Factored out the multipart MIME handling in the RequestProcessor to a servlet filter.

Added:
    cocoon/trunk/core/cocoon-core/src/main/java/org/apache/cocoon/servlet/multipart/MultipartFilter.java
Modified:
    cocoon/trunk/core/cocoon-core/src/main/java/org/apache/cocoon/servlet/RequestProcessor.java

Modified: cocoon/trunk/core/cocoon-core/src/main/java/org/apache/cocoon/servlet/RequestProcessor.java
URL: http://svn.apache.org/viewvc/cocoon/trunk/core/cocoon-core/src/main/java/org/apache/cocoon/servlet/RequestProcessor.java?rev=418292&r1=418291&r2=418292&view=diff
==============================================================================
--- cocoon/trunk/core/cocoon-core/src/main/java/org/apache/cocoon/servlet/RequestProcessor.java
(original)
+++ cocoon/trunk/core/cocoon-core/src/main/java/org/apache/cocoon/servlet/RequestProcessor.java
Fri Jun 30 07:16:40 2006
@@ -15,7 +15,6 @@
  */
 package org.apache.cocoon.servlet;
 
-import java.io.File;
 import java.io.IOException;
 import java.util.HashMap;
 
@@ -40,8 +39,6 @@
 import org.apache.cocoon.environment.http.HttpContext;
 import org.apache.cocoon.environment.http.HttpEnvironment;
 import org.apache.cocoon.environment.internal.EnvironmentHelper;
-import org.apache.cocoon.servlet.multipart.MultipartHttpServletRequest;
-import org.apache.cocoon.servlet.multipart.RequestFactory;
 import org.apache.commons.lang.time.StopWatch;
 import org.springframework.beans.factory.BeanFactory;
 
@@ -68,12 +65,6 @@
 
     protected final String containerEncoding;
 
-    /**
-     * The RequestFactory is responsible for wrapping multipart-encoded
-     * forms and for handing the file payload of incoming requests
-     */
-    protected final RequestFactory requestFactory;
-
     /** The logger. */
     protected final Logger log;
 
@@ -98,12 +89,6 @@
         } else {
             this.containerEncoding = encoding;
         }
-        this.requestFactory = new RequestFactory(this.settings.isAutosaveUploads(),
-                                                 new File(this.settings.getUploadDirectory()),
-                                                 this.settings.isAllowOverwrite(),
-                                                 this.settings.isSilentlyRename(),
-                                                 this.settings.getMaxUploadSize(),
-                                                 this.containerEncoding);
         this.log = (Logger) this.cocoonBeanFactory.getBean(ProcessingUtil.LOGGER_ROLE);
         this.rootProcessor = (Processor)this.cocoonBeanFactory.getBean(Processor.ROLE);
         this.environmentContext = new HttpContext(this.servletContext);
@@ -113,7 +98,7 @@
      * Process the specified <code>HttpServletRequest</code> producing output
      * on the specified <code>HttpServletResponse</code>.
      */
-    public void service(HttpServletRequest req, HttpServletResponse res)
+    public void service(HttpServletRequest request, HttpServletResponse res)
     throws ServletException, IOException {        
         // used for timing the processing
         StopWatch stopWatch = new StopWatch();
@@ -124,25 +109,6 @@
             res.addHeader("X-Cocoon-Version", Constants.VERSION);
         }
 
-        // get the request (wrapped if contains multipart-form data)
-        HttpServletRequest request;
-        try{
-            if (this.settings.isEnableUploads()) {
-                request = requestFactory.getServletRequest(req);
-            } else {
-                request = req;
-            }
-        } catch (Exception e) {
-            if (getLogger().isErrorEnabled()) {
-                getLogger().error("Problem with Cocoon servlet", e);
-            }
-
-            manageException(req, res, null, null,
-                            HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
-                            "Problem in creating the Request", null, null, e);
-            return;
-        }
-
         // We got it... Process the request
         String uri = request.getServletPath();
         if (uri == null) {
@@ -195,119 +161,106 @@
         }
 
         try {
-            try {
-                if (this.process(env)) {
-                    contentType = env.getContentType();
-                } else {
-                    // We reach this when there is nothing in the processing change that
matches
-                    // the request. For example, no matcher matches.
-                    getLogger().fatalError("The Cocoon engine failed to process the request.");
-                    manageException(request, res, env, uri,
-                                    HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
-                                    "Request Processing Failed",
-                                    "Cocoon engine failed in process the request",
-                                    "The processing engine failed to process the request.
This could be due to lack of matching or bugs in the pipeline engine.",
-                                    null);
-                    return;
-                }
-            } catch (ResourceNotFoundException e) {
-                if (getLogger().isDebugEnabled()) {
-                    getLogger().warn(e.getMessage(), e);
-                } else if (getLogger().isWarnEnabled()) {
-                    getLogger().warn(e.getMessage());
-                }
-
-                manageException(request, res, env, uri,
-                                HttpServletResponse.SC_NOT_FOUND,
-                                "Resource Not Found",
-                                "Resource Not Found",
-                                "The requested resource \"" + request.getRequestURI() + "\"
could not be found",
-                                e);
-                return;
-
-            } catch (ConnectionResetException e) {
-                if (getLogger().isDebugEnabled()) {
-                    getLogger().debug(e.toString(), e);
-                } else if (getLogger().isWarnEnabled()) {
-                    getLogger().warn(e.toString());
-                }
-
-            } catch (IOException e) {
-                // Tomcat5 wraps SocketException into ClientAbortException which extends
IOException.
-                if (getLogger().isDebugEnabled()) {
-                    getLogger().debug(e.toString(), e);
-                } else if (getLogger().isWarnEnabled()) {
-                    getLogger().warn(e.toString());
-                }
-
-            } catch (Exception e) {
-                if (getLogger().isErrorEnabled()) {
-                    getLogger().error("Internal Cocoon Problem", e);
-                }
-
+            if (this.process(env)) {
+                contentType = env.getContentType();
+            } else {
+                // We reach this when there is nothing in the processing change that matches
+                // the request. For example, no matcher matches.
+                getLogger().fatalError("The Cocoon engine failed to process the request.");
                 manageException(request, res, env, uri,
                                 HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
-                                "Internal Server Error", null, null, e);
+                                "Request Processing Failed",
+                                "Cocoon engine failed in process the request",
+                                "The processing engine failed to process the request. This
could be due to lack of matching or bugs in the pipeline engine.",
+                                null);
                 return;
             }
+        } catch (ResourceNotFoundException e) {
+            if (getLogger().isDebugEnabled()) {
+                getLogger().warn(e.getMessage(), e);
+            } else if (getLogger().isWarnEnabled()) {
+                getLogger().warn(e.getMessage());
+            }
+
+            manageException(request, res, env, uri,
+                            HttpServletResponse.SC_NOT_FOUND,
+                            "Resource Not Found",
+                            "Resource Not Found",
+                            "The requested resource \"" + request.getRequestURI() + "\" could
not be found",
+                            e);
+            return;
 
-            stopWatch.stop();
-            String timeString = null;
-            if (getLogger().isInfoEnabled()) {
-                timeString = processTime(stopWatch.getTime());
-                getLogger().info("'" + uri + "' " + timeString);
+        } catch (ConnectionResetException e) {
+            if (getLogger().isDebugEnabled()) {
+                getLogger().debug(e.toString(), e);
+            } else if (getLogger().isWarnEnabled()) {
+                getLogger().warn(e.toString());
             }
 
-            if (contentType != null && contentType.equals("text/html")) {
-                String showTime = request.getParameter(Constants.SHOWTIME_PARAM);
-                boolean show = this.settings.isShowTime();
-                if (showTime != null) {
-                    show = !showTime.equalsIgnoreCase("no");
-                }
-                if (show) {
-                    if ( timeString == null ) {
-                        timeString = processTime(stopWatch.getTime());
-                    }
-                    boolean hide = this.settings.isHideShowTime();
-                    if (showTime != null) {
-                        hide = showTime.equalsIgnoreCase("hide");
-                    }
-                    ServletOutputStream out = res.getOutputStream();
-                    out.print((hide) ? "<!-- " : "<p>");
-                    out.print(timeString);
-                    out.println((hide) ? " -->" : "</p>");
-                }
+        } catch (IOException e) {
+            // Tomcat5 wraps SocketException into ClientAbortException which extends IOException.
+            if (getLogger().isDebugEnabled()) {
+                getLogger().debug(e.toString(), e);
+            } else if (getLogger().isWarnEnabled()) {
+                getLogger().warn(e.toString());
             }
-        } finally {
-            try {
-                if (request instanceof MultipartHttpServletRequest) {
-                    if (getLogger().isDebugEnabled()) {
-                        getLogger().debug("Deleting uploaded file(s).");
-                    }
-                    ((MultipartHttpServletRequest) request).cleanup();
-                }
-            } catch (IOException e) {
-                getLogger().error("Cocoon got an Exception while trying to cleanup the uploaded
files.", e);
+
+        } catch (Exception e) {
+            if (getLogger().isErrorEnabled()) {
+                getLogger().error("Internal Cocoon Problem", e);
             }
 
-            /*
-             * Servlet Specification 2.2, 6.5 Closure of Response Object:
-             *
-             *   A number of events can indicate that the servlet has provided all of the
-             *   content to satisfy the request and that the response object can be
-             *   considered to be closed. The events are:
-             *     o The termination of the service method of the servlet.
-             *     o When the amount of content specified in the setContentLength method
-             *       of the response has been written to the response.
-             *     o The sendError method is called.
-             *     o The sendRedirect method is called.
-             *   When a response is closed, all content in the response buffer, if any remains,
-             *   must be immediately flushed to the client.
-             *
-             * Due to the above, out.flush() and out.close() are not necessary, and sometimes
-             * (if sendError or sendRedirect were used) request may be already closed.
-             */
+            manageException(request, res, env, uri,
+                            HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
+                            "Internal Server Error", null, null, e);
+            return;
         }
+
+        stopWatch.stop();
+        String timeString = null;
+        if (getLogger().isInfoEnabled()) {
+            timeString = processTime(stopWatch.getTime());
+            getLogger().info("'" + uri + "' " + timeString);
+        }
+
+        if (contentType != null && contentType.equals("text/html")) {
+            String showTime = request.getParameter(Constants.SHOWTIME_PARAM);
+            boolean show = this.settings.isShowTime();
+            if (showTime != null) {
+                show = !showTime.equalsIgnoreCase("no");
+            }
+            if (show) {
+                if ( timeString == null ) {
+                    timeString = processTime(stopWatch.getTime());
+                }
+                boolean hide = this.settings.isHideShowTime();
+                if (showTime != null) {
+                    hide = showTime.equalsIgnoreCase("hide");
+                }
+                ServletOutputStream out = res.getOutputStream();
+                out.print((hide) ? "<!-- " : "<p>");
+                out.print(timeString);
+                out.println((hide) ? " -->" : "</p>");
+            }
+        }
+        
+        /*
+         * Servlet Specification 2.2, 6.5 Closure of Response Object:
+         *
+         *   A number of events can indicate that the servlet has provided all of the
+         *   content to satisfy the request and that the response object can be
+         *   considered to be closed. The events are:
+         *     o The termination of the service method of the servlet.
+         *     o When the amount of content specified in the setContentLength method
+         *       of the response has been written to the response.
+         *     o The sendError method is called.
+         *     o The sendRedirect method is called.
+         *   When a response is closed, all content in the response buffer, if any remains,
+         *   must be immediately flushed to the client.
+         *
+         * Due to the above, out.flush() and out.close() are not necessary, and sometimes
+         * (if sendError or sendRedirect were used) request may be already closed.
+         */
     }
 
     protected void manageException(HttpServletRequest req, HttpServletResponse res, Environment
env,

Added: cocoon/trunk/core/cocoon-core/src/main/java/org/apache/cocoon/servlet/multipart/MultipartFilter.java
URL: http://svn.apache.org/viewvc/cocoon/trunk/core/cocoon-core/src/main/java/org/apache/cocoon/servlet/multipart/MultipartFilter.java?rev=418292&view=auto
==============================================================================
--- cocoon/trunk/core/cocoon-core/src/main/java/org/apache/cocoon/servlet/multipart/MultipartFilter.java
(added)
+++ cocoon/trunk/core/cocoon-core/src/main/java/org/apache/cocoon/servlet/multipart/MultipartFilter.java
Fri Jun 30 07:16:40 2006
@@ -0,0 +1,181 @@
+/*
+ * Copyright 2006 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cocoon.servlet.multipart;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.HashMap;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.avalon.framework.logger.Logger;
+import org.apache.cocoon.ProcessingUtil;
+import org.apache.cocoon.components.notification.DefaultNotifyingBuilder;
+import org.apache.cocoon.components.notification.Notifier;
+import org.apache.cocoon.components.notification.Notifying;
+import org.apache.cocoon.core.Settings;
+import org.apache.cocoon.environment.Environment;
+import org.springframework.beans.factory.BeanFactory;
+
+/**
+ * Servlet filter for handling multi part MIME uploads
+ * 
+ * @version $Id$
+ */
+public class MultipartFilter implements Filter{
+
+    /**
+     * The RequestFactory is responsible for wrapping multipart-encoded
+     * forms and for handing the file payload of incoming requests
+     */
+    protected RequestFactory requestFactory;
+
+    /** The logger. */
+    protected Logger log;
+
+    /** Root Cocoon Bean Factory. */
+    protected BeanFactory cocoonBeanFactory;
+
+    /** The root settings. */
+    protected Settings settings;
+
+    /* (non-Javadoc)
+     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
+     */
+    public void init(FilterConfig config) throws ServletException {
+        String containerEncoding;
+        ServletContext servletContext = config.getServletContext();
+        this.cocoonBeanFactory = (BeanFactory) servletContext.getAttribute(ProcessingUtil.CONTAINER_CONTEXT_ATTR_NAME);
+        this.settings = (Settings) this.cocoonBeanFactory.getBean(ProcessingUtil.SETTINGS_ROLE);
+        final String encoding = servletContext.getInitParameter("container-encoding");
+        if ( encoding == null ) {
+            containerEncoding = "ISO-8859-1";
+        } else {
+            containerEncoding = encoding;
+        }
+        this.requestFactory = new RequestFactory(this.settings.isAutosaveUploads(),
+                                                 new File(this.settings.getUploadDirectory()),
+                                                 this.settings.isAllowOverwrite(),
+                                                 this.settings.isSilentlyRename(),
+                                                 this.settings.getMaxUploadSize(),
+                                                 containerEncoding);
+        this.log = (Logger) this.cocoonBeanFactory.getBean(ProcessingUtil.LOGGER_ROLE);
+    }
+
+    /* (non-Javadoc)
+     * @see javax.servlet.Filter#destroy()
+     */
+    public void destroy() {
+    }
+
+    /* (non-Javadoc)
+     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
javax.servlet.FilterChain)
+     */
+    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
throws IOException, ServletException {
+        // get the request (wrapped if contains multipart-form data)
+        HttpServletRequest request = (HttpServletRequest) req;
+        HttpServletResponse response = (HttpServletResponse) res;
+        try{
+            request = this.requestFactory.getServletRequest(request);
+            filterChain.doFilter(request, response);
+        } catch (Exception e) {
+            if (getLogger().isErrorEnabled()) {
+                getLogger().error("Problem with Cocoon servlet", e);
+            }
+
+            manageException(request, response, null, null,
+                            HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
+                            "Problem in creating the Request", null, null, e);
+        } finally {
+            try {
+                if (request instanceof MultipartHttpServletRequest) {
+                    if (getLogger().isDebugEnabled()) {
+                        getLogger().debug("Deleting uploaded file(s).");
+                    }
+                    ((MultipartHttpServletRequest) request).cleanup();
+                }
+            } catch (IOException e) {
+                getLogger().error("Cocoon got an Exception while trying to cleanup the uploaded
files.", e);
+            }
+        }
+    }
+
+    // FIXME: This method is a copy from the RequestProcessor, it should be factored out
+    // to some utility class. 
+    protected void manageException(HttpServletRequest req, HttpServletResponse res, Environment
env,
+                                   String uri, int errorStatus,
+                                   String title, String message, String description,
+                                   Exception e)
+    throws IOException {
+        if (this.settings.isManageExceptions()) {
+            if (env != null) {
+                env.tryResetResponse();
+            } else {
+                res.reset();
+            }
+
+            String type = Notifying.FATAL_NOTIFICATION;
+            HashMap extraDescriptions = null;
+
+            if (errorStatus == HttpServletResponse.SC_NOT_FOUND) {
+                type = "resource-not-found";
+                // Do not show the exception stacktrace for such common errors.
+                e = null;
+            } else {
+                extraDescriptions = new HashMap(2);
+                extraDescriptions.put(Notifying.EXTRA_REQUESTURI, req.getRequestURI());
+                if (uri != null) {
+                     extraDescriptions.put("Request URI", uri);
+                }
+
+                // Do not show exception stack trace when log level is WARN or above. Show
only message.
+                if (!getLogger().isInfoEnabled()) {
+                    Throwable t = DefaultNotifyingBuilder.getRootCause(e);
+                    if (t != null) extraDescriptions.put(Notifying.EXTRA_CAUSE, t.getMessage());
+                    e = null;
+                }
+            }
+
+            Notifying n = new DefaultNotifyingBuilder().build(this,
+                                                              e,
+                                                              type,
+                                                              title,
+                                                              "Cocoon Servlet",
+                                                              message,
+                                                              description,
+                                                              extraDescriptions);
+
+            res.setContentType("text/html");
+            res.setStatus(errorStatus);
+            Notifier.notify(n, res.getOutputStream(), "text/html");
+        } else {
+            res.sendError(errorStatus, title);
+            res.flushBuffer();
+        }
+    }
+
+    protected Logger getLogger() {
+        return this.log;
+    }
+}



Mime
View raw message