1 24 package org.ofbiz.base.util; 25 26 import java.io.BufferedInputStream ; 27 import java.io.BufferedOutputStream ; 28 import java.io.ByteArrayInputStream ; 29 import java.io.IOException ; 30 import java.io.InputStream ; 31 import java.io.OutputStream ; 32 import java.io.UnsupportedEncodingException ; 33 import java.net.FileNameMap ; 34 import java.net.URLConnection ; 35 import java.net.URLEncoder ; 36 import java.sql.Timestamp ; 37 import java.util.ArrayList ; 38 import java.util.Arrays ; 39 import java.util.Calendar ; 40 import java.util.Collection ; 41 import java.util.Currency ; 42 import java.util.Enumeration ; 43 import java.util.HashMap ; 44 import java.util.HashSet ; 45 import java.util.Iterator ; 46 import java.util.List ; 47 import java.util.Locale ; 48 import java.util.Map ; 49 import java.util.Set ; 50 import java.util.StringTokenizer ; 51 52 import javax.servlet.http.HttpServletRequest ; 53 import javax.servlet.http.HttpServletResponse ; 54 import javax.servlet.http.HttpSession ; 55 56 import javolution.util.FastList; 57 import javolution.util.FastMap; 58 59 67 public class UtilHttp { 68 69 public static final String module = UtilHttp.class.getName(); 70 71 public static final String MULTI_ROW_DELIMITER = "_o_"; 72 public static final String ROW_SUBMIT_PREFIX = "_rowSubmit_o_"; 73 public static final String COMPOSITE_DELIMITER = "_c_"; 74 public static final int MULTI_ROW_DELIMITER_LENGTH = MULTI_ROW_DELIMITER.length(); 75 public static final int ROW_SUBMIT_PREFIX_LENGTH = ROW_SUBMIT_PREFIX.length(); 76 public static final int COMPOSITE_DELIMITER_LENGTH = COMPOSITE_DELIMITER.length(); 77 78 79 83 public static Map getParameterMap(HttpServletRequest request) { 84 Map paramMap = FastMap.newInstance(); 85 86 Enumeration e = request.getParameterNames(); 88 while (e.hasMoreElements()) { 89 String name = (String ) e.nextElement(); 90 Object value = null; 91 String [] paramArr = request.getParameterValues(name); 92 if (paramArr != null) { 93 if (paramArr.length > 1) { 94 value = Arrays.asList(paramArr); 95 } else { 96 value = paramArr[0]; 97 } 99 } 100 paramMap.put(name, value); 101 } 102 103 String pathInfoStr = request.getPathInfo(); 106 107 if (pathInfoStr != null && pathInfoStr.length() > 0) { 108 if (!pathInfoStr.endsWith("/")) pathInfoStr += "/"; 110 111 int current = pathInfoStr.indexOf('/'); 112 int last = current; 113 while ((current = pathInfoStr.indexOf('/', last + 1)) != -1) { 114 String element = pathInfoStr.substring(last + 1, current); 115 last = current; 116 if (element.charAt(0) == '~' && element.indexOf('=') > -1) { 117 String name = element.substring(1, element.indexOf('=')); 118 String value = element.substring(element.indexOf('=') + 1); 119 Object curValue = paramMap.get(name); 120 if (curValue != null) { 121 List paramList = null; 122 if (curValue instanceof List ) { 123 paramList = (List ) curValue; 124 paramList.add(value); 125 } else { 126 String paramString = (String ) curValue; 127 paramList = FastList.newInstance(); 128 paramList.add(paramString); 129 paramList.add(value); 130 } 131 paramMap.put(name, paramList); 132 } else { 133 paramMap.put(name, value); 134 } 135 } 136 } 137 } 138 139 if (paramMap.size() == 0) { 140 Map multiPartMap = (Map ) request.getAttribute("multiPartMap"); 142 if (multiPartMap != null && multiPartMap.size() > 0) { 143 paramMap.putAll(multiPartMap); 144 } 145 } 146 147 if (Debug.verboseOn()) { 149 Debug.logVerbose("Made Request Parameter Map with [" + paramMap.size() + "] Entries", module); 150 Iterator entryIter = paramMap.entrySet().iterator(); 151 while (entryIter.hasNext()) { 152 Map.Entry entry = (Map.Entry ) entryIter.next(); 153 Debug.logVerbose("Request Parameter Map Entry: [" + entry.getKey() + "] --> " + entry.getValue(), module); 154 } 155 } 156 157 return paramMap; 158 } 159 160 public static Map makeParamMapWithPrefix(HttpServletRequest request, String prefix, String suffix) { 161 return makeParamMapWithPrefix(request, null, prefix, suffix); 162 } 163 164 public static Map makeParamMapWithPrefix(HttpServletRequest request, Map additionalFields, String prefix, String suffix) { 165 Map paramMap = new HashMap (); 166 Enumeration parameterNames = request.getParameterNames(); 167 while (parameterNames.hasMoreElements()) { 168 String parameterName = (String ) parameterNames.nextElement(); 169 if (parameterName.startsWith(prefix)) { 170 if (suffix != null && suffix.length() > 0) { 171 if (parameterName.endsWith(suffix)) { 172 String key = parameterName.substring(prefix.length(), parameterName.length() - (suffix.length())); 173 String value = request.getParameter(parameterName); 174 paramMap.put(key, value); 175 } 176 } else { 177 String key = parameterName.substring(prefix.length()); 178 String value = request.getParameter(parameterName); 179 paramMap.put(key, value); 180 } 181 } 182 } 183 if (additionalFields != null) { 184 Iterator i = additionalFields.keySet().iterator(); 185 while (i.hasNext()) { 186 String fieldName = (String ) i.next(); 187 if (fieldName.startsWith(prefix)) { 188 if (suffix != null && suffix.length() > 0) { 189 if (fieldName.endsWith(suffix)) { 190 String key = fieldName.substring(prefix.length(), fieldName.length() - (suffix.length() - 1)); 191 Object value = additionalFields.get(fieldName); 192 paramMap.put(key, value); 193 194 if (!(value instanceof String )) { 196 String nameKey = "_" + key + "_fileName"; 197 Object nameVal = additionalFields.get("_" + fieldName + "_fileName"); 198 if (nameVal != null) { 199 paramMap.put(nameKey, nameVal); 200 } 201 202 String typeKey = "_" + key + "_contentType"; 203 Object typeVal = additionalFields.get("_" + fieldName + "_contentType"); 204 if (typeVal != null) { 205 paramMap.put(typeKey, typeVal); 206 } 207 208 String sizeKey = "_" + key + "_size"; 209 Object sizeVal = additionalFields.get("_" + fieldName + "_size"); 210 if (sizeVal != null) { 211 paramMap.put(sizeKey, sizeVal); 212 } 213 } 214 } 215 } else { 216 String key = fieldName.substring(prefix.length()); 217 Object value = additionalFields.get(fieldName); 218 paramMap.put(key, value); 219 220 if (!(value instanceof String )) { 222 String nameKey = "_" + key + "_fileName"; 223 Object nameVal = additionalFields.get("_" + fieldName + "_fileName"); 224 if (nameVal != null) { 225 paramMap.put(nameKey, nameVal); 226 } 227 228 String typeKey = "_" + key + "_contentType"; 229 Object typeVal = additionalFields.get("_" + fieldName + "_contentType"); 230 if (typeVal != null) { 231 paramMap.put(typeKey, typeVal); 232 } 233 234 String sizeKey = "_" + key + "_size"; 235 Object sizeVal = additionalFields.get("_" + fieldName + "_size"); 236 if (sizeVal != null) { 237 paramMap.put(sizeKey, sizeVal); 238 } 239 } 240 } 241 } 242 } 243 } 244 return paramMap; 245 } 246 247 public static List makeParamListWithSuffix(HttpServletRequest request, String suffix, String prefix) { 248 return makeParamListWithSuffix(request, null, suffix, prefix); 249 } 250 251 public static List makeParamListWithSuffix(HttpServletRequest request, Map additionalFields, String suffix, String prefix) { 252 List paramList = new ArrayList (); 253 Enumeration parameterNames = request.getParameterNames(); 254 while (parameterNames.hasMoreElements()) { 255 String parameterName = (String ) parameterNames.nextElement(); 256 if (parameterName.endsWith(suffix)) { 257 if (prefix != null && prefix.length() > 0) { 258 if (parameterName.startsWith(prefix)) { 259 String value = request.getParameter(parameterName); 260 paramList.add(value); 261 } 262 } else { 263 String value = request.getParameter(parameterName); 264 paramList.add(value); 265 } 266 } 267 } 268 if (additionalFields != null) { 269 Iterator i = additionalFields.keySet().iterator(); 270 while (i.hasNext()) { 271 String fieldName = (String ) i.next(); 272 if (fieldName.endsWith(suffix)) { 273 if (prefix != null && prefix.length() > 0) { 274 if (fieldName.startsWith(prefix)) { 275 Object value = additionalFields.get(fieldName); 276 paramList.add(value); 277 } 278 } else { 279 Object value = additionalFields.get(fieldName); 280 paramList.add(value); 281 } 282 } 283 } 284 } 285 return paramList; 286 } 287 288 293 public static String getApplicationName(HttpServletRequest request) { 294 String appName = "root"; 295 if (request.getContextPath().length() > 1) { 296 appName = request.getContextPath().substring(1); 297 } 298 return appName; 299 } 300 301 305 public static void parametersToAttributes(HttpServletRequest request) { 306 java.util.Enumeration e = request.getParameterNames(); 307 while (e.hasMoreElements()) { 308 String name = (String ) e.nextElement(); 309 request.setAttribute(name, request.getParameter(name)); 310 } 311 } 312 313 public static StringBuffer getServerRootUrl(HttpServletRequest request) { 314 StringBuffer requestUrl = new StringBuffer (); 315 requestUrl.append(request.getScheme()); 316 requestUrl.append("://" + request.getServerName()); 317 if (request.getServerPort() != 80 && request.getServerPort() != 443) 318 requestUrl.append(":" + request.getServerPort()); 319 return requestUrl; 320 } 321 322 public static StringBuffer getFullRequestUrl(HttpServletRequest request) { 323 StringBuffer requestUrl = UtilHttp.getServerRootUrl(request); 324 requestUrl.append(request.getRequestURI()); 325 if (request.getQueryString() != null) { 326 requestUrl.append("?" + request.getQueryString()); 327 } 328 return requestUrl; 329 } 330 331 private static Locale getLocale(HttpServletRequest request, HttpSession session) { 332 Object localeObject = localeObject = session != null ? session.getAttribute("locale") : null; 334 335 if (localeObject == null) { 337 Map userLogin = (Map ) session.getAttribute("userLogin"); 338 if (userLogin == null) { 339 userLogin = (Map ) session.getAttribute("autoUserLogin"); 340 } 341 342 if (userLogin != null) { 343 localeObject = userLogin.get("lastLocale"); 344 } 345 } 346 347 if (localeObject == null) { 349 localeObject = request != null ? request.getLocale() : null; 350 } 351 352 return UtilMisc.ensureLocale(localeObject); 353 } 354 355 360 public static Locale getLocale(HttpServletRequest request) { 361 if (request == null) return Locale.getDefault(); 362 return UtilHttp.getLocale(request, request.getSession()); 363 } 364 365 371 public static Locale getLocale(HttpSession session) { 372 if (session == null) return Locale.getDefault(); 373 return UtilHttp.getLocale(null, session); 374 } 375 376 public static void setLocale(HttpServletRequest request, String localeString) { 377 UtilHttp.setLocale(request.getSession(), UtilMisc.parseLocale(localeString)); 378 } 379 380 public static void setLocale(HttpSession session, Locale locale) { 381 session.setAttribute("locale", locale); 382 } 383 384 public static void setLocaleIfNone(HttpSession session, String localeString) { 385 if (UtilValidate.isNotEmpty(localeString) && session.getAttribute("locale") == null) { 386 UtilHttp.setLocale(session, UtilMisc.parseLocale(localeString)); 387 } 388 } 389 390 395 public static String getCurrencyUom(HttpSession session) { 396 String iso = (String ) session.getAttribute("currencyUom"); 398 399 if (iso == null) { 401 Map userLogin = (Map ) session.getAttribute("userLogin"); 402 if (userLogin == null) { 403 userLogin = (Map ) session.getAttribute("autoUserLogin"); 404 } 405 406 if (userLogin != null) { 407 iso = (String ) userLogin.get("lastCurrencyUom"); 408 } 409 } 410 411 if (iso == null) { 413 try { 414 iso = UtilProperties.getPropertyValue("general", "currency.uom.id.default", "USD"); 415 } catch (Exception e) { 416 Debug.logWarning("Error getting the general:currency.uom.id.default value: " + e.toString(), module); 417 } 418 } 419 420 421 if (iso == null) { 423 Currency cur = Currency.getInstance(getLocale(session)); 424 iso = cur.getCurrencyCode(); 425 } 426 427 return iso; 428 } 429 430 435 public static String getCurrencyUom(HttpServletRequest request) { 436 return getCurrencyUom(request.getSession()); 437 } 438 439 440 public static void setCurrencyUom(HttpSession session, String currencyUom) { 441 session.setAttribute("currencyUom", currencyUom); 442 } 443 444 public static void setCurrencyUomIfNone(HttpSession session, String currencyUom) { 445 if (UtilValidate.isNotEmpty(currencyUom) && session.getAttribute("currencyUom") == null) { 446 session.setAttribute("currencyUom", currencyUom); 447 } 448 } 449 450 451 public static String urlEncodeArgs(Map args) { 452 return urlEncodeArgs(args, true); 453 } 454 455 456 public static String urlEncodeArgs(Map args, boolean useExpandedEntites) { 457 StringBuffer buf = new StringBuffer (); 458 if (args != null) { 459 Iterator i = args.entrySet().iterator(); 460 while (i.hasNext()) { 461 Map.Entry entry = (Map.Entry ) i.next(); 462 String name = (String ) entry.getKey(); 463 Object value = entry.getValue(); 464 String valueStr = null; 465 if (name != null && value != null) { 466 if (value instanceof String ) { 467 valueStr = (String ) value; 468 } else { 469 valueStr = value.toString(); 470 } 471 472 if (valueStr != null && valueStr.length() > 0) { 473 if (buf.length() > 0) { 474 if (useExpandedEntites) { 475 buf.append("&"); 476 } else { 477 buf.append("&"); 478 } 479 } 480 try { 481 buf.append(URLEncoder.encode(name, "UTF-8")); 482 } catch (UnsupportedEncodingException e) { 483 Debug.logError(e, module); 484 } 485 buf.append('='); 486 try { 487 buf.append(URLEncoder.encode(valueStr, "UTF-8")); 488 } catch (UnsupportedEncodingException e) { 489 Debug.logError(e, module); 490 } 491 } 492 } 493 } 494 } 495 return buf.toString(); 496 } 497 498 public static String encodeAmpersands(String htmlString) { 499 StringBuffer htmlBuffer = new StringBuffer (htmlString); 500 int ampLoc = -1; 501 while ((ampLoc = htmlBuffer.indexOf("&", ampLoc + 1)) != -1) { 502 504 int semiLoc = htmlBuffer.indexOf(";", ampLoc); 506 if (semiLoc != -1) { 507 int eqLoc = htmlBuffer.indexOf("=", ampLoc); 509 int amp2Loc = htmlBuffer.indexOf("&", ampLoc + 1); 510 if ((eqLoc == -1 || eqLoc > semiLoc) && (amp2Loc == -1 || amp2Loc > semiLoc)) { 511 continue; 512 } 513 } 514 515 htmlBuffer.insert(ampLoc + 1, "amp;"); 517 } 518 return htmlBuffer.toString(); 519 } 520 521 public static String encodeBlanks(String htmlString) { 522 return htmlString.replaceAll(" ", "%20"); 523 } 524 525 public static String setResponseBrowserProxyNoCache(HttpServletRequest request, HttpServletResponse response) { 526 setResponseBrowserProxyNoCache(response); 527 return "success"; 528 } 529 530 public static void setResponseBrowserProxyNoCache(HttpServletResponse response) { 531 long nowMillis = System.currentTimeMillis(); 532 response.setDateHeader("Expires", nowMillis); 533 response.setDateHeader("Last-Modified", nowMillis); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0, false"); 536 response.setHeader("Pragma", "no-cache"); } 538 539 public static String getContentTypeByFileName(String fileName) { 540 FileNameMap mime = URLConnection.getFileNameMap(); 541 return mime.getContentTypeFor(fileName); 542 } 543 544 553 public static void streamContentToBrowser(HttpServletResponse response, byte[] bytes, String contentType) throws IOException { 554 setResponseBrowserProxyNoCache(response); 556 557 response.setContentLength(bytes.length); 559 if (contentType != null) { 560 response.setContentType(contentType); 561 } 562 563 OutputStream out = response.getOutputStream(); 565 InputStream in = new ByteArrayInputStream (bytes); 566 567 try { 569 streamContent(out, in, bytes.length); 570 } catch (IOException e) { 571 in.close(); 572 out.close(); throw e; 574 } 575 576 in.close(); 578 579 out.flush(); 581 out.close(); 582 } 583 584 595 public static void streamContentToBrowser(HttpServletResponse response, InputStream in, int length, String contentType) throws IOException { 596 setResponseBrowserProxyNoCache(response); 598 599 response.setContentLength(length); 601 if (contentType != null) { 602 response.setContentType(contentType); 603 } 604 605 OutputStream out = response.getOutputStream(); 607 try { 608 streamContent(out, in, length); 609 } catch (IOException e) { 610 out.close(); 611 throw e; 612 } 613 614 out.flush(); 616 out.close(); 617 } 618 619 628 public static void streamContent(OutputStream out, InputStream in, int length) throws IOException { 629 int bufferSize = 512; 631 if (out == null) { 633 throw new IOException ("Attempt to write to null output stream"); 634 } 635 636 if (in == null) { 638 throw new IOException ("Attempt to read from null input stream"); 639 } 640 641 if (length == 0) { 643 throw new IOException ("Attempt to write 0 bytes of content to output stream"); 644 } 645 646 BufferedOutputStream bos = new BufferedOutputStream (out, bufferSize); 648 BufferedInputStream bis = new BufferedInputStream (in, bufferSize); 649 650 byte[] buffer = new byte[length]; 651 int read = 0; 652 try { 653 while ((read = bis.read(buffer, 0, buffer.length)) != -1) { 654 bos.write(buffer, 0, read); 655 } 656 } catch (IOException e) { 657 Debug.logError(e, "Problem reading/writing buffers", module); 658 bis.close(); 659 bos.close(); 660 throw e; 661 } finally { 662 if (bis != null) { 663 bis.close(); 664 } 665 if (bos != null) { 666 bos.flush(); 667 bos.close(); 668 } 669 } 670 } 671 672 public static String stripViewParamsFromQueryString(String queryString) { 673 Set paramNames = new HashSet (); 674 paramNames.add("VIEW_INDEX"); 675 paramNames.add("VIEW_SIZE"); 676 paramNames.add("viewIndex"); 677 paramNames.add("viewSize"); 678 return stripNamedParamsFromQueryString(queryString, paramNames); 679 } 680 681 public static String stripNamedParamsFromQueryString(String queryString, Collection paramNames) { 682 String retStr = null; 683 if (UtilValidate.isNotEmpty(queryString)) { 684 StringTokenizer queryTokens = new StringTokenizer (queryString, "&"); 685 StringBuffer cleanQuery = new StringBuffer (); 686 while (queryTokens.hasMoreTokens()) { 687 String token = queryTokens.nextToken(); 688 if (token.startsWith("amp;")) { 689 token = token.substring(4); 690 } 691 int equalsIndex = token.indexOf("="); 692 String name = token; 693 if (equalsIndex > 0) { 694 name = token.substring(0, equalsIndex); 695 } 696 if (!paramNames.contains(name)) { 697 cleanQuery.append(token); 698 if(queryTokens.hasMoreTokens()){ 699 cleanQuery.append("&"); 700 } 701 } 702 } 703 retStr = cleanQuery.toString(); 704 } 705 return retStr; 706 } 707 708 715 public static Collection parseMultiFormData(Map parameters) { 716 FastMap rows = new FastMap(); 718 Iterator keys = parameters.keySet().iterator(); 720 while (keys.hasNext()) { 721 String key = (String ) keys.next(); 722 723 if (key == null || key.length() <= ROW_SUBMIT_PREFIX_LENGTH) continue; 725 if (key.indexOf(MULTI_ROW_DELIMITER) <= 0) continue; 726 if (!key.substring(0, ROW_SUBMIT_PREFIX_LENGTH).equals(ROW_SUBMIT_PREFIX)) continue; 727 if (!parameters.get(key).equals("Y")) continue; 728 729 Integer n = Integer.decode(key.substring(ROW_SUBMIT_PREFIX_LENGTH, key.length())); 731 Map m = new FastMap(); 732 m.put("row", n); rows.put(n, m); } 735 736 keys = parameters.keySet().iterator(); 738 while (keys.hasNext()) { 739 String key = (String ) keys.next(); 740 741 if (key == null) continue; 743 int index = key.indexOf(MULTI_ROW_DELIMITER); 744 if (index <= 0) continue; 745 if (key.length() > ROW_SUBMIT_PREFIX_LENGTH && key.substring(0, ROW_SUBMIT_PREFIX_LENGTH).equals(ROW_SUBMIT_PREFIX)) continue; 746 747 Integer n = Integer.decode(key.substring(index + MULTI_ROW_DELIMITER_LENGTH, key.length())); Map map = (Map ) rows.get(n); 750 if (map == null) continue; 751 752 String newKey = key.substring(0, index); 754 map.put(newKey, parameters.get(key)); 755 } 756 return rows.values(); 758 } 759 760 764 public static Map removeMultiFormParameters(Map parameters) { 765 FastMap filteredParameters = new FastMap(); 766 Iterator keys = parameters.keySet().iterator(); 767 while (keys.hasNext()) { 768 String key = (String ) keys.next(); 769 770 if (key != null && (key.indexOf(MULTI_ROW_DELIMITER) != -1 || key.indexOf("_useRowSubmit") != -1 || key.indexOf("_rowCount") != -1)) { 771 continue; 772 } 773 774 filteredParameters.put(key, parameters.get(key)); 775 } 776 return filteredParameters; 777 } 778 779 789 public static String makeCompositeParam(String prefix, String suffix) { 790 return prefix + COMPOSITE_DELIMITER + suffix; 791 } 792 793 812 public static Object makeParamValueFromComposite(HttpServletRequest request, String prefix, Locale locale) { 813 String compositeType = request.getParameter(makeCompositeParam(prefix, "compositeType")); 814 if (compositeType == null || compositeType.length() == 0) return null; 815 816 Map data = FastMap.newInstance(); 818 for (Enumeration names = request.getParameterNames(); names.hasMoreElements(); ) { 819 String name = (String ) names.nextElement(); 820 if (!name.startsWith(prefix + COMPOSITE_DELIMITER)) continue; 821 822 String suffix = name.substring(name.indexOf(COMPOSITE_DELIMITER) + COMPOSITE_DELIMITER_LENGTH); 824 825 Object value = request.getParameter(name); 827 828 data.put(suffix, value); 830 } 831 if (Debug.verboseOn()) { Debug.logVerbose("Creating composite type with parameter data: " + data.toString(), module); } 832 833 if ("Timestamp".equals(compositeType)) { 835 String date = (String ) data.get("date"); 836 String hour = (String ) data.get("hour"); 837 String minutes = (String ) data.get("minutes"); 838 String ampm = (String ) data.get("ampm"); 839 if (date == null || date.length() < 10) return null; 840 if (hour == null || hour.length() == 0) return null; 841 if (minutes == null || minutes.length() == 0) return null; 842 boolean isTwelveHour = ((ampm == null || ampm.length() == 0) ? false : true); 843 844 try { 846 int h = Integer.parseInt(hour); 847 Timestamp timestamp = Timestamp.valueOf(date.substring(0, 10) + " 00:00:00.000"); 848 Calendar cal = Calendar.getInstance(locale); 849 cal.setTime(timestamp); 850 if (isTwelveHour) { 851 boolean isAM = ("AM".equals(ampm) ? true : false); 852 if (isAM && h == 12) h = 0; 853 if (!isAM && h < 12) h += 12; 854 } 855 cal.set(Calendar.HOUR_OF_DAY, h); 856 cal.set(Calendar.MINUTE, Integer.parseInt(minutes)); 857 return new Timestamp (cal.getTimeInMillis()); 858 } catch (IllegalArgumentException e) { 859 Debug.logWarning("User input for composite timestamp was invalid: " + e.getMessage(), module); 860 return null; 861 } 862 } 863 864 return null; 866 } 867 } 868 | Popular Tags |