001: /*
002: * $Id: UtilHttp.java,v 1.10 2003/12/13 17:11:38 ajzeneski Exp $
003: *
004: * Copyright (c) 2001, 2002 The Open For Business Project - www.ofbiz.org
005: *
006: * Permission is hereby granted, free of charge, to any person obtaining a
007: * copy of this software and associated documentation files (the "Software"),
008: * to deal in the Software without restriction, including without limitation
009: * the rights to use, copy, modify, merge, publish, distribute, sublicense,
010: * and/or sell copies of the Software, and to permit persons to whom the
011: * Software is furnished to do so, subject to the following conditions:
012: *
013: * The above copyright notice and this permission notice shall be included
014: * in all copies or substantial portions of the Software.
015: *
016: * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
017: * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
018: * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
019: * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
020: * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
021: * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
022: * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
023: */
024: package org.ofbiz.base.util;
025:
026: import java.io.BufferedInputStream;
027: import java.io.BufferedOutputStream;
028: import java.io.ByteArrayInputStream;
029: import java.io.IOException;
030: import java.io.InputStream;
031: import java.io.OutputStream;
032: import java.io.UnsupportedEncodingException;
033: import java.net.FileNameMap;
034: import java.net.URLConnection;
035: import java.net.URLEncoder;
036: import java.util.*;
037:
038: import javax.servlet.http.HttpServletRequest;
039: import javax.servlet.http.HttpServletResponse;
040: import javax.servlet.http.HttpSession;
041:
042: /**
043: * HttpUtil - Misc TTP Utility Functions
044: *
045: * @author <a href="mailto:jaz@ofbiz.org">Andy Zeneski</a>
046: * @author <a href="mailto:jonesde@ofbiz.org">David E. Jones</a>
047: * @version $Revision: 1.10 $
048: * @since 2.1
049: */
050: public class UtilHttp {
051:
052: public static final String module = UtilHttp.class.getName();
053:
054: /**
055: * Create a map from an HttpServletRequest object
056: * @return The resulting Map
057: */
058: public static Map getParameterMap(HttpServletRequest request) {
059: Map paramMap = new OrderedMap();
060: // first add in all path info parameters /~name1=value1/~name2=value2/
061: String pathInfoStr = request.getPathInfo();
062:
063: if (pathInfoStr != null && pathInfoStr.length() > 0) {
064: // make sure string ends with a trailing '/' so we get all values
065: if (!pathInfoStr.endsWith("/"))
066: pathInfoStr += "/";
067:
068: int current = pathInfoStr.indexOf('/');
069: int last = current;
070: while ((current = pathInfoStr.indexOf('/', last + 1)) != -1) {
071: String element = pathInfoStr.substring(last + 1,
072: current);
073: last = current;
074: if (element.charAt(0) == '~'
075: && element.indexOf('=') > -1) {
076: String name = element.substring(1, element
077: .indexOf('='));
078: String value = element.substring(element
079: .indexOf('=') + 1);
080: paramMap.put(name, value);
081: }
082: }
083: }
084:
085: // now add all the actual parameters; these take priority
086: java.util.Enumeration e = request.getParameterNames();
087: while (e.hasMoreElements()) {
088: String name = (String) e.nextElement();
089: paramMap.put(name, request.getParameter(name));
090: }
091: return paramMap;
092: }
093:
094: public static Map makeParamMapWithPrefix(
095: HttpServletRequest request, String prefix, String suffix) {
096: Map paramMap = new HashMap();
097: Enumeration parameterNames = request.getParameterNames();
098: while (parameterNames.hasMoreElements()) {
099: String parameterName = (String) parameterNames
100: .nextElement();
101: if (parameterName.startsWith(prefix)) {
102: if (suffix != null && suffix.length() > 0) {
103: if (parameterName.endsWith(suffix)) {
104: String key = parameterName.substring(prefix
105: .length(), parameterName.length()
106: - (suffix.length() - 1));
107: String value = request
108: .getParameter(parameterName);
109: paramMap.put(key, value);
110: }
111: } else {
112: String key = parameterName.substring(prefix
113: .length());
114: String value = request.getParameter(parameterName);
115: paramMap.put(key, value);
116: }
117: }
118: }
119: return paramMap;
120: }
121:
122: public static List makeParamListWithSuffix(
123: HttpServletRequest request, String suffix, String prefix) {
124: List paramList = new ArrayList();
125: Enumeration parameterNames = request.getParameterNames();
126: while (parameterNames.hasMoreElements()) {
127: String parameterName = (String) parameterNames
128: .nextElement();
129: if (parameterName.endsWith(suffix)) {
130: if (prefix != null && prefix.length() > 0) {
131: if (parameterName.startsWith(prefix)) {
132: String value = request
133: .getParameter(parameterName);
134: paramList.add(value);
135: }
136: } else {
137: String value = request.getParameter(parameterName);
138: paramList.add(value);
139: }
140: }
141: }
142: return paramList;
143: }
144:
145: /**
146: * Given a request, returns the application name or "root" if deployed on root
147: * @param request An HttpServletRequest to get the name info from
148: * @return String
149: */
150: public static String getApplicationName(HttpServletRequest request) {
151: String appName = "root";
152: if (request.getContextPath().length() > 1) {
153: appName = request.getContextPath().substring(1);
154: }
155: return appName;
156: }
157:
158: /**
159: * Put request parameters in request object as attributes.
160: * @param request
161: */
162: public static void parametersToAttributes(HttpServletRequest request) {
163: java.util.Enumeration e = request.getParameterNames();
164: while (e.hasMoreElements()) {
165: String name = (String) e.nextElement();
166: request.setAttribute(name, request.getParameter(name));
167: }
168: }
169:
170: public static StringBuffer getServerRootUrl(
171: HttpServletRequest request) {
172: StringBuffer requestUrl = new StringBuffer();
173: requestUrl.append(request.getScheme());
174: requestUrl.append("://" + request.getServerName());
175: if (request.getServerPort() != 80
176: && request.getServerPort() != 443)
177: requestUrl.append(":" + request.getServerPort());
178: return requestUrl;
179: }
180:
181: public static StringBuffer getFullRequestUrl(
182: HttpServletRequest request) {
183: StringBuffer requestUrl = UtilHttp.getServerRootUrl(request);
184: requestUrl.append(request.getRequestURI());
185: if (request.getQueryString() != null) {
186: requestUrl.append("?" + request.getQueryString());
187: }
188: return requestUrl;
189: }
190:
191: private static Locale getLocale(HttpServletRequest request,
192: HttpSession session) {
193: Object localeObject = session != null ? session
194: .getAttribute("locale") : null;
195: if (localeObject == null)
196: localeObject = request != null ? request.getLocale() : null;
197: return UtilMisc.ensureLocale(localeObject);
198: }
199:
200: /**
201: * Get the Locale object from a session variable; if not found use the browser's default
202: * @param request HttpServletRequest object to use for lookup
203: * @return Locale The current Locale to use
204: */
205: public static Locale getLocale(HttpServletRequest request) {
206: if (request == null)
207: return Locale.getDefault();
208: return UtilHttp.getLocale(request, request.getSession());
209: }
210:
211: /**
212: * Get the Locale object from a session variable; if not found use the system's default.
213: * NOTE: This method is not recommended because it ignores the Locale from the browser not having the request object.
214: * @param session HttpSession object to use for lookup
215: * @return Locale The current Locale to use
216: */
217: public static Locale getLocale(HttpSession session) {
218: if (session == null)
219: return Locale.getDefault();
220: return UtilHttp.getLocale(null, session);
221: }
222:
223: public static void setLocale(HttpServletRequest request,
224: String localeString) {
225: UtilHttp.setLocale(request, UtilMisc.parseLocale(localeString));
226: }
227:
228: public static void setLocale(HttpServletRequest request,
229: Locale locale) {
230: request.getSession().setAttribute("locale", locale);
231: }
232:
233: /** Simple event to set the users per-session locale setting */
234: public static String setSessionLocale(HttpServletRequest request,
235: HttpServletResponse response) {
236: String localeString = request.getParameter("locale");
237: if (UtilValidate.isNotEmpty(localeString)) {
238: UtilHttp.setLocale(request, localeString);
239: }
240: return "success";
241: }
242:
243: /**
244: * Get the currency string from the session.
245: * @param session HttpSession object to use for lookup
246: * @return String The ISO currency code
247: */
248: public static String getCurrencyUom(HttpSession session) {
249: String iso = (String) session.getAttribute("currencyUom");
250: if (iso == null) {
251: // if none is set we will use the system default
252: Currency cur = Currency.getInstance(Locale.getDefault());
253: iso = cur.getCurrencyCode();
254: }
255: return iso;
256: }
257:
258: /**
259: * Get the currency string from the session.
260: * @param request HttpServletRequest object to use for lookup
261: * @return String The ISO currency code
262: */
263: public static String getCurrencyUom(HttpServletRequest request) {
264: return getCurrencyUom(request.getSession());
265: }
266:
267: /** Simple event to set the users per-session currency uom value */
268: public static void setCurrencyUom(HttpServletRequest request,
269: String currencyUom) {
270: request.getSession().setAttribute("currencyUom", currencyUom);
271: }
272:
273: /** Simple event to set the users per-session currency uom value */
274: public static String setSessionCurrencyUom(
275: HttpServletRequest request, HttpServletResponse response) {
276: String currencyUom = request.getParameter("currencyUom");
277: if (UtilValidate.isNotEmpty(currencyUom)) {
278: UtilHttp.setCurrencyUom(request, currencyUom);
279: }
280: return "success";
281: }
282:
283: /** URL Encodes a Map of arguements */
284: public static String urlEncodeArgs(Map args) {
285: StringBuffer buf = new StringBuffer();
286: if (args != null) {
287: Iterator i = args.entrySet().iterator();
288: while (i.hasNext()) {
289: Map.Entry entry = (Map.Entry) i.next();
290: String name = (String) entry.getKey();
291: Object value = entry.getValue();
292: String valueStr = null;
293: if (name != null && value != null) {
294: if (value instanceof String) {
295: valueStr = (String) value;
296: } else {
297: valueStr = value.toString();
298: }
299:
300: if (valueStr != null && valueStr.length() > 0) {
301: if (buf.length() > 0)
302: buf.append('&');
303: try {
304: buf
305: .append(URLEncoder.encode(name,
306: "UTF-8"));
307: } catch (UnsupportedEncodingException e) {
308: Debug.logError(e, module);
309: }
310: buf.append('=');
311: try {
312: buf.append(URLEncoder.encode(valueStr,
313: "UTF-8"));
314: } catch (UnsupportedEncodingException e) {
315: Debug.logError(e, module);
316: }
317: }
318: }
319: }
320: }
321: return buf.toString();
322: }
323:
324: public static String setResponseBrowserProxyNoCache(
325: HttpServletRequest request, HttpServletResponse response) {
326: setResponseBrowserProxyNoCache(response);
327: return "success";
328: }
329:
330: public static void setResponseBrowserProxyNoCache(
331: HttpServletResponse response) {
332: long nowMillis = System.currentTimeMillis();
333: response.setDateHeader("Expires", nowMillis);
334: response.setDateHeader("Last-Modified", nowMillis); // always modified
335: response.setHeader("Cache-Control",
336: "no-store, no-cache, must-revalidate"); // HTTP/1.1
337: response.addHeader("Cache-Control",
338: "post-check=0, pre-check=0, false");
339: response.setHeader("Pragma", "no-cache"); // HTTP/1.0
340: }
341:
342: public static String getContentTypeByFileName(String fileName) {
343: FileNameMap mime = URLConnection.getFileNameMap();
344: return mime.getContentTypeFor(fileName);
345: }
346:
347: /**
348: * Stream an array of bytes to the browser
349: * This method will close the ServletOutputStream when finished
350: *
351: * @param response HttpServletResponse object to get OutputStream from
352: * @param bytes Byte array of content to stream
353: * @param contentType The content type to pass to the browser
354: * @throws IOException
355: */
356: public static void streamContentToBrowser(
357: HttpServletResponse response, byte[] bytes,
358: String contentType) throws IOException {
359: // tell the browser not the cache
360: setResponseBrowserProxyNoCache(response);
361:
362: // set the response info
363: response.setContentLength(bytes.length);
364: if (contentType != null) {
365: response.setContentType(contentType);
366: }
367:
368: // create the streams
369: OutputStream out = response.getOutputStream();
370: InputStream in = new ByteArrayInputStream(bytes);
371:
372: // stream the content
373: try {
374: streamContent(out, in, bytes.length);
375: } catch (IOException e) {
376: in.close();
377: out.close(); // should we close the ServletOutputStream on error??
378: throw e;
379: }
380:
381: // close the input stream
382: in.close();
383:
384: // close the servlet output stream
385: out.flush();
386: out.close();
387: }
388:
389: /**
390: * Streams content from InputStream to the ServletOutputStream
391: * This method will close the ServletOutputStream when finished
392: * This method does not close the InputSteam passed
393: *
394: * @param response HttpServletResponse object to get OutputStream from
395: * @param in InputStream of the actual content
396: * @param length Size (in bytes) of the content
397: * @param contentType The content type to pass to the browser
398: * @throws IOException
399: */
400: public static void streamContentToBrowser(
401: HttpServletResponse response, InputStream in, int length,
402: String contentType) throws IOException {
403: // tell the browser not the cache
404: setResponseBrowserProxyNoCache(response);
405:
406: // set the response info
407: response.setContentLength(length);
408: if (contentType != null) {
409: response.setContentType(contentType);
410: }
411:
412: // stream the content
413: OutputStream out = response.getOutputStream();
414: try {
415: streamContent(out, in, length);
416: } catch (IOException e) {
417: out.close();
418: throw e;
419: }
420:
421: // close the servlet output stream
422: out.flush();
423: out.close();
424: }
425:
426: /**
427: * Stream binary content from InputStream to OutputStream
428: * This method does not close the streams passed
429: *
430: * @param out OutputStream content should go to
431: * @param in InputStream of the actual content
432: * @param length Size (in bytes) of the content
433: * @throws IOException
434: */
435: public static void streamContent(OutputStream out, InputStream in,
436: int length) throws IOException {
437: int bufferSize = 512; // same as the default buffer size; change as needed
438: BufferedOutputStream bos = new BufferedOutputStream(out,
439: bufferSize);
440: BufferedInputStream bis = new BufferedInputStream(in,
441: bufferSize);
442:
443: byte[] buffer = new byte[length];
444: int read = 0;
445: try {
446: while (-1 != (read = bis.read(buffer, 0, buffer.length))) {
447: bos.write(buffer, 0, read);
448: }
449: } catch (IOException e) {
450: Debug
451: .logError(e, "Problem reading/writing buffers",
452: module);
453: bis.close();
454: bos.close();
455: throw e;
456: } finally {
457: if (bis != null) {
458: bis.close();
459: }
460: if (bos != null) {
461: bos.flush();
462: bos.close();
463: }
464: }
465: }
466: }
|