北京经济技术开发区经开区虚拟城市项目-【后端】-服务,Poi,企业,地块等定制接口
13693261870
2023-10-05 4ac741b8c15973710727ef8313432eea5a5774d1
添加帮助类的依赖工具
已添加3个文件
已修改1个文件
1096 ■■■■■ 文件已修改
pom.xml 6 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/smartearth/poiexcel/utils/FileHelper.java 431 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/smartearth/poiexcel/utils/StringHelper.java 246 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/smartearth/poiexcel/utils/WebHelper.java 413 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
pom.xml
@@ -149,6 +149,12 @@
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <!--fast-md5-->
        <dependency>
            <groupId>com.joyent.util</groupId>
            <artifactId>fast-md5</artifactId>
            <version>2.7.1</version>
        </dependency>
    </dependencies>
    <build>
src/main/java/com/smartearth/poiexcel/utils/FileHelper.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,431 @@
package com.smartearth.poiexcel.utils;
import com.smartearth.poiexcel.entity.StaticData;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.twmacinta.util.MD5;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.util.List;
/**
 * æ–‡ä»¶å¸®åŠ©ç±»
 * @author WWW
 */
public class FileHelper {
    private final static Log log = LogFactory.getLog(FileHelper.class);
    /**
     * èŽ·å–æ–‡ä»¶å
     *
     * @param file
     * @return
     */
    public static String getFileName(String file) {
        int idx = file.lastIndexOf(File.separator);
        if (idx > -1) {
            return file.substring(idx + 1);
        }
        return "";
    }
    /**
     * èŽ·å–æ–‡ä»¶æ‰©å±•å
     */
    public static String getExtension(File file) {
        if (file == null) {
            return null;
        }
        String fileName = file.getName().toLowerCase();
        int idx = fileName.indexOf(StaticData.POINT);
        if (idx == -1) {
            return "";
        }
        return fileName.substring(idx);
    }
    /**
     * èŽ·å–æ–‡ä»¶æ‰©å±•å
     */
    public static String getExtension(String fileName) {
        if (StringHelper.isEmpty(fileName)) {
            return "";
        }
        int idx = fileName.lastIndexOf(StaticData.POINT);
        if (idx == -1) {
            return "";
        }
        return fileName.substring(idx).toLowerCase();
    }
    /**
     * èŽ·å–å¤šç”¨é€”äº’è”ç½‘é‚®ä»¶æ‰©å±•ç±»åž‹
     *
     * @param ext æ–‡ä»¶æ‰©å±•名
     * @return
     */
    public static String getMime(String ext) {
        switch (ext) {
            // å›¾ç‰‡
            case ".tif":
            case ".tiff":
                return "image/tiff";
            case ".img":
                return "application/x-img";
            case ".gif":
                return "image/gif";
            case ".jpg":
            case ".jpeg":
                return "image/jpeg";
            case ".png":
                return "image/png";
            // éŸ³/视频
            case ".mp3":
                return "audio/mp3";
            case ".mp4":
                return "video/mpeg4";
            case ".avi":
                return "video/avi";
            case ".mpg":
            case ".mpeg":
                return "video/mpg";
            case ".wav":
                return "audio/wav";
            case ".wma":
                return "audio/x-ms-wma";
            case ".swf":
                return "application/x-shockwave-flash";
            case ".wmv":
                return "video/x-ms-wmv";
            case ".rm":
                return "application/vnd.rn-realmedia";
            case ".rmvb":
                return "application/vnd.rn-realmedia-vbr";
            // ç½‘页
            case ".js":
                return "application/x-javascript";
            case ".css":
                return "text/css";
            case ".asp":
                return "text/asp";
            case ".mht":
                return "message/rfc822";
            case ".jsp":
            case ".htm":
            case ".html":
            case ".xhtml":
                return "text/html";
            case ".xml":
            case ".svg":
                return "text/xml";
            // æ–‡ä»¶
            case ".txt":
                return "text/plain";
            case ".dbf":
                return "application/x-dbf";
            case ".mdb":
                return "application/msaccess";
            case ".pdf":
                return "application/pdf";
            case ".ppt":
            case ".pptx":
                return "application/x-ppt";
            case ".doc":
            case ".docx":
                return "application/msword";
            case ".xls":
            case ".xlsx":
                return "application/vnd.ms-excel";
            case ".dgn":
                return "application/x-dgn";
            case ".dwg":
                return "application/x-dwg";
            case ".ext":
                return "application/x-msdownload";
            // é»˜è®¤
            default:
                return "application/octet-stream";
        }
    }
    /**
     * å­—节单位换算
     */
    public static String formatByte(long byteNumber) {
        double kbNumber = byteNumber / StaticData.D1024;
        if (kbNumber < StaticData.D1024) {
            return new DecimalFormat("#.##KB").format(kbNumber);
        }
        double mbNumber = kbNumber / StaticData.D1024;
        if (mbNumber < StaticData.D1024) {
            return new DecimalFormat("#.##MB").format(mbNumber);
        }
        double gbNumber = mbNumber / StaticData.D1024;
        if (gbNumber < StaticData.D1024) {
            return new DecimalFormat("#.##GB").format(gbNumber);
        }
        double tbNumber = gbNumber / StaticData.D1024;
        return new DecimalFormat("#.##TB").format(tbNumber);
    }
    /**
     * èŽ·å–æ–‡ä»¶å¤§å°
     */
    public static String getSizes(double mbNumber) {
        if (mbNumber < StaticData.D1024) {
            return new DecimalFormat("#.##MB").format(mbNumber);
        }
        double gbNumber = mbNumber / StaticData.D1024;
        if (gbNumber < StaticData.D1024) {
            return new DecimalFormat("#.##GB").format(gbNumber);
        }
        double tbNumber = gbNumber / StaticData.D1024;
        return new DecimalFormat("#.##TB").format(tbNumber);
    }
    /**
     * byte转MB
     */
    public static double sizeToMb(long size) {
        if (size < StaticData.D1050) {
            return 0.001;
        }
        String str = String.format("%.3f", size / StaticData.D1024 / StaticData.D1024);
        return Double.parseDouble(str);
    }
    /**
     * 3.获取文件MD5码(JDK)
     */
    public static String getMd5ByJdk(String filePath) throws IOException {
        FileInputStream fileStream = new FileInputStream(filePath);
        String md5 = DigestUtils.md5Hex(fileStream);
        fileStream.close();
        return md5;
    }
    /**
     * 2.获取快速 MD5 ç 
     */
    public static String getFastMd5(String filePath) throws IOException {
        String hash = MD5.asHex(MD5.getHash(new File(filePath)));
        MD5 md5 = new MD5();
        md5.Update(hash, null);
        return md5.asHex();
    }
    /**
     * åˆ é™¤æ–‡ä»¶å¤¹
     *
     * @param dir æ–‡ä»¶å¤¹
     */
    public static void deleteDir(String dir) {
        File file = new File(dir);
        deleteFiles(file);
    }
    /**
     * çº§è”删除文件
     *
     * @param file æ–‡ä»¶
     */
    public static void deleteFiles(File file) {
        if (null == file || !file.exists()) {
            return;
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (null != files && files.length > 0) {
                for (File f : files) {
                    if (f.isDirectory()) {
                        deleteFiles(f);
                    } else {
                        f.delete();
                    }
                }
            }
        }
        file.delete();
    }
    /**
     * èŽ·å–ç›¸å¯¹è·¯å¾„
     *
     * @param file æ–‡ä»¶
     * @return ç›¸å¯¹è·¯å¾„
     */
    public static String getRelativePath(String file) {
        if (StringHelper.isEmpty(file)) {
            return null;
        }
        int idx = file.lastIndexOf(File.separator);
        int start = file.lastIndexOf(File.separator, idx - 1);
        return file.substring(start + 1);
    }
    /**
     * èŽ·å–è·¯å¾„
     *
     * @param file æ–‡ä»¶
     * @return æ–‡ä»¶è·¯å¾„
     */
    public static String getPath(String file) {
        if (StringHelper.isEmpty(file)) {
            return null;
        }
        int end = file.lastIndexOf(File.separator);
        return file.substring(0, end);
    }
    /**
     * 1.获取文件的MD5
     */
    @SuppressWarnings("unused")
    public static String getFileMd5(String filePath) {
        FileInputStream fis = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            fis = new FileInputStream(new File(filePath));
            FileChannel fChannel = fis.getChannel();
            ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 1024);
            while (fChannel.read(buffer) != -1) {
                buffer.flip();
                md.update(buffer);
                buffer.compact();
            }
            byte[] b = md.digest();
            return byteToHexString(b);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        } finally {
            try {
                if (null != fis) {
                    fis.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    /**
     * å­—节码转16进制
     */
    public static String byteToHexString(byte[] tmp) {
        // æ¯ä¸ªå­—节用 16 è¿›åˆ¶è¡¨ç¤ºçš„话,使用两个字符,
        char[] str = new char[16 * 2];
        // æ‰€ä»¥è¡¨ç¤ºæˆ 16 è¿›åˆ¶éœ€è¦ 32 ä¸ªå­—符,表示转换结果中对应的字符位置
        int k = 0;
        // ä»Žç¬¬ä¸€ä¸ªå­—节开始,对 MD5 çš„æ¯ä¸€ä¸ªå­—节
        for (int i = 0; i < StaticData.SIXTEEN; i++) {
            // è½¬æ¢æˆ 16 è¿›åˆ¶å­—符的转换
            byte byte0 = tmp[i];
            // å–字节中高 4 ä½çš„æ•°å­—转换
            str[k++] = StaticData.HEX_DIGITS[byte0 >>> 4 & 0xf];
            // >>> ä¸ºé€»è¾‘右移,将符号位一起右移, å–字节中低 4 ä½çš„æ•°å­—转换
            str[k++] = StaticData.HEX_DIGITS[byte0 & 0xf];
        }
        // æ¢åŽçš„结果转换为字符串
        return new String(str);
    }
    /**
     * èŽ·å–å­—ç¬¦ä¸²çš„MD5码
     */
    public static String getStringMd5(String text) {
        StringBuilder builder = new StringBuilder();
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(text.getBytes(StandardCharsets.UTF_8));
            for (byte aByte : bytes) {
                builder.append(Integer.toHexString((0x000000FF & aByte) | 0xFFFFFF00).substring(6));
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
        return builder.toString();
    }
    /**
     * æ ¹æ®è·¯å¾„获取文件
     */
    public static void getFilesByPath(List<String> list, String path) {
        File file = new File(path);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (null == files) {
                return;
            }
            for (File f : files) {
                if (f.isDirectory()) {
                    getFilesByPath(list, f.getPath());
                } else {
                    list.add(f.getPath());
                }
            }
        } else {
            list.add(file.getPath());
        }
    }
    /**
     * å¤åˆ¶æ–‡ä»¶
     *
     * @param src  æºæ–‡ä»¶
     * @param dest ç›®å½•文件
     */
    public static void copyFile(File src, File dest) throws IOException {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(src);
            os = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        } finally {
            os.close();
            is.close();
        }
    }
}
src/main/java/com/smartearth/poiexcel/utils/StringHelper.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,246 @@
package com.smartearth.poiexcel.utils;
import com.smartearth.poiexcel.entity.StaticData;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * å­—符串帮助类
 * @author WWW
 */
public class StringHelper {
    /**
     * æ•°å­—正则
     */
    public static final Pattern NUMBER_PATTERN = Pattern.compile("-?\\d+(\\.\\d+)?");
    /**
     * æ ¼å¼åŒ–当前系统日期 1
     */
    public static final SimpleDateFormat YMD_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
    /**
     * æ ¼å¼åŒ–当前系统日期 2
     */
    public static final SimpleDateFormat YMDHMS_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * æ ¼å¼åŒ–当前系统日期 3
     */
    public static final SimpleDateFormat YMD2_FORMAT = new SimpleDateFormat("yyyyMMdd");
    /**
     * æ ¼å¼åŒ–当前系统日期 4
     */
    public static final SimpleDateFormat YMDHMS2_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");
    /**
     * åˆ¤æ–­å­—符串,是否为整数
     */
    public static boolean isInteger(String str) {
        return str != null && str.matches("[0-9]+");
    }
    /**
     * åˆ¤æ–­å­—符串,是否为浮点数
     */
    public static boolean isNumeric(String str) {
        return str != null && str.matches("-?\\d+(\\.\\d+)?");
    }
    /**
     * åˆ¤æ–­å­—符串,是否为浮点数
     */
    public static boolean isNumeric2(String str) {
        return str != null && NUMBER_PATTERN.matcher(str).matches();
    }
    /**
     * æ—¥æœŸæ­£åˆ™
     */
    public static Pattern datePattern = Pattern.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/]((((0?[13578])|(1[02]))[\\-\\/]((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/]((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/]((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/]((((0?[13578])|(1[02]))[\\-\\/]((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/]((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/]((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
    /**
     * SQL正则
     */
    public static Pattern sqlPattern = Pattern.compile("|and|exec|execute|insert|select|delete|update|count|drop|\\*|%|chr|mid|master|truncate|char|declare|sitename|net user|xp_cmdshell|;|or|-|\\+|,|like");
    /**
     * å­—符串转为日期
     */
    public static Date parseDate(String str) {
        try {
            return YMD_FORMAT.parse(str);
        } catch (Exception ex) {
            return null;
        }
    }
    /**
     * å­—符串转为日期时间
     */
    public static Date parseTime(String str) {
        try {
            return YMDHMS_FORMAT.parse(str);
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * åˆ¤æ–­å€¼æ˜¯å¦ä¸ºæ—¥æœŸæ ¼å¼
     */
    public static boolean isDate(String strDate) {
        Matcher m = datePattern.matcher(strDate);
        return m.matches();
    }
    /**
     * å­—符串,是否为null æˆ– ""
     */
    public static boolean isNull(String str) {
        return null == str || str.length() == 0;
    }
    /**
     * å­—符串,是否为空null和空格
     */
    public static boolean isEmpty(String str) {
        return null == str || "".equals(str.trim());
    }
    /**
     * èŽ·å– like å­—符串
     */
    public static String getLikeStr(String str) {
        return StringHelper.isEmpty(str) ? null : "%" + str.trim() + "%";
    }
    /**
     * èŽ·å– like å­—符串
     */
    public static String getLikeUpperStr(String str) {
        return StringHelper.isEmpty(str) ? null : "%" + str.trim().toUpperCase() + "%";
    }
    /**
     * èŽ·å– å³like å­—符串
     */
    public static String getRightLike(String str) {
        return StringHelper.isEmpty(str) ? null : str.trim() + "%";
    }
    /**
     * èŽ·å–å›¾å½¢çš„WKT字符串
     *
     * @param wkt
     * @return
     */
    public static String getGeomWkt(String wkt) {
        if (StringHelper.isEmpty(wkt)) {
            return "null";
        }
        return String.format("ST_GeomFromText('%s')", wkt);
    }
    /**
     * é¦–字母大写
     */
    public static String firstCharToUpperCase(String str) {
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }
    /**
     * é¦–字母小写
     */
    public static String firstCharToLowerCase(String str) {
        return str.substring(0, 1).toLowerCase() + str.substring(1);
    }
    /**
     * åˆ¤æ–­å€¼æ˜¯å¦å­˜åœ¨SQL注入
     *
     * @param str å­—符串
     * @return æ˜¯/否
     */
    public static boolean isSqlInjection(String str) {
        if (null == str) {
            return false;
        }
        Matcher m = sqlPattern.matcher(str);
        return m.matches();
    }
    /**
     * æ ¡éªŒå¯†ç æ˜¯/否合法
     *
     * @param pwd å¯†ç 
     * @return æ˜¯/否为无效的
     */
    public static boolean isPwdInvalid(String pwd) {
        return !Pattern.matches(StaticData.PWD_REG, pwd);
    }
    /**
     * èŽ·å–GUID
     *
     * @return
     */
    public static String getGuid() {
        return UUID.randomUUID().toString();
    }
    /**
     * è¿žæŽ¥List集合
     *
     * @param list list æ•´æ•°é›†åˆ
     * @param join join è¿žæŽ¥å­—符
     * @param <T>  æ³›åž‹ç±»
     * @return å­—符串
     */
    public static <T> String join(List<T> list, String join) {
        if (null == list || list.isEmpty()) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (T t : list) {
            if (null != t) {
                sb.append(t.toString() + join);
            }
        }
        if (sb.length() > 0 && sb.lastIndexOf(join) == sb.length() - join.length()) {
            // åˆ é™¤ä»Žç´¢å¼• start å¼€å§‹åˆ° end ä¹‹é—´çš„字符,即 å‰åŒ…括 åŽä¸åŒ…括。
            sb.delete(sb.length() - join.length(), sb.length());
        }
        return sb.toString();
    }
    /**
     * å­—符串转整数集合
     */
    public static List<Integer> strToIntegers(String str) {
        if (StringHelper.isEmpty(str)) {
            return null;
        }
        List<Integer> list = new ArrayList<>();
        for (String s : str.split(StaticData.COMMA)) {
            list.add(Integer.parseInt(s));
        }
        return list;
    }
}
src/main/java/com/smartearth/poiexcel/utils/WebHelper.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,413 @@
package com.smartearth.poiexcel.utils;
import com.alibaba.fastjson.JSON;
import com.smartearth.poiexcel.entity.HttpStatus;
import com.smartearth.poiexcel.entity.ResponseMsg;
import com.smartearth.poiexcel.entity.StaticData;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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.*;
/**
 * Web帮助类
 * @author WWW
 */
public class WebHelper {
    private final static String UNKNOWN = "unknown";
    private final static String COMMA = ",";
    private final static Log log = LogFactory.getLog(WebHelper.class);
    /**
     * ä¿ç•™å°æ•°ä½
     */
    public static double round(double val, double size) {
        double power = Math.pow(10.0, size);
        return Math.round(val * power) / power;
    }
    /**
     * èŽ·å–GUID
     */
    public static String getGuid() {
        return UUID.randomUUID().toString();
    }
    /**
     * èŽ·å–ç”¨æˆ·ip
     */
    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;
    }
    /**
     * èŽ·å–å½“å‰æ—¶é—´çš„Timestamp
     */
    public static Timestamp getCurrentTimestamp() {
        return new Timestamp(System.currentTimeMillis());
    }
    /**
     * èŽ·å–å½“å‰æ—¶é—´æŒ‡å®šåˆ†é’Ÿæ•°åŽçš„Timestamp
     */
    public static Timestamp getTimestamp(int min) {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.MINUTE, min);
        return new Timestamp(now.getTimeInMillis());
    }
    /**
     * ä»ŽCookie中获取token
     */
    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;
    }
    /**
     * å‘Cookie中添加token
     */
    public static void saveToken2Cookie(String token, HttpServletRequest request, HttpServletResponse response) {
        // å…ˆåˆ é™¤
        deleteCookies(request, response);
        // å†ä¿å­˜
        saveCookie(StaticData.TOKEN_COOKIE_KEY, token, response);
    }
    /**
     * ä¿å­˜Cookie
     */
    public static void saveCookie(String key, String value, HttpServletResponse response) {
        Cookie cookie = new Cookie(key, value);
        // è®¾ç½®cookie失效时间,单位为秒
        cookie.setMaxAge(7 * 24 * 60 * 60);
        cookie.setHttpOnly(false);
        cookie.setPath("/");
        //cookie.setDomain("*")
        response.setHeader("P3P", "CP=CAO PSA OUR");
        response.addCookie(cookie);
    }
    /**
     * åˆ é™¤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);
                }
            }
        }
    }
    /**
     * åˆ é™¤æ‰€æœ‰Cookie
     */
    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);
            }
        }
    }
    /**
     * æ ¹æ®é”®èŽ·å–Cookie值
     */
    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;
    }
    /**
     * èŽ·å–Token
     */
    public static String getToken(HttpServletRequest request) {
        // 1.从url参数中,获取token
        String token = request.getParameter(StaticData.TOKEN_KEY);
        // 2.为空,则从header里获取
        if (token == null) {
            token = request.getHeader(StaticData.TOKEN_KEY);
        }
        // 3.还为空,则从cookie里获取
        if (token == null) {
            token = getTokenFromCookie(request);
        }
        return token;
    }
    /**
     * èŽ·å–Request
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getRequest();
    }
    /**
     * èŽ·å–Response
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getResponse();
    }
    /**
     * èŽ·å–Session
     */
    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);
    }
    /**
     * è¾“出str至前端
     */
    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;
    }
    /**
     * è¾“出json至前端
     */
    public static void writeJson2Page(HttpServletResponse res, String str) {
        String json = JSON.toJSONString(new ResponseMsg<>(HttpStatus.ERROR, str));
        writeStr2Page(res, json);
    }
    /**
     * èŽ·å–é”™è¯¯JSON
     */
    public static String getErrJson(HttpStatus status, String msg) {
        return JSON.toJSONString(new ResponseMsg<String>(status, msg));
    }
    /**
     * å†™å“åº”信息
     */
    public static void writeInfo(HttpStatus status, String info, HttpServletResponse res) {
        WebHelper.writeStr2Page(res, WebHelper.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);
    }
    /**
     * ä¸‹è½½æ–‡ä»¶
     *
     * @param file     æ–‡ä»¶
     * @param fileName æ–‡ä»¶å
     * @param res      å“åº”
     * @throws Exception å¼‚常
     */
    public static void download(String file, String fileName, boolean inline, HttpServletResponse res) throws Exception {
        if (StringHelper.isEmpty(fileName)) {
            fileName = StringHelper.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);
        // è®¾ç½®å“åº”头的编码格式为 UTF-8
        res.setCharacterEncoding("UTF-8");
        // é€šè¿‡response对象设置响应数据格式(如:"text/plain; charset=utf-8")
        String ext = FileHelper.getExtension(file);
        String mime = FileHelper.getMime(ext);
        res.setContentType(mime);
        // é€šè¿‡response对象,获取到输出流
        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();
    }
    /**
     * æ‰§è¡Œå‘½ä»¤
     *
     * @param cmd å‘½ä»¤
     */
    public static void exec(String cmd) {
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            process.waitFor();
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    }
    /**
     * èŽ·å–è¯·æ±‚çš„å‚æ•°å€¼
     *
     * @param req è¯·æ±‚
     * @param key å‚数名
     * @return å‚数值
     */
    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;
    }
    /**
     * èŽ·å–è¯·æ±‚çš„å‚æ•°å€¼
     *
     * @param req è¯·æ±‚
     * @param key å‚数名
     * @return å‚数值
     */
    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;
    }
}