📄 utilhttp.java
字号:
// stream the content try { streamContent(out, in, bytes.length); } catch (IOException e) { in.close(); out.close(); // should we close the ServletOutputStream on error?? throw e; } // close the input stream in.close(); // close the servlet output stream out.flush(); out.close(); } /** * Streams content from InputStream to the ServletOutputStream * This method will close the ServletOutputStream when finished * This method does not close the InputSteam passed * * @param response HttpServletResponse object to get OutputStream from * @param in InputStream of the actual content * @param length Size (in bytes) of the content * @param contentType The content type to pass to the browser * @throws IOException */ public static void streamContentToBrowser(HttpServletResponse response, InputStream in, int length, String contentType) throws IOException { // tell the browser not the cache setResponseBrowserProxyNoCache(response); // set the response info response.setContentLength(length); if (contentType != null) { response.setContentType(contentType); } // stream the content OutputStream out = response.getOutputStream(); try { streamContent(out, in, length); } catch (IOException e) { out.close(); throw e; } // close the servlet output stream out.flush(); out.close(); } /** * Stream binary content from InputStream to OutputStream * This method does not close the streams passed * * @param out OutputStream content should go to * @param in InputStream of the actual content * @param length Size (in bytes) of the content * @throws IOException */ public static void streamContent(OutputStream out, InputStream in, int length) throws IOException { int bufferSize = 512; // same as the default buffer size; change as needed // make sure we have something to write to if (out == null) { throw new IOException("Attempt to write to null output stream"); } // make sure we have something to read from if (in == null) { throw new IOException("Attempt to read from null input stream"); } // make sure we have some content if (length == 0) { throw new IOException("Attempt to write 0 bytes of content to output stream"); } // initialize the buffered streams BufferedOutputStream bos = new BufferedOutputStream(out, bufferSize); BufferedInputStream bis = new BufferedInputStream(in, bufferSize); byte[] buffer = new byte[length]; int read = 0; try { while ((read = bis.read(buffer, 0, buffer.length)) != -1) { bos.write(buffer, 0, read); } } catch (IOException e) { Debug.logError(e, "Problem reading/writing buffers", module); bis.close(); bos.close(); throw e; } finally { if (bis != null) { bis.close(); } if (bos != null) { bos.flush(); bos.close(); } } } public static String stripViewParamsFromQueryString(String queryString) { Set paramNames = new HashSet(); paramNames.add("VIEW_INDEX"); paramNames.add("VIEW_SIZE"); paramNames.add("viewIndex"); paramNames.add("viewSize"); return stripNamedParamsFromQueryString(queryString, paramNames); } public static String stripNamedParamsFromQueryString(String queryString, Collection paramNames) { String retStr = null; if (UtilValidate.isNotEmpty(queryString)) { StringTokenizer queryTokens = new StringTokenizer(queryString, "&"); StringBuffer cleanQuery = new StringBuffer(); while (queryTokens.hasMoreTokens()) { String token = queryTokens.nextToken(); if (token.startsWith("amp;")) { token = token.substring(4); } int equalsIndex = token.indexOf("="); String name = token; if (equalsIndex > 0) { name = token.substring(0, equalsIndex); } if (!paramNames.contains(name)) { cleanQuery.append(token); if(queryTokens.hasMoreTokens()){ cleanQuery.append("&"); } } } retStr = cleanQuery.toString(); } return retStr; } /** * Given multi form data with the ${param}_o_N notation, creates a Collection * of Maps for the submitted rows. Each Map contains the key/value pairs * of a particular row. The keys will be stripped of the _o_N suffix. * There is an additionaly key "row" for each Map that holds the * index of the row. */ public static Collection parseMultiFormData(Map parameters) { FastMap rows = new FastMap(); // stores the rows keyed by row number // first loop through all the keys and create a hashmap for each ${ROW_SUBMIT_PREFIX}${N} = Y Iterator keys = parameters.keySet().iterator(); while (keys.hasNext()) { String key = (String) keys.next(); // skip everything that is not ${ROW_SUBMIT_PREFIX}N if (key == null || key.length() <= ROW_SUBMIT_PREFIX_LENGTH) continue; if (key.indexOf(MULTI_ROW_DELIMITER) <= 0) continue; if (!key.substring(0, ROW_SUBMIT_PREFIX_LENGTH).equals(ROW_SUBMIT_PREFIX)) continue; if (!parameters.get(key).equals("Y")) continue; // decode the value of N and create a new map for it Integer n = Integer.decode(key.substring(ROW_SUBMIT_PREFIX_LENGTH, key.length())); Map m = new FastMap(); m.put("row", n); // special "row" = N tuple rows.put(n, m); // key it to N } // next put all parameters with matching N in the right map keys = parameters.keySet().iterator(); while (keys.hasNext()) { String key = (String) keys.next(); // skip keys without DELIMITER and skip ROW_SUBMIT_PREFIX if (key == null) continue; int index = key.indexOf(MULTI_ROW_DELIMITER); if (index <= 0) continue; if (key.length() > ROW_SUBMIT_PREFIX_LENGTH && key.substring(0, ROW_SUBMIT_PREFIX_LENGTH).equals(ROW_SUBMIT_PREFIX)) continue; // get the map with index N Integer n = Integer.decode(key.substring(index + MULTI_ROW_DELIMITER_LENGTH, key.length())); // N from ${param}${DELIMITER}${N} Map map = (Map) rows.get(n); if (map == null) continue; // get the key without the <DELIMITER>N suffix and store it and its value String newKey = key.substring(0, index); map.put(newKey, parameters.get(key)); } // return only the values, which is the list of maps return rows.values(); } /** * Utility to make a composite parameter from the given prefix and suffix. * The prefix should be a regular paramter name such as meetingDate. The * suffix is the composite field, such as the hour of the meeting. The * result would be meetingDate_${COMPOSITE_DELIMITER}_hour. * * @param paramName * @param compositeName * @return */ public static String makeCompositeParam(String prefix, String suffix) { return prefix + COMPOSITE_DELIMITER + suffix; } /** * Given the prefix of a composite parameter, recomposes a single Object from * the composite according to compositeType. For example, consider the following * form widget field, * * <field name="meetingDate"> * <date-time type="timestamp" input-method="time-dropdown"> * </field> * * The result in HTML is three input boxes to input the date, hour and minutes separately. * The parameter names are named meetingDate_c_date, meetingDate_c_hour, meetingDate_c_minutes. * Additionally, there will be a field named meetingDate_c_compositeType with a value of "Timestamp". * where _c_ is the COMPOSITE_DELIMITER. These parameters will then be recomposed into a Timestamp * object from the composite fields. * * @param request * @param prefix * @return Composite object from data or nulll if not supported or a parsing error occured. */ public static Object makeParamValueFromComposite(HttpServletRequest request, String prefix, Locale locale) { String compositeType = request.getParameter(makeCompositeParam(prefix, "compositeType")); if (compositeType == null || compositeType.length() == 0) return null; // collect the composite fields into a map Map data = FastMap.newInstance(); for (Enumeration names = request.getParameterNames(); names.hasMoreElements(); ) { String name = (String) names.nextElement(); if (!name.startsWith(prefix + COMPOSITE_DELIMITER)) continue; // extract the suffix of the composite name String suffix = name.substring(name.indexOf(COMPOSITE_DELIMITER) + COMPOSITE_DELIMITER_LENGTH); // and the value of this parameter Object value = request.getParameter(name); // key = suffix, value = parameter data data.put(suffix, value); } if (Debug.verboseOn()) { Debug.logVerbose("Creating composite type with parameter data: " + data.toString(), module); } // handle recomposition of data into the compositeType if ("Timestamp".equals(compositeType)) { String date = (String) data.get("date"); String hour = (String) data.get("hour"); String minutes = (String) data.get("minutes"); String ampm = (String) data.get("ampm"); if (date == null || date.length() < 10) return null; if (hour == null || hour.length() == 0) return null; if (minutes == null || minutes.length() == 0) return null; boolean isTwelveHour = ((ampm == null || ampm.length() == 0) ? false : true); // create the timestamp from the data try { int h = Integer.parseInt(hour); Timestamp timestamp = Timestamp.valueOf(date.substring(0, 10) + " 00:00:00.000"); Calendar cal = Calendar.getInstance(locale); cal.setTime(timestamp); if (isTwelveHour) { boolean isAM = ("AM".equals(ampm) ? true : false); if (isAM && h == 12) h = 0; if (!isAM && h < 12) h += 12; } cal.set(Calendar.HOUR_OF_DAY, h); cal.set(Calendar.MINUTE, Integer.parseInt(minutes)); return new Timestamp(cal.getTimeInMillis()); } catch (IllegalArgumentException e) { Debug.logWarning("User input for composite timestamp was invalid: " + e.getMessage(), module); return null; } } // we don't support any other compositeTypes (yet) return null; }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -