package com.se.system.utils;
|
|
import com.alibaba.fastjson.JSON;
|
import com.se.common.core.constant.HttpStatus;
|
import com.se.common.core.web.domain.AjaxResult;
|
import com.se.system.domain.StaticData;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
import org.springframework.web.context.request.RequestContextHolder;
|
import org.springframework.web.context.request.ServletRequestAttributes;
|
|
import javax.servlet.ServletContext;
|
import javax.servlet.ServletOutputStream;
|
import javax.servlet.http.Cookie;
|
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpSession;
|
import java.io.FileInputStream;
|
import java.io.PrintWriter;
|
import java.net.URLEncoder;
|
import java.sql.Timestamp;
|
import java.util.*;
|
|
@SuppressWarnings("ALL")
|
public class WebUtils {
|
private final static String UNKNOWN = "unknown";
|
|
private final static String COMMA = ",";
|
|
private static final Logger log = LoggerFactory.getLogger(WebUtils.class);
|
|
public static double round(double val, double size) {
|
double power = Math.pow(10.0, size);
|
|
return Math.round(val * power) / power;
|
}
|
|
public static String getGuid() {
|
return UUID.randomUUID().toString();
|
}
|
|
public static String getIpAddress(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.getHeader("HTTP_X_FORWARDED_FOR");
|
}
|
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
|
ip = request.getHeader("HTTP_X_FORWARDED");
|
}
|
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
|
ip = request.getHeader("HTTP_X_CLUSTER_CLIENT_IP");
|
}
|
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
|
ip = request.getHeader("HTTP_CLIENT_IP");
|
}
|
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
|
ip = request.getHeader("HTTP_FORWARDED_FOR");
|
}
|
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
|
ip = request.getHeader("HTTP_FORWARDED");
|
}
|
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
|
ip = request.getHeader("HTTP_VIA");
|
}
|
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
|
ip = request.getHeader("REMOTE_ADDR");
|
}
|
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
|
ip = request.getRemoteAddr();
|
}
|
if (ip.contains(COMMA)) {
|
return ip.split(",")[0];
|
}
|
|
return ip;
|
}
|
|
public static Timestamp getCurrentTimestamp() {
|
return new Timestamp(System.currentTimeMillis());
|
}
|
|
public static Timestamp getTimestamp(int min) {
|
Calendar now = Calendar.getInstance();
|
now.add(Calendar.MINUTE, min);
|
|
return new Timestamp(now.getTimeInMillis());
|
}
|
|
public static String getTokenFromCookie(HttpServletRequest request) {
|
Cookie[] cookies = request.getCookies();
|
if (cookies == null || cookies.length == 0) {
|
return null;
|
}
|
|
for (Cookie cookie : cookies) {
|
switch (cookie.getName()) {
|
case StaticData.TOKEN_COOKIE_KEY:
|
return cookie.getValue();
|
default:
|
break;
|
}
|
}
|
|
return null;
|
}
|
|
public static void saveToken2Cookie(String token, HttpServletRequest request, HttpServletResponse response) {
|
deleteCookies(request, response);
|
|
saveCookie(StaticData.TOKEN_COOKIE_KEY, token, response);
|
}
|
|
public static void saveCookie(String key, String value, HttpServletResponse response) {
|
Cookie cookie = new Cookie(key, value);
|
cookie.setMaxAge(StaticData.COOKIE_MAX_AGE);
|
cookie.setHttpOnly(false);
|
cookie.setPath("/");
|
//cookie.setDomain("*")
|
|
response.setHeader("P3P", "CP=CAO PSA OUR");
|
response.addCookie(cookie);
|
}
|
|
public static void deleteCookie(String cookieKey, HttpServletRequest request, HttpServletResponse response) {
|
Cookie[] cookies = request.getCookies();
|
if (cookies != null && cookies.length > 0) {
|
for (Cookie c : cookies) {
|
if (cookieKey.equalsIgnoreCase(c.getName())) {
|
c.setMaxAge(0);
|
c.setPath("/");
|
response.addCookie(c);
|
}
|
}
|
}
|
}
|
|
public static void deleteCookies(HttpServletRequest request, HttpServletResponse response) {
|
Cookie[] cookies = request.getCookies();
|
if (cookies != null && cookies.length > 0) {
|
for (Cookie c : cookies) {
|
c.setMaxAge(0);
|
c.setPath("/");
|
response.addCookie(c);
|
}
|
}
|
}
|
|
public static String getCookieByKey(String key, HttpServletRequest request) {
|
Cookie[] cookies = request.getCookies();
|
if (cookies == null || cookies.length == 0) {
|
return null;
|
}
|
|
for (Cookie c : cookies) {
|
if (key.equals(c.getName())) {
|
return c.getValue();
|
}
|
}
|
|
return null;
|
}
|
|
public static String getToken(HttpServletRequest request) {
|
String token = request.getParameter(StaticData.TOKEN_KEY);
|
|
if (token == null) {
|
token = request.getHeader(StaticData.TOKEN_KEY);
|
}
|
|
if (token == null) {
|
token = getTokenFromCookie(request);
|
}
|
|
return token;
|
}
|
|
public static HttpServletRequest getRequest() {
|
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
|
return servletRequestAttributes.getRequest();
|
}
|
|
public static HttpServletResponse getResponse() {
|
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
|
return servletRequestAttributes.getResponse();
|
}
|
|
public static HttpSession getSession() {
|
return getRequest().getSession();
|
}
|
|
public static String getRealPath(String path) {
|
HttpServletRequest req = getRequest();
|
ServletContext ctx = req.getSession().getServletContext();
|
|
return ctx.getRealPath("/" + path);
|
}
|
|
public static boolean writeStr2Page(HttpServletResponse res, String str) {
|
try {
|
res.setContentType("application/json;charset=UTF-8");
|
res.setHeader("Cache-Control", "no-cache");
|
res.setHeader("Pragma", "No-cache");
|
res.setDateHeader("Expires", 0);
|
|
PrintWriter out = res.getWriter();
|
out.print(str);
|
|
out.flush();
|
out.close();
|
} catch (Exception ex) {
|
log.error(ex.getMessage(), ex);
|
}
|
|
return false;
|
}
|
|
public static void writeJson2Page(HttpServletResponse res, String str) {
|
String json = JSON.toJSONString(new AjaxResult(HttpStatus.ERROR, str));
|
writeStr2Page(res, json);
|
}
|
|
public static String getErrJson(int status, String msg) {
|
return JSON.toJSONString(new AjaxResult(status, msg));
|
}
|
|
public static void writeInfo(int status, String info, HttpServletResponse res) {
|
WebUtils.writeStr2Page(res, WebUtils.getErrJson(status, info));
|
}
|
|
public static int getRandomInt(int min, int max) {
|
return new Random().nextInt(max) % (max - min + 1) + min;
|
}
|
|
public static void download(String file, String fileName, HttpServletResponse res) throws Exception {
|
download(file, fileName, false, res);
|
}
|
|
public static void download(String file, String fileName, boolean inline, HttpServletResponse res) throws Exception {
|
if (StringUtils.isEmpty(fileName)) {
|
fileName = StringUtils.YMDHMS2_FORMAT.format(new Date());
|
}
|
fileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
|
String dispose = inline ? "inline" : "attachment";
|
|
res.setHeader("Content-Disposition", dispose + "; filename*=UTF-8''" + fileName);
|
res.setCharacterEncoding("UTF-8");
|
|
String ext = FileUtils.getExtension(file);
|
String mime = FileUtils.getMime(ext);
|
res.setContentType(mime);
|
|
ServletOutputStream outputStream = res.getOutputStream();
|
FileInputStream fileInputStream = new FileInputStream(file);
|
|
int len = 0;
|
byte[] bytes = new byte[1024];
|
while ((len = fileInputStream.read(bytes)) != -1) {
|
outputStream.write(bytes, 0, len);
|
outputStream.flush();
|
}
|
|
fileInputStream.close();
|
outputStream.close();
|
}
|
|
public static void exec(String cmd) {
|
try {
|
Process process = Runtime.getRuntime().exec(cmd);
|
process.waitFor();
|
} catch (Exception ex) {
|
log.error(ex.getMessage(), ex);
|
}
|
}
|
|
public static String getReqParamVal(HttpServletRequest req, String key) {
|
Map<String, String[]> maps = req.getParameterMap();
|
for (Map.Entry<String, String[]> entry : maps.entrySet()) {
|
if (entry.getKey().equalsIgnoreCase(key)) {
|
return null == entry.getValue() || 0 == entry.getValue().length ? null : entry.getValue()[0];
|
}
|
}
|
|
return null;
|
}
|
|
public static String[] getReqParamVals(HttpServletRequest req, String key) {
|
Map<String, String[]> maps = req.getParameterMap();
|
for (Map.Entry<String, String[]> entry : maps.entrySet()) {
|
if (entry.getKey().equalsIgnoreCase(key)) {
|
return entry.getValue();
|
}
|
}
|
|
return null;
|
}
|
}
|