From 4ac741b8c15973710727ef8313432eea5a5774d1 Mon Sep 17 00:00:00 2001 From: 13693261870 <252740454@qq.com> Date: 星期四, 05 十月 2023 11:13:39 +0800 Subject: [PATCH] 添加帮助类的依赖工具 --- src/main/java/com/smartearth/poiexcel/utils/StringHelper.java | 246 ++++++++++++ src/main/java/com/smartearth/poiexcel/utils/FileHelper.java | 431 ++++++++++++++++++++++ pom.xml | 6 src/main/java/com/smartearth/poiexcel/utils/WebHelper.java | 413 +++++++++++++++++++++ 4 files changed, 1,096 insertions(+), 0 deletions(-) diff --git a/pom.xml b/pom.xml index 9f562fe..a1ea8d8 100644 --- a/pom.xml +++ b/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> diff --git a/src/main/java/com/smartearth/poiexcel/utils/FileHelper.java b/src/main/java/com/smartearth/poiexcel/utils/FileHelper.java new file mode 100644 index 0000000..5f5fca5 --- /dev/null +++ b/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杞琈B + */ + 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.鑾峰彇鏂囦欢鐨凪D5 + */ + @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(); + } + } +} diff --git a/src/main/java/com/smartearth/poiexcel/utils/StringHelper.java b/src/main/java/com/smartearth/poiexcel/utils/StringHelper.java new file mode 100644 index 0000000..a82781e --- /dev/null +++ b/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 { + /** + * 鏁板瓧姝e垯 + */ + 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(); + } + + /** + * 鏃ユ湡姝e垯 + */ + 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姝e垯 + */ + 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(); + } + + /** + * 瀛楃涓诧紝鏄惁涓簄ull 鎴� "" + */ + 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() + "%"; + } + + /** + * 鑾峰彇 鍙砽ike 瀛楃涓� + */ + public static String getRightLike(String str) { + return StringHelper.isEmpty(str) ? null : str.trim() + "%"; + } + + /** + * 鑾峰彇鍥惧舰鐨刉KT瀛楃涓� + * + * @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); + } + + /** + * 鍒ゆ柇鍊兼槸鍚﹀瓨鍦⊿QL娉ㄥ叆 + * + * @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; + } +} diff --git a/src/main/java/com/smartearth/poiexcel/utils/WebHelper.java b/src/main/java/com/smartearth/poiexcel/utils/WebHelper.java new file mode 100644 index 0000000..a40a78a --- /dev/null +++ b/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; + } + + /** + * 鑾峰彇褰撳墠鏃堕棿鐨凾imestamp + */ + public static Timestamp getCurrentTimestamp() { + return new Timestamp(System.currentTimeMillis()); + } + + /** + * 鑾峰彇褰撳墠鏃堕棿鎸囧畾鍒嗛挓鏁板悗鐨凾imestamp + */ + public static Timestamp getTimestamp(int min) { + Calendar now = Calendar.getInstance(); + now.add(Calendar.MINUTE, min); + + return new Timestamp(now.getTimeInMillis()); + } + + /** + * 浠嶤ookie涓幏鍙杢oken + */ + 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; + } + + /** + * 鍚慍ookie涓坊鍔爐oken + */ + 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); + } + } + } + } + + /** + * 鍒犻櫎鎵�鏈塁ookie + */ + 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); + } + } + } + + /** + * 鏍规嵁閿幏鍙朇ookie鍊� + */ + 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.浠巙rl鍙傛暟涓紝鑾峰彇token + String token = request.getParameter(StaticData.TOKEN_KEY); + + // 2.涓虹┖锛屽垯浠巋eader閲岃幏鍙� + 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; + } +} -- Gitblit v1.9.3