From 050294412168d3b33cfea1595d50e0ebfb393dde Mon Sep 17 00:00:00 2001 From: 13693261870 <252740454@qq.com> Date: 星期五, 06 十二月 2024 14:01:51 +0800 Subject: [PATCH] 1 --- se-modules/se-system/src/main/java/com/se/system/utils/RestUtils.java | 201 ++++++ se-modules/se-system/src/main/java/com/se/system/utils/FileUtils.java | 364 ++++++++++++ se-modules/se-system/src/main/java/com/se/system/utils/JsonUtils.java | 42 + se-modules/se-system/src/main/java/com/se/system/utils/AesUtils.java | 59 + se-modules/se-system/src/main/java/com/se/system/utils/SpringContextUtils.java | 41 + se-modules/se-system/src/main/java/com/se/system/domain/StaticData.java | 262 ++++++++ se-modules/se-system/src/main/java/com/se/system/utils/StringUtils.java | 153 +++++ se-modules/se-system/src/main/java/com/se/system/utils/HttpUtils.java | 269 ++++++++ se-modules/se-system/src/main/java/com/se/system/utils/EnumUtils.java | 58 + se-modules/se-system/src/main/java/com/se/system/utils/WebUtils.java | 304 ++++++++++ 10 files changed, 1,753 insertions(+), 0 deletions(-) diff --git a/se-modules/se-system/src/main/java/com/se/system/domain/StaticData.java b/se-modules/se-system/src/main/java/com/se/system/domain/StaticData.java new file mode 100644 index 0000000..5edf55d --- /dev/null +++ b/se-modules/se-system/src/main/java/com/se/system/domain/StaticData.java @@ -0,0 +1,262 @@ +package com.se.system.domain; + +import com.alibaba.fastjson.JSON; +import com.se.common.core.constant.HttpStatus; +import com.se.common.core.web.domain.AjaxResult; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +@SuppressWarnings("ALL") +public class StaticData { + /** + * 鏉冮檺鎺掗櫎璺緞锛�/proxy锛岃姹傚叏閮ㄥ皬鍐� + */ + public static String[] EXCLUDE_PATH = new String[]{"/sign/", "/perms/", "/fmeit/", "/crds/", "/floatserver/", "/wmts/select", "/onemap/", "/swagger", "/error"}; + + public final static int I1 = 1; + + public final static int I2 = 2; + + public final static int FOUR = 4; + + public final static int I5 = 5; + + public final static int NINE = 9; + + public final static int I10 = 10; + + public final static int I16 = 16; + + public final static int TWO_HUNDRED = 200; + + public final static int I100000 = 100000; + + public final static int I1000000 = 1000000; + + public static final double D90 = 90.0; + + public static final double D100 = 100.0; + + public static final double D1024 = 1024.0; + + public static final double D1050 = 1050.0; + + public static final int I12 = 12; + + public static final int I23 = 23; + + public static final int I24 = 24; + + public static final int I31 = 31; + + public static final int I50 = 50; + + public static final int I60 = 60; + + public static final int I90 = 90; + + public static final int I90_NEG = -90; + + public final static int I100 = 100; + + public final static int I120 = 120; + + public static final int I180 = 180; + + public static final int I180_NEG = -180; + + public static final int I1000 = 1000; + + public static final int I2050 = 2050; + + public static final int I4326 = 4326; + + public static final int I4490 = 4490; + + public final static String S1 = "1"; + + public final static String EQ = "="; + + public final static String POINT = "."; + + public final static String COMMA = ","; + + public final static String TILDE = "~"; + + public final static String SINGLE_QUOTES = "'"; + + public final static String SLASH = "/"; + + public final static String IN = "in"; + + public final static String DWG = "dwg"; + + public final static String ZIP = ".zip"; + + public final static String XLS = ".xls"; + + public final static String XLSX = ".xlsx"; + + public final static String MDB = ".mdb"; + + public final static String KML = ".kml"; + + public final static String SHP = ".shp"; + + public final static String NGDB = "gdb"; + + public final static String GDB = ".gdb"; + + public final static String JPG = ".jpg"; + + public final static String IMG = ".img"; + + public final static String MPT = ".mpt"; + + public final static String D3DML = ".3dml"; + + public final static String TIF = ".tif"; + + public final static String TIFF = ".tiff"; + + public final static String LAS = ".las"; + + public final static String OSGB = ".osgb"; + + public static String ADMIN = "admin"; + + public final static String SYS_META = "sysmeta"; + + public final static String VERSION = "1.0.0"; + + public final static String TOKEN_KEY = "token"; + + public static int COOKIE_MAX_AGE = 4 * 60 * 60; + + public final static String TOKEN_COOKIE_KEY = "token"; + + public final static String TEXT_ENCODER = "UTF-8"; + + public final static String CHECK_MAIN = "checkMain"; + + public final static String OBJECT = "java.lang.Object"; + + public final static String DRUID_COOKIE_KEY = "JSESSIONID"; + + public final static String YES = "YES"; + + public final static String NO = "NO"; + + public final static String LINESTRING = "LINESTRING"; + + public final static String MULTILINESTRING = "MULTILINESTRING"; + + public final static String POLYGON = "POLYGON"; + + public final static String MULTIPOLYGON = "MULTIPOLYGON"; + + public final static String MULTICURVE = "MULTICURVE"; + + public final static String COMPOUNDCURVE = "COMPOUNDCURVE"; + + public final static String CGCS2000 = "CGCS2000"; + + public static final String NO_FILE = JSON.toJSONString(new AjaxResult(HttpStatus.NOT_FOUND, "鏂囦欢鎵句笉鍒�")); + + /** + * 16杩涘埗 + */ + public static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + + /** + * 鏍呮牸鏁版嵁鎵╁睍鍚� + */ + public final static List<String> RASTER_EXT = new ArrayList<>(Arrays.asList(".img", ".tif", ".tiff", ".jpg", ".jp2")); + + /** + * 瀵嗙爜姝e垯琛ㄨ揪寮� + */ + public final static String PWD_REG = "^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W!@#$%^&*`~()\\-_+=,.?;<>]+$)(?![a-z0-9]+$)(?![a-z\\W!@#$%^&*`~()\\-_+=,.?;<>]+$)(?![0-9\\W!@#$%^&*`~()\\-_+=,.?;<>]+$)[a-zA-Z0-9\\W!@#$%^&*`~()\\-_+=,.?;<>]{12,20}$"; + + /** + * MPT鏂囦欢鎵╁睍鍚� + */ + public final static List<String> MPT_EXT = new ArrayList<>(Arrays.asList(".midx", ".strmi", ".ei.midx", ".ei.mpt", ".ei.strmi")); + + /** + * JPG鏂囦欢鎵╁睍鍚� + */ + public final static List<String> JPG_EXT = new ArrayList<>(Arrays.asList(".jpg.aux.xml", ".jpg.ovr", ".jpg.xml", ".jgw", ".prj")); + + /** + * JP2鏂囦欢鎵╁睍鍚� + */ + public final static List<String> JP2_EXT = new ArrayList<>(Arrays.asList(".jp2.aux.xml", ".jp2.ovr", ".jp2.xml", ".jgw", ".prj", ".jp2.html", ".jp2.txt")); + + /** + * IMG鏂囦欢鎵╁睍鍚� + */ + public final static List<String> IMG_EXT = new ArrayList<>(Arrays.asList(".rrd", ".img.aux.xml", ".hdr", ".img.enp", ".img.xml")); + + /** + * TIF鏂囦欢鎵╁睍鍚� + */ + public final static List<String> TIF_EXT = new ArrayList<>(Arrays.asList(".prj", ".tfw", ".aux", ".tif.ovr", ".tif.aux.xml", ".tif.xml")); + + /** + * TIFF鏂囦欢鎵╁睍鍚� + */ + public final static List<String> TIFF_EXT = new ArrayList<>(Arrays.asList(".prj", ".tfw", ".aux", ".tiff.ovr", ".tiff.aux.xml", ".tiff.xml")); + + /** + * SHP鏂囦欢鎵╁睍鍚� + */ + public final static List<String> SHP_EXT = new ArrayList<>(Arrays.asList(".shx", ".dbf", ".prj", ".cpg")); + + /** + * Mapper鎺掗櫎鎵╁睍鍚� + */ + public final static List<String> MAPPER_EXCLUDE_EXT = new ArrayList<>(Arrays.asList(".jpg.aux.xml", ".jpg.xml", ".jp2.aux.xml", ".jp2.xml", ".jp2.html", ".jp2.txt", ".img.aux.xml", ".img.xml", ".tif.aux.xml", ".tif.xml", ".tiff.aux.xml", ".tiff.xml", ".shp.xml", ".ecw.xml", "ecw.aux.xml")); + + /** + * 鎵�鏈夋枃浠舵墿灞曞悕 + */ + public final static List<String> ALL_EXTENSION = new ArrayList<>(Arrays.asList(".txt", ".xml", ".pdf", ".xls", ".xlsx", ".doc", ".docx", ".ppt", ".pptx", ".shp", ".gdb", ".mdb", ".dwg", ".las", ".laz", ".cpt", ".mpt", ".ei.mpt", ".fly", ".efb", ".g3d", ".fbx", ".obj", ".3dm", ".3dml", ".osgb", ".rvt", ".ifc", ".jpg", ".jp2", ".png", ".img", ".tif", ".tiff", ".dem", ".bmp", ".gif", ".rmvb", ".rm", ".mp3", ".mp4", ".avi", ".wma", ".wmv", ".7z", ".rar", ".zip", ".lz", ".kml")); + + /** + * 鎻掑叆鎺掗櫎瀛楁 + */ + public final static List<String> INSERT_EXCLUDE_FIELDS = new ArrayList<>(Arrays.asList("gid", "objectid", "updateuser", "updatetime", "shape_leng", "shape_area", "serialVersionUID", "dirName", "depName", "verName", "createName", "updateName")); + + /** + * 鏇存柊鎺掗櫎瀛楁 + */ + public final static List<String> UPDATE_EXCLUDE_FIELDS = new ArrayList<>(Arrays.asList("objectid", "createuser", "createtime", "shape_leng", "shape_area", "serialVersionUID", "dirName", "depName", "verName", "createName", "updateName")); + + /** + * 璇诲彇鎺掗櫎瀛楁 + */ + public final static List<String> READ_EXCLUDE_FIELDS = new ArrayList<>(Arrays.asList("gid", "eventid", "parentid", "objectid", "dirid", "depid", "verid", "createtime", "createuser", "updateuser", "updatetime", "shape_leng", "shape_area", "serialversionuid", "dirname", "depname", "vername", "createname", "updatename")); + + /** + * MDB鎺掗櫎瀛楁 + */ + public final static List<String> MDB_EXCLUDE_FIELDS = new ArrayList<>(Arrays.asList("Shape", "SHAPE_LENG", "Shape_Length", "Shape_Area", "OBJECTID_1")); + + /** + * 鏍囩粯Shp鎺掗櫎瀛楁 + */ + public final static List<String> MARK_EXCLUDE_FIELDS = new ArrayList<>(Arrays.asList("wkt", "geom", "objectid", "shape_leng", "shape_area", "serialVersionUID", "dirName", "depName", "verName", "createName", "updateName")); + + /** + * GDB鎺掗櫎瀛楁 + */ + public final static List<String> GDB_EXCLUDE_FIELDS = new ArrayList<>(Arrays.asList("geom", "objectid", "shape_leng", "shape_area", "serialVersionUID", "dirName", "depName", "verName", "createName", "updateName")); + + /** + * 绠$嚎鎺掗櫎瀛楁 + */ + public final static List<String> PIPE_EXCLUDE_FIELDS = new ArrayList<>(Arrays.asList("serialVersionUID", "tabs", "pwd", "gid", "wkt")); +} diff --git a/se-modules/se-system/src/main/java/com/se/system/utils/AesUtils.java b/se-modules/se-system/src/main/java/com/se/system/utils/AesUtils.java new file mode 100644 index 0000000..6999d82 --- /dev/null +++ b/se-modules/se-system/src/main/java/com/se/system/utils/AesUtils.java @@ -0,0 +1,59 @@ +package com.se.system.utils; + +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; +import java.util.Base64; + +@SuppressWarnings("ALL") +public class AesUtils { + private static final String DEFAULT_KEY = "A#s_lF_sErve_k.y"; + + private static final String KEY_ALGORITHM = "AES"; + + private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding"; + + public static String decrypt(String encrypt) throws Exception { + return decrypt(encrypt, DEFAULT_KEY); + } + + public static String encrypt(String content) throws Exception { + return encrypt(content, DEFAULT_KEY); + } + + private static String base64Encode(byte[] bytes) { + return Base64.getEncoder().encodeToString(bytes); + } + + private static byte[] base64Decode(String base64Code) { + return StringUtils.isEmpty(base64Code) ? null : Base64.getDecoder().decode(base64Code); + } + + private static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception { + // KeyGenerator kGen = KeyGenerator.getInstance(KEY_ALGORITHM) + // kGen.init(128) + + Cipher cipher = Cipher.getInstance(ALGORITHMSTR); + cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), KEY_ALGORITHM)); + + return cipher.doFinal(content.getBytes("utf-8")); + } + + public static String encrypt(String content, String encryptKey) throws Exception { + return base64Encode(aesEncryptToBytes(content, encryptKey)); + } + + public static String decrypt(String encryptStr, String decryptKey) throws Exception { + return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey); + } + + private static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception { + // KeyGenerator kGen = KeyGenerator.getInstance(KEY_ALGORITHM) + // kGen.init(128) + + Cipher cipher = Cipher.getInstance(ALGORITHMSTR); + cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), KEY_ALGORITHM)); + byte[] decryptBytes = cipher.doFinal(encryptBytes); + + return new String(decryptBytes); + } +} diff --git a/se-modules/se-system/src/main/java/com/se/system/utils/EnumUtils.java b/se-modules/se-system/src/main/java/com/se/system/utils/EnumUtils.java new file mode 100644 index 0000000..2499dc3 --- /dev/null +++ b/se-modules/se-system/src/main/java/com/se/system/utils/EnumUtils.java @@ -0,0 +1,58 @@ +package com.se.system.utils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.reflect.Method; + +@SuppressWarnings("ALL") +public class EnumUtils { + private static final String GETTER_PREFIX = "get"; + + private static final Logger log = LoggerFactory.getLogger(EnumUtils.class); + + public static <T extends Enum<T>> T nameOf(Class<T> clazz, String name) { + return Enum.valueOf(clazz, name); + } + + public static <T extends Enum<T>> T getByString(Class<T> clazz, String propertyName, String value) { + String getterMethodName = GETTER_PREFIX + StringUtils.firstCharToUpperCase(propertyName); + T result = null; + try { + T[] arr = clazz.getEnumConstants(); + Method targetMethod = clazz.getDeclaredMethod(getterMethodName); + String typeCodeVal = null; + for (T entity : arr) { + typeCodeVal = targetMethod.invoke(entity).toString(); + if (typeCodeVal.contentEquals(value)) { + result = entity; + break; + } + } + } catch (Exception ex) { + log.error(ex.getMessage(), ex); + } + + return result; + } + + public static <T extends Enum<T>> T getByInt(Class<T> clazz, String propertyName, int value) { + String getterMethodName = GETTER_PREFIX + StringUtils.firstCharToUpperCase(propertyName); + T result = null; + try { + T[] arr = clazz.getEnumConstants(); + Method targetMethod = clazz.getDeclaredMethod(getterMethodName); + int typeCodeVal; + for (T entity : arr) { + typeCodeVal = Integer.parseInt(targetMethod.invoke(entity).toString()); + if (typeCodeVal == value) { + result = entity; + break; + } + } + } catch (Exception ex) { + log.error(ex.getMessage(), ex); + } + return result; + } +} diff --git a/se-modules/se-system/src/main/java/com/se/system/utils/FileUtils.java b/se-modules/se-system/src/main/java/com/se/system/utils/FileUtils.java new file mode 100644 index 0000000..226765f --- /dev/null +++ b/se-modules/se-system/src/main/java/com/se/system/utils/FileUtils.java @@ -0,0 +1,364 @@ +package com.se.system.utils; + +import com.se.system.domain.StaticData; +import org.apache.commons.codec.digest.DigestUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import java.io.*; +import java.net.URL; +import java.net.URLDecoder; +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; + +@SuppressWarnings("ALL") +public class FileUtils { + private static final Logger log = LoggerFactory.getLogger(FileUtils.class); + + 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 (StringUtils.isEmpty(fileName)) { + return ""; + } + + int idx = fileName.lastIndexOf(StaticData.POINT); + if (idx == -1) { + return ""; + } + + return fileName.substring(idx).toLowerCase(); + } + + 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); + } + + 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); + } + + public static String getMd5ByJdk(String filePath) throws IOException { + FileInputStream fileStream = new FileInputStream(filePath); + String md5 = DigestUtils.md5Hex(fileStream); + fileStream.close(); + + return md5; + } + + public static void deleteDir(String dir) { + File file = new File(dir); + + deleteFiles(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(); + } + + public static String getRelativePath(String file) { + if (StringUtils.isEmpty(file)) { + return null; + } + + int idx = file.lastIndexOf(File.separator); + int start = file.lastIndexOf(File.separator, idx - 1); + + return file.substring(start + 1); + } + + public static String getPath(String file) { + if (StringUtils.isEmpty(file)) { + return null; + } + + int end = file.lastIndexOf(File.separator); + + return file.substring(0, end); + } + + @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(); + } + } + } + + public static String byteToHexString(byte[] tmp) { + char[] str = new char[16 * 2]; + + int k = 0; + for (int i = 0; i < StaticData.I16; i++) { + byte byte0 = tmp[i]; + str[k++] = StaticData.HEX_DIGITS[byte0 >>> 4 & 0xf]; + str[k++] = StaticData.HEX_DIGITS[byte0 & 0xf]; + } + return new String(str); + } + + 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()); + } + } + + 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(); + } + } + + public static String filter(String str) { + return str.replaceAll("/\\*[\\s\\S]*?\\*/", ""); + } + + public static String decode(String str) { + try { + return URLDecoder.decode(str, "UTF-8"); + } catch (Exception ex) { + log.error(ex.getMessage(), ex); + return null; + } + } + + public static String getClassPathForJar() { + URL resource = ClassLoader.getSystemResource(""); + if (null == resource) { + return null; + } + + return decode(filter(resource.getPath())); + } + + public static String getClassPathForWar() throws IOException { + ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(); + + return context.getResource("").getFile().getAbsolutePath(); + } +} diff --git a/se-modules/se-system/src/main/java/com/se/system/utils/HttpUtils.java b/se-modules/se-system/src/main/java/com/se/system/utils/HttpUtils.java new file mode 100644 index 0000000..c6f142e --- /dev/null +++ b/se-modules/se-system/src/main/java/com/se/system/utils/HttpUtils.java @@ -0,0 +1,269 @@ +package com.se.system.utils; + +import org.apache.http.*; +import org.apache.http.client.config.CookieSpecs; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.utils.URIUtils; +import org.apache.http.entity.InputStreamEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicHeader; +import org.apache.http.message.BasicHttpEntityEnclosingRequest; +import org.apache.http.message.BasicHttpRequest; +import org.apache.http.message.HeaderGroup; +import org.apache.http.util.EntityUtils; + +import javax.servlet.ServletException; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.net.HttpCookie; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Enumeration; + +@SuppressWarnings("ALL") +public class HttpUtils { + private final static String HTTP_SLASH2 = "://"; + + private final static String HTTP_SLASH = "/"; + + private final static Integer THREE = 3; + + protected static final HeaderGroup HOP_HEADERS; + + static { + HOP_HEADERS = new HeaderGroup(); + + String[] headers = new String[]{ + "Connection", "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization", + "TE", "Trailers", "Transfer-Encoding", "Upgrade", + //"X-RateLimit-Burst-Capacity", "X-RateLimit-Remaining", "X-RateLimit-Replenish-Rate", + "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials", "Access-Control-Allow-Headers"}; + + for (String header : headers) { + HOP_HEADERS.addHeader(new BasicHeader(header, null)); + } + } + + public void service(HttpServletRequest request, HttpServletResponse response, String url) throws ServletException, IOException { + HttpRequest proxyRequest; + if (request.getHeader(HttpHeaders.CONTENT_LENGTH) != null || request.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { + proxyRequest = newProxyRequestWithEntity(request, url); + } else { + proxyRequest = new BasicHttpRequest(request.getMethod(), url); + } + + HttpHost host = this.getTargetHost(url); + // copyRequestHeaders(request, proxyRequest, host); + //setXrForwardedForHeader(request, proxyRequest); + + // if (!StringHelper.isEmpty(cookie)) proxyRequest.addHeader("Cookie", cookie + "; ") + + CloseableHttpClient client = null; + HttpResponse proxyResponse = null; + try { + client = this.createHttpClient(); + proxyResponse = client.execute(host, proxyRequest); + + int statusCode = proxyResponse.getStatusLine().getStatusCode(); + // response.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()) + response.setStatus(statusCode); + + copyResponseHeaders(proxyResponse, request, response, url); + + if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) { + response.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0); + } else { + copyResponseEntity(proxyResponse, request, response); + } + } catch (Exception ex) { + throw new ServletException(ex.getMessage()); + } finally { + if (proxyResponse != null) { + EntityUtils.consumeQuietly(proxyResponse.getEntity()); + } + if (client != null) { + client.close(); + } + } + } + + protected HttpRequest newProxyRequestWithEntity(HttpServletRequest request, String url) throws IOException { + String method = request.getMethod(); + HttpEntityEnclosingRequest proxyRequest = new BasicHttpEntityEnclosingRequest(method, url); + proxyRequest.setEntity(new InputStreamEntity(request.getInputStream(), getContentLength(request))); + //String str = EntityUtils.toString(proxyRequest.getEntity(), "UTF-8") + + return proxyRequest; + } + + private long getContentLength(HttpServletRequest request) { + String contentLengthHeader = request.getHeader("Content-Length"); + if (contentLengthHeader != null) { + return Long.parseLong(contentLengthHeader); + } + + return -1L; + } + + protected void copyRequestHeaders(HttpServletRequest request, HttpRequest proxyRequest, HttpHost host) { + @SuppressWarnings("unchecked") + Enumeration<String> enumerationOfHeaderNames = request.getHeaderNames(); + + while (enumerationOfHeaderNames.hasMoreElements()) { + String headerName = enumerationOfHeaderNames.nextElement(); + copyRequestHeader(request, proxyRequest, host, headerName); + } + } + + protected void copyRequestHeader(HttpServletRequest request, HttpRequest proxyRequest, HttpHost host, String headerName) { + if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH) || HOP_HEADERS.containsHeader(headerName)) { + return; + } + + @SuppressWarnings("unchecked") + Enumeration<String> headers = request.getHeaders(headerName); + while (headers.hasMoreElements()) { + String headerValue = headers.nextElement(); + if (headerName.equalsIgnoreCase(HttpHeaders.HOST)) { + headerValue = host.getHostName(); + if (host.getPort() != -1) { + headerValue += ":" + host.getPort(); + } + } else if (headerName.equalsIgnoreCase(org.apache.http.cookie.SM.COOKIE)) { + headerValue = getRealCookie(headerValue); + } + + proxyRequest.addHeader(headerName, headerValue); + } + } + + protected HttpHost getTargetHost(String url) throws ServletException { + try { + URI uri = new URI(url); + + return URIUtils.extractHost(uri); + } catch (URISyntaxException ex) { + throw new ServletException(ex.getMessage()); + } + } + + protected String getRealCookie(String cookieValue) { + StringBuilder escapedCookie = new StringBuilder(); + String[] cookies = cookieValue.split("[;,]"); + for (String cookie : cookies) { + String[] cookieSplit = cookie.split("="); + if (cookieSplit.length == 2) { + String cookieName = cookieSplit[0].trim(); + if (cookieName.startsWith(cookieName)) { + cookieName = cookieName.substring(cookieName.length()); + if (escapedCookie.length() > 0) { + escapedCookie.append("; "); + } + escapedCookie.append(cookieName).append("=").append(cookieSplit[1].trim()); + } + } + } + + return escapedCookie.toString(); + } + + private void setXrForwardedForHeader(HttpServletRequest request, HttpRequest proxyRequest) { + String forHeaderName = "X-Forwarded-For"; + String forHeader = request.getRemoteAddr(); + String existingForHeader = request.getHeader(forHeaderName); + if (existingForHeader != null) { + forHeader = existingForHeader + ", " + forHeader; + } + proxyRequest.setHeader(forHeaderName, forHeader); + + String protoHeaderName = "X-Forwarded-Proto"; + String protoHeader = request.getScheme(); + proxyRequest.setHeader(protoHeaderName, protoHeader); + } + + protected CloseableHttpClient createHttpClient() { + RequestConfig requestConfig = RequestConfig.custom() + .setRedirectsEnabled(false) + .setCookieSpec(CookieSpecs.IGNORE_COOKIES) + .setConnectTimeout(-1) + .setSocketTimeout(-1) + .build(); + + // return HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build() + return HttpClients.custom() + .setDefaultRequestConfig(requestConfig) + .build(); + } + + protected void copyResponseHeaders(HttpResponse proxyResponse, HttpServletRequest request, HttpServletResponse response, String url) { + for (Header header : proxyResponse.getAllHeaders()) { + copyResponseHeader(request, response, header, url); + } + } + + protected void copyResponseHeader(HttpServletRequest request, HttpServletResponse response, Header header, String url) { + String headerName = header.getName(); + if (HOP_HEADERS.containsHeader(headerName)) { + return; + } + + String headerValue = header.getValue(); + if (headerName.equalsIgnoreCase(org.apache.http.cookie.SM.SET_COOKIE) || headerName.equalsIgnoreCase(org.apache.http.cookie.SM.SET_COOKIE2)) { + copyProxyCookie(request, response, headerValue); + } else if (headerName.equalsIgnoreCase(HttpHeaders.LOCATION)) { + response.addHeader(headerName, rewriteUrlFromResponse(request, url, headerValue)); + } else { + response.addHeader(headerName, headerValue); + } + } + + protected void copyProxyCookie(HttpServletRequest request, HttpServletResponse response, String headerValue) { + String path = request.getContextPath() + request.getServletPath(); + if (path.isEmpty()) { + path = "/"; + } + + for (HttpCookie cookie : HttpCookie.parse(headerValue)) { + Cookie servletCookie = new Cookie(cookie.getName(), cookie.getValue()); + servletCookie.setComment(cookie.getComment()); + servletCookie.setMaxAge((int) cookie.getMaxAge()); + servletCookie.setPath(path); + + servletCookie.setSecure(cookie.getSecure()); + servletCookie.setVersion(cookie.getVersion()); + response.addCookie(servletCookie); + } + } + + protected String rewriteUrlFromResponse(HttpServletRequest request, String targetUri, String theUrl) { + if (theUrl.startsWith(targetUri)) { + StringBuffer curUrl = request.getRequestURL(); + + int pos; + if ((pos = curUrl.indexOf(HTTP_SLASH2)) >= 0) { + if ((pos = curUrl.indexOf(HTTP_SLASH, pos + THREE)) >= 0) { + curUrl.setLength(pos); + } + } + + curUrl.append(request.getContextPath()); + curUrl.append(request.getServletPath()); + curUrl.append(theUrl, targetUri.length(), theUrl.length()); + + return curUrl.toString(); + } + + return theUrl; + } + + protected void copyResponseEntity(HttpResponse proxyResponse, HttpServletRequest request, HttpServletResponse response) throws IOException { + HttpEntity entity = proxyResponse.getEntity(); + if (null == entity) { + return; + } + entity.writeTo(response.getOutputStream()); + } +} diff --git a/se-modules/se-system/src/main/java/com/se/system/utils/JsonUtils.java b/se-modules/se-system/src/main/java/com/se/system/utils/JsonUtils.java new file mode 100644 index 0000000..6b80fd0 --- /dev/null +++ b/se-modules/se-system/src/main/java/com/se/system/utils/JsonUtils.java @@ -0,0 +1,42 @@ +package com.se.system.utils; + +import com.alibaba.fastjson.JSONObject; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.List; + +@SuppressWarnings("ALL") +public class JsonUtils { + @SuppressWarnings("unchecked") + public static LinkedHashMap<String, Object> json2Map(String json) throws IOException { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true).configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); + return mapper.readValue(json, LinkedHashMap.class); + } + + public static String map2Json(Object obj) throws IOException { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true).configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); + return mapper.writeValueAsString(obj); + } + + @SuppressWarnings("unchecked") + public static List<LinkedHashMap<String, Object>> json2ListMap(String json) throws IOException { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true).configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); + return mapper.readValue(json, List.class); + } + + public static <T> T json2Object(String json, Class<T> valueType) throws IOException { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true).configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); + return mapper.readValue(json, valueType); + } + + public static <T> T obj2Vo(Object obj, Class<T> valueType) { + return JSONObject.parseObject(JSONObject.toJSONString(obj), valueType); + } +} diff --git a/se-modules/se-system/src/main/java/com/se/system/utils/RestUtils.java b/se-modules/se-system/src/main/java/com/se/system/utils/RestUtils.java new file mode 100644 index 0000000..d67f3c8 --- /dev/null +++ b/se-modules/se-system/src/main/java/com/se/system/utils/RestUtils.java @@ -0,0 +1,201 @@ +package com.se.system.utils; + +import com.se.system.domain.StaticData; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpEntity; +import org.apache.http.NameValuePair; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.springframework.web.client.RestTemplate; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +@SuppressWarnings("ALL") +public class RestUtils { + private static RestTemplate restTemplate; + + private final static Log log = LogFactory.getLog(RestUtils.class); + + public static RestTemplate getRestTemplate() { + if (restTemplate == null) { + restTemplate = SpringContextUtils.getBean(RestTemplate.class); + } + + return restTemplate; + } + + public static String getForConn(String url) throws IOException { + BufferedReader br = null; + HttpURLConnection conn = null; + + try { + URL restUrl = new URL(url); + + conn = (HttpURLConnection) restUrl.openConnection(); + // POST,GET,PUT,DELETE + conn.setRequestMethod("GET"); + conn.setRequestProperty("Accept", "application/json"); + + br = new BufferedReader(new InputStreamReader(conn.getInputStream())); + + String line; + StringBuilder sb = new StringBuilder(); + while ((line = br.readLine()) != null) { + sb.append(line); + } + + return sb.toString(); + } finally { + if (br != null) { + br.close(); + } + if (conn != null) { + conn.disconnect(); + } + } + } + + public static String postForConn(String url, String query) throws IOException { + BufferedReader br = null; + HttpURLConnection conn = null; + + try { + URL restUrl = new URL(url); + + conn = (HttpURLConnection) restUrl.openConnection(); + conn.setRequestMethod("POST"); + conn.setRequestProperty("Content-Type", "application/json"); + conn.setDoOutput(true); + + PrintStream ps = new PrintStream(conn.getOutputStream()); + ps.print(query); + ps.close(); + + // OutputStream out = conn.getOutputStream() + // out.write(query.getBytes()) + // out.close() + + br = new BufferedReader(new InputStreamReader(conn.getInputStream())); + + String line; + StringBuilder sb = new StringBuilder(); + while ((line = br.readLine()) != null) { + sb.append(line); + } + + return sb.toString(); + } finally { + if (br != null) { + br.close(); + } + if (conn != null) { + conn.disconnect(); + } + } + } + + public static String get(String uri) { + try { + CloseableHttpClient httpClient = HttpClients.custom().build(); + + HttpGet httpGet = new HttpGet(uri); + + CloseableHttpResponse closeResponse = httpClient.execute(httpGet); + + HttpEntity entity = closeResponse.getEntity(); + + return EntityUtils.toString(entity, StaticData.TEXT_ENCODER); + } catch (Exception ex) { + log.error(ex.getMessage(), ex); + + return getErrorInfo(uri, ex); + } + } + + public static String post(String uri, List<NameValuePair> postData) { + try { + CloseableHttpClient httpClient = HttpClients.custom().build(); + + UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(postData, StaticData.TEXT_ENCODER); + HttpPost httpPost = new HttpPost(uri); + httpPost.setEntity(postEntity); + + CloseableHttpResponse closeResponse = httpClient.execute(httpPost); + + HttpEntity entity = closeResponse.getEntity(); + + return EntityUtils.toString(entity, StaticData.TEXT_ENCODER); + } catch (Exception ex) { + log.error(ex.getMessage(), ex); + + return getErrorInfo(uri, ex); + } + } + + public static String getErrorInfo(String uri, Exception ex) { + Map<String, Object> map = new LinkedHashMap<>(); + map.put("result", null); + map.put("message", ex.getMessage()); + map.put("code", 400); + map.put("uri", uri); + //map.put("tag", StaticData.CACHE_PREFIX) + + return map.toString(); + } + + public static String getForRest(String uri) { + RestTemplate rest = getRestTemplate(); + + return rest.getForObject(uri, String.class); + } + + public static <T> T getForRest(String uri, Class<T> clazz) { + RestTemplate rest = getRestTemplate(); + + return rest.getForObject(uri, clazz); + } + + public static String postForRest(String uri, Map<String, Object> map) { + RestTemplate rest = getRestTemplate(); + + return rest.postForObject(uri, map, String.class); + } + + public static <T> String postForRest(String uri, List<T> list) { + RestTemplate rest = getRestTemplate(); + + return rest.postForObject(uri, list, String.class); + } + + public static <T> String postForRest(String uri, T t) { + RestTemplate rest = getRestTemplate(); + + return rest.postForObject(uri, t, String.class); + } + + public static void deleteForRest(String uri) { + RestTemplate rest = getRestTemplate(); + + rest.delete(uri); + } + + public static void deleteForRest(String uri, Map<String, Object> map) { + RestTemplate rest = getRestTemplate(); + + rest.delete(uri, map); + } +} diff --git a/se-modules/se-system/src/main/java/com/se/system/utils/SpringContextUtils.java b/se-modules/se-system/src/main/java/com/se/system/utils/SpringContextUtils.java new file mode 100644 index 0000000..4f43efe --- /dev/null +++ b/se-modules/se-system/src/main/java/com/se/system/utils/SpringContextUtils.java @@ -0,0 +1,41 @@ +package com.se.system.utils; + +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Component; + +@Component +@SuppressWarnings("ALL") +public class SpringContextUtils implements ApplicationContextAware { + private static ApplicationContext context = null; + + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + context = applicationContext; + } + + public static <T> T getBean(String name) { + return (T) context.getBean(name); + } + + public static <T> T getBean(Class<T> clazz) { + return context.getBean(clazz); + } + + public static boolean containsBean(String name) { + return context.containsBean(name); + } + + public static Class<?> getType(String name) { + return context.getType(name); + } + + public static ApplicationContext getContext() { + return context; + } + + public static String getActiveProfile() { + return context.getEnvironment().getActiveProfiles()[0]; + } +} diff --git a/se-modules/se-system/src/main/java/com/se/system/utils/StringUtils.java b/se-modules/se-system/src/main/java/com/se/system/utils/StringUtils.java new file mode 100644 index 0000000..dfe3641 --- /dev/null +++ b/se-modules/se-system/src/main/java/com/se/system/utils/StringUtils.java @@ -0,0 +1,153 @@ +package com.se.system.utils; + +import com.se.system.domain.StaticData; + +import java.sql.Timestamp; +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; + +@SuppressWarnings("ALL") +public class StringUtils { + public static final Pattern NUMBER_PATTERN = Pattern.compile("-?\\d+(\\.\\d+)?"); + + public static final SimpleDateFormat YMD_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); + + public static final SimpleDateFormat YMDHMS_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + public static final SimpleDateFormat YMD2_FORMAT = new SimpleDateFormat("yyyyMMdd"); + + 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])))))?$"); + + 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(); + } + + public static boolean isNull(String str) { + return null == str || str.length() == 0; + } + + public static boolean isEmpty(String str) { + return null == str || "".equals(str.trim()); + } + + public static String getLikeStr(String str) { + return StringUtils.isEmpty(str) ? null : "%" + str.trim() + "%"; + } + + public static String getLikeUpperStr(String str) { + return StringUtils.isEmpty(str) ? null : "%" + str.trim().toUpperCase() + "%"; + } + + public static String getRightLike(String str) { + return StringUtils.isEmpty(str) ? null : str.trim() + "%"; + } + + public static String getGeomWkt(String wkt) { + if (StringUtils.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); + } + + public static boolean isSqlInjection(String str) { + if (null == str) { + return false; + } + + Matcher m = sqlPattern.matcher(str); + + return m.matches(); + } + + public static boolean isPwdInvalid(String pwd) { + return !Pattern.matches(StaticData.PWD_REG, pwd); + } + + public static String getGuid() { + return UUID.randomUUID().toString(); + } + + public static long getMinuteDifference(Timestamp ts) { + return (ts.getTime() - System.currentTimeMillis()) / 1000 / 60; + } + + 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()).append(join); + } + } + + if (sb.length() > 0 && sb.lastIndexOf(join) == sb.length() - join.length()) { + sb.delete(sb.length() - join.length(), sb.length()); + } + + return sb.toString(); + } + + public static List<Integer> strToIntegers(String str) { + if (StringUtils.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/se-modules/se-system/src/main/java/com/se/system/utils/WebUtils.java b/se-modules/se-system/src/main/java/com/se/system/utils/WebUtils.java new file mode 100644 index 0000000..6c74369 --- /dev/null +++ b/se-modules/se-system/src/main/java/com/se/system/utils/WebUtils.java @@ -0,0 +1,304 @@ +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; + } +} -- Gitblit v1.9.3