From 20958386b59b0134b071ee600d89a9659a7e7693 Mon Sep 17 00:00:00 2001 From: xiang Date: Tue, 5 Aug 2025 21:28:09 +0800 Subject: [PATCH] =?UTF-8?q?perf:=E5=B7=A5=E5=85=B7=E7=B1=BB=E6=95=B4?= =?UTF-8?q?=E5=90=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- xservice-common/pom.xml | 2 +- .../xservice/basic/constants/Constants.java | 157 +++++++++++ .../xservice/basic/constants/HttpStatus.java | 94 +++++++ .../xiang/xservice/basic/utils/Base64.java | 253 ++++++++++++++++++ .../xiang/xservice/basic/utils/DateUtils.java | 56 ++-- .../basic/utils/DesensitizedUtil.java | 66 +++++ .../xservice/basic/utils/FileTypeUtils.java | 64 +++++ .../xiang/xservice/basic/utils/HttpUtils.java | 119 ++------ .../xiang/xservice/basic/utils/Md5Utils.java | 55 ++++ .../xservice/basic/utils/MimeTypeUtils.java | 56 ++++ .../xservice/basic/utils/MyStringUtils.java | 60 +++++ 11 files changed, 860 insertions(+), 122 deletions(-) create mode 100644 xservice-common/src/main/java/com/xiang/xservice/basic/constants/Constants.java create mode 100644 xservice-common/src/main/java/com/xiang/xservice/basic/constants/HttpStatus.java create mode 100644 xservice-common/src/main/java/com/xiang/xservice/basic/utils/Base64.java create mode 100644 xservice-common/src/main/java/com/xiang/xservice/basic/utils/DesensitizedUtil.java create mode 100644 xservice-common/src/main/java/com/xiang/xservice/basic/utils/FileTypeUtils.java create mode 100644 xservice-common/src/main/java/com/xiang/xservice/basic/utils/Md5Utils.java create mode 100644 xservice-common/src/main/java/com/xiang/xservice/basic/utils/MimeTypeUtils.java create mode 100644 xservice-common/src/main/java/com/xiang/xservice/basic/utils/MyStringUtils.java diff --git a/xservice-common/pom.xml b/xservice-common/pom.xml index e969ce0..ac79559 100644 --- a/xservice-common/pom.xml +++ b/xservice-common/pom.xml @@ -8,7 +8,7 @@ xservice-basic 1.1 - 1.1 + 1.1-SNAPSHOT xservice-common diff --git a/xservice-common/src/main/java/com/xiang/xservice/basic/constants/Constants.java b/xservice-common/src/main/java/com/xiang/xservice/basic/constants/Constants.java new file mode 100644 index 0000000..ec67d91 --- /dev/null +++ b/xservice-common/src/main/java/com/xiang/xservice/basic/constants/Constants.java @@ -0,0 +1,157 @@ +package com.xiang.xservice.basic.constants; + +import java.util.Locale; + +/** + * 通用常量信息 + * + * @author xiang + */ +public class Constants +{ + /** + * UTF-8 字符集 + */ + public static final String UTF8 = "UTF-8"; + + /** + * GBK 字符集 + */ + public static final String GBK = "GBK"; + + /** + * 系统语言 + */ + public static final Locale DEFAULT_LOCALE = Locale.SIMPLIFIED_CHINESE; + + /** + * www主域 + */ + public static final String WWW = "www."; + + /** + * http请求 + */ + public static final String HTTP = "http://"; + + /** + * https请求 + */ + public static final String HTTPS = "https://"; + + /** + * 通用成功标识 + */ + public static final String SUCCESS = "0"; + + /** + * 通用失败标识 + */ + public static final String FAIL = "1"; + + /** + * 登录成功 + */ + public static final String LOGIN_SUCCESS = "Success"; + + /** + * 注销 + */ + public static final String LOGOUT = "Logout"; + + /** + * 注册 + */ + public static final String REGISTER = "Register"; + + /** + * 登录失败 + */ + public static final String LOGIN_FAIL = "Error"; + + /** + * 所有权限标识 + */ + public static final String ALL_PERMISSION = "*:*:*"; + + /** + * 管理员角色权限标识 + */ + public static final String SUPER_ADMIN = "admin"; + + /** + * 角色权限分隔符 + */ + public static final String ROLE_DELIMETER = ","; + + /** + * 权限标识分隔符 + */ + public static final String PERMISSION_DELIMETER = ","; + + /** + * 验证码有效期(分钟) + */ + public static final Integer CAPTCHA_EXPIRATION = 2; + + /** + * 令牌 + */ + public static final String TOKEN = "token"; + + /** + * 令牌前缀 + */ + public static final String TOKEN_PREFIX = "Bearer "; + + /** + * 令牌前缀 + */ + public static final String LOGIN_USER_KEY = "login_user_key"; + + /** + * 用户ID + */ + public static final String JWT_USERID = "userid"; + + /** + * 用户头像 + */ + public static final String JWT_AVATAR = "avatar"; + + /** + * 创建时间 + */ + public static final String JWT_CREATED = "created"; + + /** + * 用户权限 + */ + public static final String JWT_AUTHORITIES = "authorities"; + + /** + * 资源映射路径 前缀 + */ + public static final String RESOURCE_PREFIX = "/profile"; + + /** + * RMI 远程方法调用 + */ + public static final String LOOKUP_RMI = "rmi:"; + + /** + * LDAP 远程方法调用 + */ + public static final String LOOKUP_LDAP = "ldap:"; + + /** + * LDAPS 远程方法调用 + */ + public static final String LOOKUP_LDAPS = "ldaps:"; + + /** + * 定时任务违规的字符 + */ + public static final String[] JOB_ERROR_STR = { "java.net.URL", "javax.naming.InitialContext", "org.yaml.snakeyaml", + "org.springframework", "org.apache", "com.ruoyi.common.utils.file", "com.ruoyi.common.config", "com.ruoyi.generator" }; +} diff --git a/xservice-common/src/main/java/com/xiang/xservice/basic/constants/HttpStatus.java b/xservice-common/src/main/java/com/xiang/xservice/basic/constants/HttpStatus.java new file mode 100644 index 0000000..69ccdce --- /dev/null +++ b/xservice-common/src/main/java/com/xiang/xservice/basic/constants/HttpStatus.java @@ -0,0 +1,94 @@ +package com.xiang.xservice.basic.constants; + +/** + * 返回状态码 + * + * @author xiang + */ +public class HttpStatus +{ + /** + * 操作成功 + */ + public static final int SUCCESS = 200; + + /** + * 对象创建成功 + */ + public static final int CREATED = 201; + + /** + * 请求已经被接受 + */ + public static final int ACCEPTED = 202; + + /** + * 操作已经执行成功,但是没有返回数据 + */ + public static final int NO_CONTENT = 204; + + /** + * 资源已被移除 + */ + public static final int MOVED_PERM = 301; + + /** + * 重定向 + */ + public static final int SEE_OTHER = 303; + + /** + * 资源没有被修改 + */ + public static final int NOT_MODIFIED = 304; + + /** + * 参数列表错误(缺少,格式不匹配) + */ + public static final int BAD_REQUEST = 400; + + /** + * 未授权 + */ + public static final int UNAUTHORIZED = 401; + + /** + * 访问受限,授权过期 + */ + public static final int FORBIDDEN = 403; + + /** + * 资源,服务未找到 + */ + public static final int NOT_FOUND = 404; + + /** + * 不允许的http方法 + */ + public static final int BAD_METHOD = 405; + + /** + * 资源冲突,或者资源被锁 + */ + public static final int CONFLICT = 409; + + /** + * 不支持的数据,媒体类型 + */ + public static final int UNSUPPORTED_TYPE = 415; + + /** + * 系统内部错误 + */ + public static final int ERROR = 500; + + /** + * 接口未实现 + */ + public static final int NOT_IMPLEMENTED = 501; + + /** + * 系统警告消息 + */ + public static final int WARN = 601; +} diff --git a/xservice-common/src/main/java/com/xiang/xservice/basic/utils/Base64.java b/xservice-common/src/main/java/com/xiang/xservice/basic/utils/Base64.java new file mode 100644 index 0000000..f125403 --- /dev/null +++ b/xservice-common/src/main/java/com/xiang/xservice/basic/utils/Base64.java @@ -0,0 +1,253 @@ +package com.xiang.xservice.basic.utils; + +/** + * Base64工具类 + * + * @author xiang + */ +public final class Base64 { + static private final int BASELENGTH = 128; + static private final int LOOKUPLENGTH = 64; + static private final int TWENTYFOURBITGROUP = 24; + static private final int EIGHTBIT = 8; + static private final int SIXTEENBIT = 16; + static private final int FOURBYTE = 4; + static private final int SIGN = -128; + static private final char PAD = '='; + static final private byte[] base64Alphabet = new byte[BASELENGTH]; + static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH]; + + static { + for (int i = 0; i < BASELENGTH; ++i) { + base64Alphabet[i] = -1; + } + for (int i = 'Z'; i >= 'A'; i--) { + base64Alphabet[i] = (byte) (i - 'A'); + } + for (int i = 'z'; i >= 'a'; i--) { + base64Alphabet[i] = (byte) (i - 'a' + 26); + } + + for (int i = '9'; i >= '0'; i--) { + base64Alphabet[i] = (byte) (i - '0' + 52); + } + + base64Alphabet['+'] = 62; + base64Alphabet['/'] = 63; + + for (int i = 0; i <= 25; i++) { + lookUpBase64Alphabet[i] = (char) ('A' + i); + } + + for (int i = 26, j = 0; i <= 51; i++, j++) { + lookUpBase64Alphabet[i] = (char) ('a' + j); + } + + for (int i = 52, j = 0; i <= 61; i++, j++) { + lookUpBase64Alphabet[i] = (char) ('0' + j); + } + lookUpBase64Alphabet[62] = '+'; + lookUpBase64Alphabet[63] = '/'; + } + + private static boolean isWhiteSpace(char octect) { + return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9); + } + + private static boolean isPad(char octect) { + return (octect == PAD); + } + + private static boolean isData(char octect) { + return (octect < BASELENGTH && base64Alphabet[octect] != -1); + } + + /** + * Encodes hex octects into Base64 + * + * @param binaryData Array containing binaryData + * @return Encoded Base64 array + */ + public static String encode(byte[] binaryData) { + if (binaryData == null) { + return null; + } + + int lengthDataBits = binaryData.length * EIGHTBIT; + if (lengthDataBits == 0) { + return ""; + } + + int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; + int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; + int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets; + char[] encodedData = null; + + encodedData = new char[numberQuartet * 4]; + + byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; + + int encodedIndex = 0; + int dataIndex = 0; + + for (int i = 0; i < numberTriplets; i++) { + b1 = binaryData[dataIndex++]; + b2 = binaryData[dataIndex++]; + b3 = binaryData[dataIndex++]; + + l = (byte) (b2 & 0x0f); + k = (byte) (b1 & 0x03); + + byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); + byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); + byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc); + + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f]; + } + + // form integral number of 6-bit groups + if (fewerThan24bits == EIGHTBIT) { + b1 = binaryData[dataIndex]; + k = (byte) (b1 & 0x03); + byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4]; + encodedData[encodedIndex++] = PAD; + encodedData[encodedIndex++] = PAD; + } else if (fewerThan24bits == SIXTEENBIT) { + b1 = binaryData[dataIndex]; + b2 = binaryData[dataIndex + 1]; + l = (byte) (b2 & 0x0f); + k = (byte) (b1 & 0x03); + + byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); + byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); + + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2]; + encodedData[encodedIndex++] = PAD; + } + return new String(encodedData); + } + + /** + * Decodes Base64 data into octects + * + * @param encoded string containing Base64 data + * @return Array containind decoded data. + */ + public static byte[] decode(String encoded) { + if (encoded == null) { + return null; + } + + char[] base64Data = encoded.toCharArray(); + // remove white spaces + int len = removeWhiteSpace(base64Data); + + if (len % FOURBYTE != 0) { + return null;// should be divisible by four + } + + int numberQuadruple = (len / FOURBYTE); + + if (numberQuadruple == 0) { + return new byte[0]; + } + + byte[] decodedData = null; + byte b1 = 0, b2 = 0, b3 = 0, b4 = 0; + char d1 = 0, d2 = 0, d3 = 0, d4 = 0; + + int i = 0; + int encodedIndex = 0; + int dataIndex = 0; + decodedData = new byte[(numberQuadruple) * 3]; + + for (; i < numberQuadruple - 1; i++) { + + if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++])) + || !isData((d3 = base64Data[dataIndex++])) || !isData((d4 = base64Data[dataIndex++]))) { + return null; + } // if found "no data" just return null + + b1 = base64Alphabet[d1]; + b2 = base64Alphabet[d2]; + b3 = base64Alphabet[d3]; + b4 = base64Alphabet[d4]; + + decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4); + decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); + decodedData[encodedIndex++] = (byte) (b3 << 6 | b4); + } + + if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) { + return null;// if found "no data" just return null + } + + b1 = base64Alphabet[d1]; + b2 = base64Alphabet[d2]; + + d3 = base64Data[dataIndex++]; + d4 = base64Data[dataIndex++]; + if (!isData((d3)) || !isData((d4))) {// Check if they are PAD characters + if (isPad(d3) && isPad(d4)) { + if ((b2 & 0xf) != 0)// last 4 bits should be zero + { + return null; + } + byte[] tmp = new byte[i * 3 + 1]; + System.arraycopy(decodedData, 0, tmp, 0, i * 3); + tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); + return tmp; + } else if (!isPad(d3) && isPad(d4)) { + b3 = base64Alphabet[d3]; + if ((b3 & 0x3) != 0)// last 2 bits should be zero + { + return null; + } + byte[] tmp = new byte[i * 3 + 2]; + System.arraycopy(decodedData, 0, tmp, 0, i * 3); + tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4); + tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); + return tmp; + } else { + return null; + } + } else { // No PAD e.g 3cQl + b3 = base64Alphabet[d3]; + b4 = base64Alphabet[d4]; + decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4); + decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); + decodedData[encodedIndex++] = (byte) (b3 << 6 | b4); + + } + return decodedData; + } + + /** + * remove WhiteSpace from MIME containing encoded Base64 data. + * + * @param data the byte array of base64 data (with WS) + * @return the new length + */ + private static int removeWhiteSpace(char[] data) { + if (data == null) { + return 0; + } + + // count characters that's not whitespace + int newSize = 0; + int len = data.length; + for (int i = 0; i < len; i++) { + if (!isWhiteSpace(data[i])) { + data[newSize++] = data[i]; + } + } + return newSize; + } +} diff --git a/xservice-common/src/main/java/com/xiang/xservice/basic/utils/DateUtils.java b/xservice-common/src/main/java/com/xiang/xservice/basic/utils/DateUtils.java index b6acd6f..2b6d907 100644 --- a/xservice-common/src/main/java/com/xiang/xservice/basic/utils/DateUtils.java +++ b/xservice-common/src/main/java/com/xiang/xservice/basic/utils/DateUtils.java @@ -10,6 +10,43 @@ import java.time.format.DateTimeFormatter; */ public class DateUtils { + private final static String defaultDateFormatter = "yyyy-MM-dd"; + private final static String defaultDateTimeFormatter = "yyyy-MM-dd HH:mm:ss"; + + public static LocalDateTime getDateTimeFromStr(String dateStr) { + return getDateTimeFromStr(dateStr, defaultDateTimeFormatter); + } + + public static LocalDateTime getDateTimeFromStr(String dateStr, String pattern) { + return LocalDateTime.parse(dateStr, DateTimeFormatter.ofPattern(pattern)); + } + + public static LocalDate getDateFromStr(String dataStr) { + return getDateFromStr(dataStr, defaultDateFormatter); + } + + public static LocalDate getDateFromStr(String dataStr, String pattern) { + return LocalDate.parse(dataStr, DateTimeFormatter.ofPattern(pattern)); + } + + public static String getDateFromDate(LocalDate date) { + return getDateFromDate(date, defaultDateFormatter); + } + + public static String getDateFromDate(LocalDate date, String pattern) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); + return date.format(formatter); + } + + public static String getDateTimeFromDateTime(LocalDateTime dateTime) { + return getDateTimeFromDateTime(dateTime, defaultDateTimeFormatter); + } + + public static String getDateTimeFromDateTime(LocalDateTime dateTime, String pattern) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); + return dateTime.format(formatter); + } + /** * 字符串(yyyy-MM-dd HH:mm:ss)转换为时间 * @param date 字符串日期 @@ -21,23 +58,4 @@ public class DateUtils { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); return LocalDateTime.parse(dateTimeStr, formatter); } - public static LocalDateTime getTimeFromStr(String str) { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - return LocalDateTime.parse(str, formatter); - } - - public static LocalDate getDateFromStr(String date) { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd"); - return LocalDate.parse(date, formatter); - } - - public static LocalDateTime getDateTimeFromStr(String dateTime) { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); - return LocalDateTime.parse(dateTime, formatter); - } - - public static String getDateTimeStr(LocalDateTime dateTime) { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - return dateTime.format(formatter); - } } diff --git a/xservice-common/src/main/java/com/xiang/xservice/basic/utils/DesensitizedUtil.java b/xservice-common/src/main/java/com/xiang/xservice/basic/utils/DesensitizedUtil.java new file mode 100644 index 0000000..6d0184e --- /dev/null +++ b/xservice-common/src/main/java/com/xiang/xservice/basic/utils/DesensitizedUtil.java @@ -0,0 +1,66 @@ +package com.xiang.xservice.basic.utils; + +import org.apache.commons.lang3.StringUtils; + +import java.util.Objects; + +/** + * 脱敏工具类 + * + * @author xiang + */ +public class DesensitizedUtil { + /** + * 密码的全部字符都用*代替,比如:****** + * + * @param password 密码 + * @return 脱敏后的密码 + */ + public static String password(String password) { + if (StringUtils.isBlank(password)) { + return StringUtils.EMPTY; + } + return StringUtils.repeat('*', password.length()); + } + + /** + * 车牌中间用*代替,如果是错误的车牌,不处理 + * + * @param carLicense 完整的车牌号 + * @return 脱敏后的车牌 + */ + public static String carLicense(String carLicense) { + if (StringUtils.isBlank(carLicense)) { + return StringUtils.EMPTY; + } + // 普通车牌 + if (carLicense.length() == 7) { + carLicense = MyStringUtils.hide(carLicense, 3, 6); + } else if (carLicense.length() == 8) { + // 新能源车牌 + carLicense = MyStringUtils.hide(carLicense, 3, 7); + } + return carLicense; + } + + /** + * 身份证中间用*号代替 身份证号必须先通过工具类校验(15位或者18位) + * + * @param cardNo 身份证号码 + * @return 脱敏后的身份证号码 + */ + public static String cardNoLicense(String cardNo) { + if (StringUtils.isBlank(cardNo)) { + return StringUtils.EMPTY; + } + // 第一代身份证号码 + if (Objects.equals(15, cardNo.length())) { + cardNo = MyStringUtils.hide(cardNo, 3, 13); + } + // 第二代身份证号码 + if (Objects.equals(18, cardNo.length())) { + cardNo = MyStringUtils.hide(cardNo, 3, 15); + } + return cardNo; + } +} diff --git a/xservice-common/src/main/java/com/xiang/xservice/basic/utils/FileTypeUtils.java b/xservice-common/src/main/java/com/xiang/xservice/basic/utils/FileTypeUtils.java new file mode 100644 index 0000000..6f9af10 --- /dev/null +++ b/xservice-common/src/main/java/com/xiang/xservice/basic/utils/FileTypeUtils.java @@ -0,0 +1,64 @@ +package com.xiang.xservice.basic.utils; + +import org.apache.commons.lang3.StringUtils; + +import java.io.File; + +/** + * 文件类型工具类 + * + * @author xiang + */ +public class FileTypeUtils { + /** + * 获取文件类型 + *

