This project has retired. For details please refer to its Attic page.
HttpUtils xref

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   * http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.chemistry.opencmis.server.shared;
20  
21  import java.io.File;
22  import java.lang.reflect.Method;
23  import java.math.BigInteger;
24  import java.util.Map;
25  
26  import javax.servlet.ServletContext;
27  import javax.servlet.http.HttpServletRequest;
28  import javax.servlet.http.HttpServletResponse;
29  
30  import org.apache.chemistry.opencmis.commons.exceptions.CmisInvalidArgumentException;
31  import org.apache.chemistry.opencmis.commons.exceptions.CmisRuntimeException;
32  import org.apache.chemistry.opencmis.commons.server.CallContext;
33  import org.apache.chemistry.opencmis.server.impl.CallContextImpl;
34  
35  /**
36   * Utility methods that are used by the AtomPub and Browser binding.
37   */
38  public class HttpUtils {
39  
40      private HttpUtils() {
41      }
42  
43      /**
44       * Creates a {@link CallContext} object from a servlet request.
45       */
46      public static CallContext createContext(HttpServletRequest request, HttpServletResponse response,
47              ServletContext servletContext, String binding, CallContextHandler callContextHandler, File tempDir,
48              int memoryThreshold) {
49          String[] pathFragments = splitPath(request);
50  
51          String repositoryId = null;
52          if (pathFragments.length > 0) {
53              repositoryId = pathFragments[0];
54          }
55  
56          CallContextImpl context = new CallContextImpl(binding, repositoryId, true);
57  
58          // call call context handler
59          if (callContextHandler != null) {
60              Map<String, String> callContextMap = callContextHandler.getCallContextMap(request);
61              if (callContextMap != null) {
62                  for (Map.Entry<String, String> e : callContextMap.entrySet()) {
63                      context.put(e.getKey(), e.getValue());
64                  }
65              }
66          }
67  
68          // servlet context and HTTP servlet request and response
69          context.put(CallContext.SERVLET_CONTEXT, servletContext);
70          context.put(CallContext.HTTP_SERVLET_REQUEST, request);
71          context.put(CallContext.HTTP_SERVLET_RESPONSE, response);
72  
73          // temp files
74          context.put(CallContext.TEMP_DIR, tempDir);
75          context.put(CallContext.MEMORY_THRESHOLD, memoryThreshold);
76  
77          // decode range
78          String rangeHeader = request.getHeader("Range");
79          if (rangeHeader != null) {
80              rangeHeader = rangeHeader.trim();
81              BigInteger offset = null;
82              BigInteger length = null;
83  
84              int eq = rangeHeader.indexOf('=');
85              int ds = rangeHeader.indexOf('-');
86              if ((eq > 0) && (ds > eq)) {
87                  String offsetStr = rangeHeader.substring(eq + 1, ds).trim();
88                  if (offsetStr.length() > 0) {
89                      offset = new BigInteger(offsetStr);
90                  }
91  
92                  if (ds < rangeHeader.length()) {
93                      String lengthStr = rangeHeader.substring(ds + 1).trim();
94                      if (lengthStr.length() > 0) {
95                          if (offset == null) {
96                              length = new BigInteger(lengthStr);
97                          } else {
98                              length = (new BigInteger(lengthStr)).subtract(offset);
99                          }
100                     }
101 
102                     if (offset != null) {
103                         context.put(CallContext.OFFSET, offset);
104                     }
105                     if (length != null) {
106                         context.put(CallContext.LENGTH, length);
107                     }
108                 }
109             }
110         }
111 
112         // get locale
113         String acceptLanguage = request.getHeader("Accept-Language");
114         if (acceptLanguage != null) {
115             String[] locale = acceptLanguage.split("-");
116             context.put(CallContext.LOCALE_ISO639_LANGUAGE, locale[0].trim());
117             if (locale.length > 1) {
118                 int x = locale[1].indexOf(',');
119                 if (x == -1) {
120                     context.put(CallContext.LOCALE_ISO3166_COUNTRY, locale[1].trim());
121                 } else {
122                     context.put(CallContext.LOCALE_ISO3166_COUNTRY, locale[1].substring(0, x).trim());
123                 }
124             }
125         }
126 
127         return context;
128     }
129 
130     /**
131      * Splits the path into its fragments.
132      */
133     public static String[] splitPath(HttpServletRequest request) {
134         String p = request.getPathInfo();
135         if (p == null) {
136             return new String[0];
137         }
138 
139         return p.substring(1).split("/");
140     }
141 
142     // -------------------------------------------------------------------------
143     // --- parameters ---
144     // -------------------------------------------------------------------------
145 
146     /**
147      * Extracts a string parameter.
148      */
149     @SuppressWarnings("unchecked")
150     public static String getStringParameter(HttpServletRequest request, String name) {
151         if (name == null) {
152             return null;
153         }
154 
155         Map<String, String[]> parameters = (Map<String, String[]>) request.getParameterMap();
156         for (Map.Entry<String, String[]> parameter : parameters.entrySet()) {
157             if (name.equalsIgnoreCase(parameter.getKey())) {
158                 if (parameter.getValue() == null) {
159                     return null;
160                 }
161                 return parameter.getValue()[0];
162             }
163         }
164 
165         return null;
166     }
167 
168     /**
169      * Extracts a boolean parameter (with default).
170      */
171     public static boolean getBooleanParameter(HttpServletRequest request, String name, boolean def) {
172         String value = getStringParameter(request, name);
173         if ((value == null) || (value.length() == 0)) {
174             return def;
175         }
176 
177         return Boolean.valueOf(value);
178     }
179 
180     /**
181      * Extracts a boolean parameter.
182      */
183     public static Boolean getBooleanParameter(HttpServletRequest request, String name) {
184         String value = getStringParameter(request, name);
185         if ((value == null) || (value.length() == 0)) {
186             return null;
187         }
188 
189         return Boolean.valueOf(value);
190     }
191 
192     /**
193      * Extracts an integer parameter (with default).
194      */
195     public static BigInteger getBigIntegerParameter(HttpServletRequest request, String name, long def) {
196         BigInteger result = getBigIntegerParameter(request, name);
197         if (result == null) {
198             result = BigInteger.valueOf(def);
199         }
200 
201         return result;
202     }
203 
204     /**
205      * Extracts an integer parameter.
206      */
207     public static BigInteger getBigIntegerParameter(HttpServletRequest request, String name) {
208         String value = getStringParameter(request, name);
209         if ((value == null) || (value.length() == 0)) {
210             return null;
211         }
212 
213         try {
214             return new BigInteger(value);
215         } catch (Exception e) {
216             throw new CmisInvalidArgumentException("Invalid parameter '" + name + "'!");
217         }
218     }
219 
220     /**
221      * Extracts an enum parameter.
222      */
223     @SuppressWarnings("unchecked")
224     public static <T> T getEnumParameter(HttpServletRequest request, String name, Class<T> clazz) {
225         String value = getStringParameter(request, name);
226         if ((value == null) || (value.length() == 0)) {
227             return null;
228         }
229 
230         try {
231             Method m = clazz.getMethod("fromValue", new Class[] { String.class });
232             return (T) m.invoke(null, new Object[] { value });
233         } catch (Exception e) {
234             if (e instanceof IllegalArgumentException) {
235                 throw new CmisInvalidArgumentException("Invalid parameter '" + name + "'!");
236             }
237 
238             throw new CmisRuntimeException(e.getMessage(), e);
239         }
240     }
241 }