Java tutorial
/* * Copyright 2005-2013 shopxx.net. All rights reserved. * Support: http://www.shopxx.net * License: http://www.shopxx.net/license */ package com.o2o.util; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.collections4.MultiValuedMap; import org.apache.commons.collections4.multimap.ArrayListValuedHashMap; import org.apache.commons.lang.StringUtils; import org.springframework.util.Assert; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; /** * Utils - Web * * @author SHOP++ Team * @version 3.0 */ public final class WebUtils { /** * ?? */ private WebUtils() { } /** * cookie * * @param request * HttpServletRequest * @param response * HttpServletResponse * @param name * cookie?? * @param value * cookie * @param maxAge * (??: ) * @param path * * @param domain * * @param secure * ?? */ public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name, String value, Integer maxAge, String path, String domain, Boolean secure) { Assert.notNull(request); Assert.notNull(response); Assert.hasText(name); try { name = URLEncoder.encode(name, "UTF-8"); value = URLEncoder.encode(value, "UTF-8"); Cookie cookie = new Cookie(name, value); if (maxAge != null) { cookie.setMaxAge(maxAge); } if (StringUtils.isNotEmpty(path)) { cookie.setPath(path); } if (StringUtils.isNotEmpty(domain)) { cookie.setDomain(domain); } if (secure != null) { cookie.setSecure(secure); } response.addCookie(cookie); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } /** * cookie * * @param request * HttpServletRequest * @param response * HttpServletResponse * @param name * cookie?? * @param value * cookie * @param maxAge * (??: ) */ public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name, String value, Integer maxAge, String domain, String path) { addCookie(request, response, name, value, maxAge, path, domain, null); } /** * cookie * * @param request * HttpServletRequest * @param response * HttpServletResponse * @param name * cookie?? * @param value * cookie */ public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name, String value, String domain, String path) { addCookie(request, response, name, value, null, path, domain, null); } /** * ?cookie * * @param request * HttpServletRequest * @param name * cookie?? * @return ?null */ public static String getCookie(HttpServletRequest request, String name) { if (null == name) { return null; } Assert.notNull(request); Assert.hasText(name); Cookie[] cookies = request.getCookies(); if (cookies != null) { try { name = URLEncoder.encode(name, "UTF-8"); for (Cookie cookie : cookies) { if (name.equals(cookie.getName())) { return URLDecoder.decode(cookie.getValue(), "UTF-8"); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return null; } /** * cookie * * @param request * HttpServletRequest * @param response * HttpServletResponse * @param name * cookie?? * @param path * * @param domain * */ public static void removeCookie(HttpServletRequest request, HttpServletResponse response, String name, String path, String domain) { Assert.notNull(request); Assert.notNull(response); Assert.hasText(name); try { name = URLEncoder.encode(name, "UTF-8"); Cookie cookie = new Cookie(name, null); cookie.setMaxAge(0); if (StringUtils.isNotEmpty(path)) { cookie.setPath(path); } if (StringUtils.isNotEmpty(domain)) { cookie.setDomain(domain); } response.addCookie(cookie); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } /** * ?? * * @param queryString * * @param encoding * ?? * @param name * ??? * @return ? */ public static String getParameter(String queryString, String encoding, String name) { String[] parameterValues = getParameterMap(queryString, encoding).get(name); return parameterValues != null && parameterValues.length > 0 ? parameterValues[0] : null; } /** * ?? * * @param queryString * * @param encoding * ?? * @param name * ??? * @return ? */ public static String[] getParameterValues(String queryString, String encoding, String name) { return getParameterMap(queryString, encoding).get(name); } /** * ?? * * @param queryString * * @param encoding * ?? * @return ? */ public static Map<String, String[]> getParameterMap(String queryString, String encoding) { Map<String, String[]> parameterMap = new HashMap<String, String[]>(); Charset charset = Charset.forName(encoding); if (StringUtils.isNotEmpty(queryString)) { byte[] bytes = queryString.getBytes(charset); if (bytes != null && bytes.length > 0) { int ix = 0; int ox = 0; String key = null; String value = null; while (ix < bytes.length) { byte c = bytes[ix++]; switch ((char) c) { case '&': value = new String(bytes, 0, ox, charset); if (key != null) { putMapEntry(parameterMap, key, value); key = null; } ox = 0; break; case '=': if (key == null) { key = new String(bytes, 0, ox, charset); ox = 0; } else { bytes[ox++] = c; } break; case '+': bytes[ox++] = (byte) ' '; break; case '%': bytes[ox++] = (byte) ((convertHexDigit(bytes[ix++]) << 4) + convertHexDigit(bytes[ix++])); break; default: bytes[ox++] = c; } } if (key != null) { value = new String(bytes, 0, ox, charset); putMapEntry(parameterMap, key, value); } } } return parameterMap; } private static void putMapEntry(Map<String, String[]> map, String name, String value) { String[] newValues = null; String[] oldValues = map.get(name); if (oldValues == null) { newValues = new String[] { value }; } else { newValues = new String[oldValues.length + 1]; System.arraycopy(oldValues, 0, newValues, 0, oldValues.length); newValues[oldValues.length] = value; } map.put(name, newValues); } private static byte convertHexDigit(byte b) { if ((b >= '0') && (b <= '9')) { return (byte) (b - '0'); } if ((b >= 'a') && (b <= 'f')) { return (byte) (b - 'a' + 10); } if ((b >= 'A') && (b <= 'F')) { return (byte) (b - 'A' + 10); } throw new IllegalArgumentException(); } public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; } public static String getPath(HttpServletRequest request) { String path_str = request.getServletPath(); String param_str = request.getQueryString(); if (request.getQueryString() != null) { path_str += "?" + param_str; } return path_str; } public static String getContentType(String fileName) { Path path = Paths.get(fileName); String contentType = null; try { contentType = Files.probeContentType(path); } catch (IOException e) { e.printStackTrace(); } return contentType; } public final static String getWebAppRootPath(HttpServletRequest request) { return request.getSession().getServletContext().getRealPath("/");// } public static String getUrl(HttpServletRequest request) { String path_str = request.getRequestURL().toString(); String param_str = request.getQueryString(); if (request.getQueryString() != null) { path_str += "?" + param_str; } return path_str; } /** * ?? * @param request * @return */ public static Boolean isWeiXin(HttpServletRequest request) { String ua = request.getHeader("user-agent").toLowerCase(); if (ua.indexOf("micromessenger") > 0) {// ? return true; } return false; } public static void clearCookie(HttpServletRequest request, HttpServletResponse response, String path, String domain) { Assert.notNull(request); Assert.notNull(response); try { Cookie[] cookies = request.getCookies(); for (Cookie cookie_old : cookies) { String name = URLEncoder.encode(cookie_old.getName(), "UTF-8"); Cookie cookie = new Cookie(name, null); cookie.setMaxAge(0); if (StringUtils.isNotEmpty(path)) { cookie.setPath(path); } if (StringUtils.isNotEmpty(domain)) { cookie.setDomain(domain); } response.addCookie(cookie); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } /** * ?? * @param url * @return */ public static String generateShortUrl(String url) { MultiValuedMap<String, Object> params = new ArrayListValuedHashMap<String, Object>(); params.put("url", url); String jsonStr = HttpUtil.doPost("http://dwz.cn/create.php", params); JSONObject object = JSON.parseObject(jsonStr); String shortUrl = object.getString("tinyurl"); if (StringUtils.isEmpty(shortUrl)) return url; return shortUrl; } }