+ * 例如: ruoyi.txt, 返回: txt + * + * @param file 文件名 + * @return 后缀(不含".") + */ + public static String getFileType(File file) { + if (null == file) { + return StringUtils.EMPTY; + } + return getFileType(file.getName()); + } + + /** + * 获取文件类型 + *

+ * 例如: ruoyi.txt, 返回: txt + * + * @param fileName 文件名 + * @return 后缀(不含".") + */ + public static String getFileType(String fileName) { + int separatorIndex = fileName.lastIndexOf("."); + if (separatorIndex < 0) { + return ""; + } + return fileName.substring(separatorIndex + 1).toLowerCase(); + } + + /** + * 获取文件类型 + * + * @param photoByte 文件字节码 + * @return 后缀(不含".") + */ + public static String getFileExtendName(byte[] photoByte) { + String strFileExtendName = "JPG"; + if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56) + && ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97)) { + strFileExtendName = "GIF"; + } else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70)) { + strFileExtendName = "JPG"; + } else if ((photoByte[0] == 66) && (photoByte[1] == 77)) { + strFileExtendName = "BMP"; + } else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71)) { + strFileExtendName = "PNG"; + } + return strFileExtendName; + } +} \ No newline at end of file diff --git a/xservice-common/src/main/java/com/xiang/xservice/basic/utils/HttpUtils.java b/xservice-common/src/main/java/com/xiang/xservice/basic/utils/HttpUtils.java index 947d6cd..85c75dc 100644 --- a/xservice-common/src/main/java/com/xiang/xservice/basic/utils/HttpUtils.java +++ b/xservice-common/src/main/java/com/xiang/xservice/basic/utils/HttpUtils.java @@ -1,7 +1,5 @@ package com.xiang.xservice.basic.utils; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.MapUtils; import org.apache.http.client.config.RequestConfig; @@ -58,40 +56,27 @@ public class HttpUtils { .build(); } - public static String doPostV1(String url, Map header, String jsonParams) { - RequestConfig requestConfig = RequestConfig.custom() - // 设置连接超时时间 - .setConnectTimeout(connectTimeout) - // 设置Socket超时时间 - .setSocketTimeout(socketTimeOut) - .setConnectionRequestTimeout(connectionRequestTimeout) - .build(); - //创建httpClient对象 - CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build(); - CloseableHttpResponse response = null; - String result = ""; - try { - // 创建http请求 - HttpPost httpPost = getPost(url, header, jsonParams); - response = httpClient.execute(httpPost); - result = EntityUtils.toString(response.getEntity(), "utf-8"); - } catch (Exception e) { - log.error("doPost异常", e); - } finally { - //关闭资源 - closeResource(response, httpClient); - } - return result; - } - public static String doPost(String url, Map header, String jsonParams) { CloseableHttpResponse response = null; String result = ""; try { - log.info("HTTP请求,请求参数===>{}", jsonParams); - HttpPost httpPost = getPost(url, header, jsonParams); + log.info("HTTP请求,请求地址===>{}, 请求参数===>{}", url, jsonParams); + HttpPost httpPost = new HttpPost(url); + httpPost.addHeader("Content-Type", "application/json"); + // 创建请求内容 + StringEntity entity = new StringEntity(jsonParams, "utf-8"); + entity.setContentType("application/json"); + httpPost.setEntity(entity); + // 设置请求头 + if (null != header && !header.isEmpty()) { + Set> entries = header.entrySet(); + for (Map.Entry e : entries) { + httpPost.setHeader(e.getKey(), e.getValue()); + } + } response = httpClient.execute(httpPost); result = EntityUtils.toString(response.getEntity(), "utf-8"); + log.info("【POST请求】 请求地址===>{}, 响应结果==={}", url, result); } catch (Exception e) { log.error("doPost异常", e); } finally { @@ -101,19 +86,6 @@ public class HttpUtils { return result; } - public static String doPostWithRetry(String url, Map header, String jsonParams, Integer successCode, int retryCounts) { - int i = 0; - while (i++ < retryCounts) { - String respStr = doPost(url, header, jsonParams); - JSONObject resp = JSON.parseObject(respStr); - Integer code = (Integer) resp.get("code"); - if (successCode.equals(code)) { - return respStr; - } - } - return null; - } - public static String doGet(String url, Map header, Map param) { CloseableHttpResponse response = null; String result = ""; @@ -135,9 +107,10 @@ public class HttpUtils { httpGet.setHeader(entry.getKey(), entry.getValue()); } } - log.info("doGet请求:请求地址:{}", url + request); + log.info("doGet请求:请求头:{},请求地址:{}", header, url + request); response = httpClient.execute(httpGet); result = EntityUtils.toString(response.getEntity(), "utf-8"); + log.info("【GET请求】, 请求地址===>{}, 响应结果===>{}", url + request, result); } catch (Exception e) { log.error("doGet异常:", e); } finally { @@ -146,64 +119,6 @@ public class HttpUtils { return result; } - - - private static HttpPost getPost(String url, Map header, String jsonParams) { - HttpPost httpPost = new HttpPost(url); - httpPost.addHeader("Content-Type", "application/json"); - httpPost.setHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.61(0x18003d2e) NetType/WIFI Language/zh_CN"); - // 创建请求内容 - StringEntity entity = new StringEntity(jsonParams, "utf-8"); - entity.setContentType("application/json"); - httpPost.setEntity(entity); - // 设置请求头 - if (null != header && !header.isEmpty()) { - Set> entries = header.entrySet(); - for (Map.Entry e : entries) { - httpPost.setHeader(e.getKey(), e.getValue()); - } - } - return httpPost; - } - - public static String doGetV1(String url, Map header, Map param) { - RequestConfig requestConfig = RequestConfig.custom() - // 设置连接超时时间 - .setConnectTimeout(connectTimeout) - // 设置Socket超时时间 - .setSocketTimeout(socketTimeOut) - .setConnectionRequestTimeout(connectionRequestTimeout) - .build(); - CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build(); - CloseableHttpResponse response; - String result = ""; - try { - String request = ""; - if (MapUtils.isNotEmpty(param)) { - StringBuilder req = new StringBuilder("?"); - for (Map.Entry entry : param.entrySet()) { - req.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); - } - request = req.substring(0, req.length() - 1); - } - - HttpGet httpGet = new HttpGet(url + request); - httpGet.addHeader("Content-Type", "application/json"); - httpGet.setHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.61(0x18003d2e) NetType/WIFI Language/zh_CN"); - if (MapUtils.isNotEmpty(header)) { - for (Map.Entry entry : header.entrySet()) { - httpGet.setHeader(entry.getKey(), entry.getValue()); - } - } - log.info("doGet请求:请求地址:{}", url + request); - response = httpClient.execute(httpGet); - result = EntityUtils.toString(response.getEntity(), "utf-8"); - } catch (Exception e) { - log.error("doGet异常:", e); - } - return result; - } - /** * @Description 关闭资源 */ diff --git a/xservice-common/src/main/java/com/xiang/xservice/basic/utils/Md5Utils.java b/xservice-common/src/main/java/com/xiang/xservice/basic/utils/Md5Utils.java new file mode 100644 index 0000000..06ad955 --- /dev/null +++ b/xservice-common/src/main/java/com/xiang/xservice/basic/utils/Md5Utils.java @@ -0,0 +1,55 @@ +package com.xiang.xservice.basic.utils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; + +/** + * Md5加密方法 + * + * @author xiang + */ +public class Md5Utils { + private static final Logger log = LoggerFactory.getLogger(Md5Utils.class); + + private static byte[] md5(String s) { + MessageDigest algorithm; + try { + algorithm = MessageDigest.getInstance("MD5"); + algorithm.reset(); + algorithm.update(s.getBytes(StandardCharsets.UTF_8)); + byte[] messageDigest = algorithm.digest(); + return messageDigest; + } catch (Exception e) { + log.error("MD5 Error...", e); + } + return null; + } + + private static String toHex(byte[] hash) { + if (hash == null) { + return null; + } + StringBuffer buf = new StringBuffer(hash.length * 2); + int i; + + for (i = 0; i < hash.length; i++) { + if ((hash[i] & 0xff) < 0x10) { + buf.append("0"); + } + buf.append(Long.toString(hash[i] & 0xff, 16)); + } + return buf.toString(); + } + + public static String hash(String s) { + try { + return new String(toHex(md5(s)).getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8); + } catch (Exception e) { + log.error("not supported charset...{}", e); + return s; + } + } +} diff --git a/xservice-common/src/main/java/com/xiang/xservice/basic/utils/MimeTypeUtils.java b/xservice-common/src/main/java/com/xiang/xservice/basic/utils/MimeTypeUtils.java new file mode 100644 index 0000000..635fce9 --- /dev/null +++ b/xservice-common/src/main/java/com/xiang/xservice/basic/utils/MimeTypeUtils.java @@ -0,0 +1,56 @@ +package com.xiang.xservice.basic.utils; + +/** + * 媒体类型工具类 + * + * @author xiang + */ +public class MimeTypeUtils { + public static final String IMAGE_PNG = "image/png"; + + public static final String IMAGE_JPG = "image/jpg"; + + public static final String IMAGE_JPEG = "image/jpeg"; + + public static final String IMAGE_BMP = "image/bmp"; + + public static final String IMAGE_GIF = "image/gif"; + + public static final String[] IMAGE_EXTENSION = {"bmp", "gif", "jpg", "jpeg", "png"}; + + public static final String[] FLASH_EXTENSION = {"swf", "flv"}; + + public static final String[] MEDIA_EXTENSION = {"swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg", + "asf", "rm", "rmvb"}; + + public static final String[] VIDEO_EXTENSION = {"mp4", "avi", "rmvb"}; + + public static final String[] DEFAULT_ALLOWED_EXTENSION = { + // 图片 + "bmp", "gif", "jpg", "jpeg", "png", + // word excel powerpoint + "doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt", + // 压缩文件 + "rar", "zip", "gz", "bz2", + // 视频格式 + "mp4", "avi", "rmvb", + // pdf + "pdf"}; + + public static String getExtension(String prefix) { + switch (prefix) { + case IMAGE_PNG: + return "png"; + case IMAGE_JPG: + return "jpg"; + case IMAGE_JPEG: + return "jpeg"; + case IMAGE_BMP: + return "bmp"; + case IMAGE_GIF: + return "gif"; + default: + return ""; + } + } +} diff --git a/xservice-common/src/main/java/com/xiang/xservice/basic/utils/MyStringUtils.java b/xservice-common/src/main/java/com/xiang/xservice/basic/utils/MyStringUtils.java new file mode 100644 index 0000000..a764eab --- /dev/null +++ b/xservice-common/src/main/java/com/xiang/xservice/basic/utils/MyStringUtils.java @@ -0,0 +1,60 @@ +package com.xiang.xservice.basic.utils; + +import org.apache.commons.lang3.StringUtils; + +/** + * 字符串工具类 + * + * @author Xiang + */ +public class MyStringUtils extends StringUtils { + + /** + * 空字符串 + */ + public final static String EMPTY_STRING = ""; + + /** + * 下划线 + */ + private static final char SEPARATOR = '_'; + + /** + * 星号 + */ + private static final char ASTERISK = '*'; + + /** + * 替换指定字符串的指定区间内字符为"*" + * + * @param str 字符串 + * @param startInclude 开始位置(包含) + * @param endExclude 结束位置(不包含) + * @return 替换后的字符串 + */ + public static String hide(CharSequence str, int startInclude, int endExclude) { + if (isEmpty(str)) { + return EMPTY_STRING; + } + final int strLength = str.length(); + if (startInclude > strLength) { + return EMPTY_STRING; + } + if (endExclude > strLength) { + endExclude = strLength; + } + if (startInclude > endExclude) { + // 如果起始位置大于结束位置,不替换 + return EMPTY_STRING; + } + final char[] chars = new char[strLength]; + for (int i = 0; i < strLength; i++) { + if (i >= startInclude && i < endExclude) { + chars[i] = ASTERISK; + } else { + chars[i] = str.charAt(i); + } + } + return new String(chars); + } +}