View Javadoc
1   /**
2    * This file Copyright (c) 2010-2018 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 java.util.Locale;
39  
40  import javax.servlet.FilterConfig;
41  import javax.servlet.ServletConfig;
42  import javax.servlet.ServletRequest;
43  import javax.servlet.ServletRequestWrapper;
44  import javax.servlet.http.HttpServletRequest;
45  
46  import org.apache.commons.lang3.StringUtils;
47  
48  /**
49   * Utility methods for operations related to Servlet API.
50   *
51   * @see info.magnolia.cms.util.RequestHeaderUtil
52   */
53  public abstract class ServletUtil {
54  
55      public static final String FORWARD_REQUEST_URI_ATTRIBUTE = "javax.servlet.forward.request_uri";
56      public static final String FORWARD_QUERY_STRING_ATTRIBUTE = "javax.servlet.forward.query_string";
57  
58      public static final String INCLUDE_REQUEST_URI_ATTRIBUTE = "javax.servlet.include.request_uri";
59      public static final String INCLUDE_CONTEXT_PATH_ATTRIBUTE = "javax.servlet.include.context_path";
60  
61      public static final String ERROR_REQUEST_STATUS_CODE_ATTRIBUTE = "javax.servlet.error.status_code";
62  
63      /**
64       * Returns the init parameters for a {@link javax.servlet.ServletConfig} object as a Map, preserving the order in which they are exposed
65       * by the {@link javax.servlet.ServletConfig} object.
66       */
67      public static LinkedHashMap<String, String> initParametersToMap(ServletConfig config) {
68          LinkedHashMap<String, String> initParameters = new LinkedHashMap<String, String>();
69          Enumeration parameterNames = config.getInitParameterNames();
70          while (parameterNames.hasMoreElements()) {
71              String parameterName = (String) parameterNames.nextElement();
72              initParameters.put(parameterName, config.getInitParameter(parameterName));
73          }
74          return initParameters;
75      }
76  
77      /**
78       * Returns the init parameters for a {@link javax.servlet.FilterConfig} object as a Map, preserving the order in which they are exposed
79       * by the {@link javax.servlet.FilterConfig} object.
80       */
81      public static LinkedHashMap<String, String> initParametersToMap(FilterConfig config) {
82          LinkedHashMap<String, String> initParameters = new LinkedHashMap<String, String>();
83          Enumeration parameterNames = config.getInitParameterNames();
84          while (parameterNames.hasMoreElements()) {
85              String parameterName = (String) parameterNames.nextElement();
86              initParameters.put(parameterName, config.getInitParameter(parameterName));
87          }
88          return initParameters;
89      }
90  
91      /**
92       * Finds a request wrapper object inside the chain of request wrappers.
93       */
94      public static <T extends ServletRequest> T getWrappedRequest(ServletRequest request, Class<T> clazz) {
95          while (request != null) {
96              if (clazz.isAssignableFrom(request.getClass())) {
97                  return (T) request;
98              }
99              request = (request instanceof ServletRequestWrapper) ? ((ServletRequestWrapper) request).getRequest() : null;
100         }
101         return null;
102     }
103 
104     /**
105      * Returns true if the request has a content type that indicates that is a multipart request.
106      */
107     public static boolean isMultipart(HttpServletRequest request) {
108         String contentType = request.getContentType();
109         return contentType != null && contentType.toLowerCase(Locale.ROOT).startsWith("multipart/");
110     }
111 
112     /**
113      * Returns true if the request is currently processing a forward operation. This method will return false after
114      * an include operation has begun and will return true after that include operations has completed.
115      */
116     public static boolean isForward(HttpServletRequest request) {
117         return request.getAttribute(FORWARD_REQUEST_URI_ATTRIBUTE) != null && !isInclude(request);
118     }
119 
120     /**
121      * Returns true if the request is currently processing an include operation.
122      */
123     public static boolean isInclude(HttpServletRequest request) {
124         return request.getAttribute(INCLUDE_REQUEST_URI_ATTRIBUTE) != null;
125     }
126 
127     /**
128      * Returns true if the request is rendering an error page, either due to a call to sendError() or an exception
129      * being thrown in a filter or a servlet that reached the container. Will return true also after an include() or
130      * forward() while rendering the error page.
131      */
132     public static boolean isError(HttpServletRequest request) {
133         return request.getAttribute(ERROR_REQUEST_STATUS_CODE_ATTRIBUTE) != null;
134     }
135 
136     /**
137      * Returns the dispatcher type of the request, the dispatcher type is defined to be identical to the semantics of
138      * filter mappings in web.xml.
139      */
140     public static DispatcherType getDispatcherType(HttpServletRequest request) {
141         // The order of these tests is important.
142         if (request.getAttribute(INCLUDE_REQUEST_URI_ATTRIBUTE) != null) {
143             return DispatcherType.INCLUDE;
144         }
145         if (request.getAttribute(FORWARD_REQUEST_URI_ATTRIBUTE) != null) {
146             return DispatcherType.FORWARD;
147         }
148         if (request.getAttribute(ERROR_REQUEST_STATUS_CODE_ATTRIBUTE) != null) {
149             return DispatcherType.ERROR;
150         }
151         return DispatcherType.REQUEST;
152     }
153 
154     /**
155      * Returns the original request uri. The If the request has been forwarded it finds the original request uri from
156      * request attributes. The returned uri is not decoded.
157      */
158     public static String getOriginalRequestURI(HttpServletRequest request) {
159         String uri = (String) request.getAttribute(FORWARD_REQUEST_URI_ATTRIBUTE);
160         if (uri == null) {
161             uri = request.getRequestURI();
162         }
163         return stripPathParameters(uri);
164     }
165 
166     /**
167      * Returns the original request url. If the request has been forwarded it reconstructs the url from  request
168      * attributes. The returned url is not decoded.
169      */
170     public static String getOriginalRequestURLIncludingQueryString(HttpServletRequest request) {
171         if (request.getAttribute(FORWARD_REQUEST_URI_ATTRIBUTE) != null) {
172             StringBuilder builder = new StringBuilder();
173 
174             String scheme = request.getScheme();
175             builder.append(scheme).append("://").append(request.getServerName());
176 
177             int port = request.getServerPort();
178             if ((scheme.equalsIgnoreCase("http") && port == 80) || (scheme.equalsIgnoreCase("https") && port == 443)) {
179                 // adding port is not necessary
180             } else {
181                 builder.append(":").append(port);
182             }
183 
184             String requestUri = (String) request.getAttribute(FORWARD_REQUEST_URI_ATTRIBUTE);
185             builder.append(requestUri);
186 
187             String queryString = (String) request.getAttribute(FORWARD_QUERY_STRING_ATTRIBUTE);
188             if (StringUtils.isNotEmpty(queryString)) {
189                 builder.append("?").append(queryString);
190             }
191 
192             return builder.toString();
193         }
194         StringBuilder builder = new StringBuilder();
195         builder.append(request.getRequestURL());
196         String queryString = request.getQueryString();
197         if (StringUtils.isNotEmpty(queryString)) {
198             builder.append("?").append(queryString);
199         }
200         return builder.toString();
201     }
202 
203     /**
204      * Returns the request uri for the request. If the request is an include it will return the uri being included. The
205      * returned uri is not decoded.
206      */
207     public static String getRequestUri(HttpServletRequest request) {
208         String uri = (String) request.getAttribute(INCLUDE_REQUEST_URI_ATTRIBUTE);
209         if (uri == null) {
210             uri = request.getRequestURI();
211         }
212         return stripPathParameters(uri);
213     }
214 
215     /**
216      * Strips path parameters from a URI. Path parameters are mentioned in
217      * <a href="http://tools.ietf.org/html/rfc3986#section-3.3">RFC-3986 section 3.3</a> but not clearly defined. The
218      * most common case for Java web applications is the <code>JSESSIONID</code> path parameter.
219      */
220     public static String stripPathParameters(String uri) {
221         int semicolonIndex = uri.indexOf(';');
222         return semicolonIndex != -1 ? uri.substring(0, semicolonIndex) : uri;
223     }
224 
225     /**
226      * Returns the current path relative to the context path, the current path is the path used in the latest forward or
227      * include dispatch. The returned path is not decoded.
228      */
229     public static String getContextRelativePath(HttpServletRequest request) {
230         String uri = getRequestUri(request);
231         String contextPath = getContextPath(request);
232         // The requestUri should always start with the context path
233         if (uri.startsWith(contextPath + "/")) {
234             return uri.substring(contextPath.length());
235         }
236         return uri;
237     }
238 
239     public static String getContextPath(HttpServletRequest request) {
240         String contextPath = (String) request.getAttribute(INCLUDE_CONTEXT_PATH_ATTRIBUTE);
241         if (contextPath == null) {
242             contextPath = request.getContextPath();
243         }
244         // Should not be the case but is in Jetty
245         if ("/".equals(contextPath)) {
246             contextPath = "";
247         }
248         return contextPath;
249     }
250 }