View Javadoc

1   /**
2    * This file Copyright (c) 2010-2013 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.cms.util;
35  
36  import java.util.Enumeration;
37  import java.util.LinkedHashMap;
38  import javax.servlet.FilterConfig;
39  import javax.servlet.ServletConfig;
40  import javax.servlet.ServletRequest;
41  import javax.servlet.ServletRequestWrapper;
42  import javax.servlet.http.HttpServletRequest;
43  
44  import org.apache.commons.lang.StringUtils;
45  
46  /**
47   * Utility methods for operations related to Servlet API.
48   *
49   * @author tmattsson
50   * @see info.magnolia.cms.util.RequestHeaderUtil
51   */
52  public abstract class ServletUtil {
53  
54      public static final String FORWARD_REQUEST_URI_ATTRIBUTE = "javax.servlet.forward.request_uri";
55      public static final String FORWARD_QUERY_STRING_ATTRIBUTE = "javax.servlet.forward.query_string";
56  
57      public static final String INCLUDE_REQUEST_URI_ATTRIBUTE = "javax.servlet.include.request_uri";
58  
59      public static final String ERROR_REQUEST_STATUS_CODE_ATTRIBUTE = "javax.servlet.error.status_code";
60  
61      /**
62       * Returns the init parameters for a {@link javax.servlet.ServletConfig} object as a Map, preserving the order in which they are exposed
63       * by the {@link javax.servlet.ServletConfig} object.
64       */
65      public static LinkedHashMap<String, String> initParametersToMap(ServletConfig config) {
66          LinkedHashMap<String, String> initParameters = new LinkedHashMap<String, String>();
67          Enumeration parameterNames = config.getInitParameterNames();
68          while (parameterNames.hasMoreElements()) {
69              String parameterName = (String) parameterNames.nextElement();
70              initParameters.put(parameterName, config.getInitParameter(parameterName));
71          }
72          return initParameters;
73      }
74  
75      /**
76       * Returns the init parameters for a {@link javax.servlet.FilterConfig} object as a Map, preserving the order in which they are exposed
77       * by the {@link javax.servlet.FilterConfig} object.
78       */
79      public static LinkedHashMap<String, String> initParametersToMap(FilterConfig config) {
80          LinkedHashMap<String, String> initParameters = new LinkedHashMap<String, String>();
81          Enumeration parameterNames = config.getInitParameterNames();
82          while (parameterNames.hasMoreElements()) {
83              String parameterName = (String) parameterNames.nextElement();
84              initParameters.put(parameterName, config.getInitParameter(parameterName));
85          }
86          return initParameters;
87      }
88  
89      /**
90       * Finds a request wrapper object inside the chain of request wrappers.
91       */
92      public static <T extends ServletRequest> T getWrappedRequest(ServletRequest request, Class<T> clazz) {
93          while (request != null) {
94              if (clazz.isAssignableFrom(request.getClass())) {
95                  return (T) request;
96              }
97              request = (request instanceof ServletRequestWrapper) ? ((ServletRequestWrapper) request).getRequest() : null;
98          }
99          return null;
100     }
101 
102     /**
103      * Returns true if the request has a content type that indicates that is a multipart request.
104      */
105     public static boolean isMultipart(HttpServletRequest request) {
106         String contentType = request.getContentType();
107         return contentType != null && contentType.toLowerCase().startsWith("multipart/");
108     }
109 
110     /**
111      * Returns true if the request is currently processing a forward operation. This method will return false after
112      * an include operation has begun and will return true after that include operations has completed.
113      */
114     public static boolean isForward(HttpServletRequest request) {
115         return request.getAttribute(FORWARD_REQUEST_URI_ATTRIBUTE) != null && !isInclude(request);
116     }
117 
118     /**
119      * Returns true if the request is currently processing an include operation.
120      */
121     public static boolean isInclude(HttpServletRequest request) {
122         return request.getAttribute(INCLUDE_REQUEST_URI_ATTRIBUTE) != null;
123     }
124 
125     /**
126      * Returns true if the request is rendering an error page, either due to a call to sendError() or an exception
127      * being thrown in a filter or a servlet that reached the container. Will return true also after an include() or
128      * forward() while rendering the error page.
129      */
130     public static boolean isError(HttpServletRequest request) {
131         return request.getAttribute(ERROR_REQUEST_STATUS_CODE_ATTRIBUTE) != null;
132     }
133 
134     /**
135      * Returns the dispatcher type of the request, the dispatcher type is defined to be identical to the semantics of
136      * filter mappings in web.xml.
137      */
138     public static DispatcherType getDispatcherType(HttpServletRequest request) {
139         // The order of these tests is important.
140         if (request.getAttribute(INCLUDE_REQUEST_URI_ATTRIBUTE) != null) {
141             return DispatcherType.INCLUDE;
142         }
143         if (request.getAttribute(FORWARD_REQUEST_URI_ATTRIBUTE) != null) {
144             return DispatcherType.FORWARD;
145         }
146         if (request.getAttribute(ERROR_REQUEST_STATUS_CODE_ATTRIBUTE) != null) {
147             return DispatcherType.ERROR;
148         }
149         return DispatcherType.REQUEST;
150     }
151 
152     /**
153      * Returns the original request uri. The If the request has been forwarded it finds the original request uri from
154      * request attributes. The returned uri is not decoded.
155      */
156     public static String getOriginalRequestURI(HttpServletRequest request) {
157         if (request.getAttribute(FORWARD_REQUEST_URI_ATTRIBUTE) != null) {
158             return (String) request.getAttribute(FORWARD_REQUEST_URI_ATTRIBUTE);
159         }
160         return request.getRequestURI();
161     }
162 
163     /**
164      * Returns the original request url. If the request has been forwarded it reconstructs the url from  request
165      * attributes. The returned url is not decoded.
166      */
167     public static String getOriginalRequestURLIncludingQueryString(HttpServletRequest request) {
168         if (request.getAttribute(FORWARD_REQUEST_URI_ATTRIBUTE) != null) {
169             StringBuilder builder = new StringBuilder();
170 
171             String scheme = request.getScheme();
172             builder.append(scheme).append("://").append(request.getServerName());
173 
174             int port = request.getServerPort();
175             if ((scheme.equalsIgnoreCase("http") && port == 80) || (scheme.equalsIgnoreCase("https") && port == 443)) {
176                 // adding port is not necessary
177             } else {
178                 builder.append(":").append(port);
179             }
180 
181             String requestUri = (String) request.getAttribute(FORWARD_REQUEST_URI_ATTRIBUTE);
182             builder.append(requestUri);
183 
184             String queryString = (String) request.getAttribute(FORWARD_QUERY_STRING_ATTRIBUTE);
185             if (StringUtils.isNotEmpty(queryString)) {
186                 builder.append("?").append(queryString);
187             }
188 
189             return builder.toString();
190         }
191         StringBuilder builder = new StringBuilder();
192         builder.append(request.getRequestURL());
193         String queryString = request.getQueryString();
194         if (StringUtils.isNotEmpty(queryString)) {
195             builder.append("?").append(queryString);
196         }
197         return builder.toString();
198     }
199 
200     /**
201      * Returns the request uri for the request. If the request is an include it will return the uri being included. The
202      * returned uri is not decoded.
203      */
204     public static String getRequestUri(HttpServletRequest request) {
205         if (request.getAttribute(INCLUDE_REQUEST_URI_ATTRIBUTE) != null)
206             return (String) request.getAttribute(INCLUDE_REQUEST_URI_ATTRIBUTE);
207         return request.getRequestURI();
208     }
209 }