From a2a247bbff8271e5d2bd6b423faec5cdbd77c463 Mon Sep 17 00:00:00 2001 From: yexuejc <940526mf> Date: Mon, 3 Sep 2018 19:27:23 +0800 Subject: [PATCH 01/27] 1.1.7 --- UPDATE.md | 9 + pom.xml | 13 +- .../java/com/yexuejc/base/encrypt/RSA.java | 1 - .../com/yexuejc/base/encrypt/RSACoder.java | 200 +++++++++ .../com/yexuejc/base/util/AlgorithmUtils.java | 45 ++ .../java/com/yexuejc/base/util/DateUtil.java | 10 +- .../java/com/yexuejc/base/util/ImgUtil.java | 419 ++++++++++++++++++ .../java/com/yexuejc/base/util/JsonUtil.java | 8 + .../java/com/yexuejc/base/util/JwtUtil.java | 66 ++- .../yexuejc/base/util/MapRemoveNullUtil.java | 8 + .../com/yexuejc/base/util/MoneyUtils.java | 2 +- .../java/com/yexuejc/base/util/ThreeDES.java | 101 +++++ 12 files changed, 869 insertions(+), 13 deletions(-) create mode 100644 src/main/java/com/yexuejc/base/encrypt/RSACoder.java create mode 100644 src/main/java/com/yexuejc/base/util/ImgUtil.java create mode 100644 src/main/java/com/yexuejc/base/util/ThreeDES.java diff --git a/UPDATE.md b/UPDATE.md index 86a6207..5489860 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -1,6 +1,15 @@ yexuejc-base 更新记录 ------------------ +#### version :1.1.8 +**time:2018-8-17 11:22:50**
+**branch:** master
+**update:**
+>1. 增肌图片处理工具类 +>2. 增肌3des工具类 +>3. 增肌RSA工具类 +>4. 优化其他工具类 +# #### version :1.1.7 **time:2018-8-17 11:22:50**
**branch:** master
diff --git a/pom.xml b/pom.xml index 1dbd45f..30f0df3 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.yexuejc.base yexuejc-base - 1.1.7 + 1.1.8 ${project.artifactId} @@ -20,6 +20,7 @@ 1.1.0.Final 1.10 2.6 + 1.60 @@ -48,6 +49,12 @@ commons-io ${commons-io.version} + + + org.bouncycastle + bcprov-jdk15on + ${bcprov-jdk15on.version} + @@ -59,8 +66,8 @@ maven-compiler-plugin UTF-8 - ${java.version} - ${java.version} + 8 + 8 diff --git a/src/main/java/com/yexuejc/base/encrypt/RSA.java b/src/main/java/com/yexuejc/base/encrypt/RSA.java index 15ee943..bbd5363 100644 --- a/src/main/java/com/yexuejc/base/encrypt/RSA.java +++ b/src/main/java/com/yexuejc/base/encrypt/RSA.java @@ -107,7 +107,6 @@ public class RSA { * @param privateKey * @return */ - public static String privateDecrypt(String data, RSAPrivateKey privateKey) { try { Cipher cipher = Cipher.getInstance(RSA_ALGORITHM); diff --git a/src/main/java/com/yexuejc/base/encrypt/RSACoder.java b/src/main/java/com/yexuejc/base/encrypt/RSACoder.java new file mode 100644 index 0000000..f77f013 --- /dev/null +++ b/src/main/java/com/yexuejc/base/encrypt/RSACoder.java @@ -0,0 +1,200 @@ +package com.yexuejc.base.encrypt; + +import org.apache.commons.codec.binary.Base64; + +import javax.crypto.Cipher; +import java.security.Key; +import java.security.KeyFactory; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; + +/** + * RSA 加解密 工具模式 + * + * @author maxf + * @ClassName RSACoder + * @Description + * @date 2018/9/3 16:13 + */ +public class RSACoder { + + public static final String KEY_ALGORITHM = "RSA"; + + /** + * 解密
+ * 用公钥解密 + * + * @param data + * @param key + * @return + * @throws Exception + */ + public static byte[] decryptByPublic(String data, String key) + throws Exception { + return getDataByPublicKey(data, key, Cipher.DECRYPT_MODE); + } + + /** + * 解密
+ * 用私钥解密 + * + * @param data + * @param key + * @return + * @throws Exception + */ + public static byte[] decryptByPrivateKey(String data, String key) + throws Exception { + return getDataByPrivateKey(data, key, Cipher.DECRYPT_MODE); + } + + /** + * 加密
+ * 用公钥加密 + * + * @param data + * @param key + * @return + * @throws Exception + */ + public static byte[] encryptByPublicKey(String data, String key) + throws Exception { + return getDataByPublicKey(data, key, Cipher.ENCRYPT_MODE); + } + + /** + * 加密
+ * 用私钥加密 + * + * @param data + * @param key + * @return + * @throws Exception + */ + public static byte[] encryptByPrivateKey(String data, String key) + throws Exception { + return getDataByPrivateKey(data, key, Cipher.ENCRYPT_MODE); + } + + /** + * 解密
+ * 用公钥解密 + * + * @param data + * @param key + * @return + * @throws Exception + */ + public static byte[] decryptByPublic(byte[] data, String key) + throws Exception { + return getDataByPublicKey(data, key, Cipher.DECRYPT_MODE); + } + + /** + * 解密
+ * 用私钥解密 + * + * @param data + * @param key + * @return + * @throws Exception + */ + public static byte[] decryptByPrivateKey(byte[] data, String key) + throws Exception { + return getDataByPrivateKey(data, key, Cipher.DECRYPT_MODE); + } + + /** + * 加密
+ * 用公钥加密 + * + * @param data + * @param key + * @return + * @throws Exception + */ + public static byte[] encryptByPublicKey(byte[] data, String key) + throws Exception { + return getDataByPublicKey(data, key, Cipher.ENCRYPT_MODE); + } + + /** + * 加密
+ * 用私钥加密 + * + * @param data + * @param key + * @return + * @throws Exception + */ + public static byte[] encryptByPrivateKey(byte[] data, String key) + throws Exception { + return getDataByPrivateKey(data, key, Cipher.ENCRYPT_MODE); + } + + /** + * 通过公钥获得加解密数据 + * + * @param data String + * @param key String + * @param mode int + * @return + */ + public static byte[] getDataByPublicKey(String data, String key, int mode) + throws Exception { + return getDataByPublicKey(data.getBytes(), key, mode); + } + + /** + * 通过私钥获得加解密数据 + * + * @param data String + * @param key String + * @param mode 加密或解密 + * @return + */ + public static byte[] getDataByPrivateKey(String data, String key, int mode) + throws Exception { + return getDataByPrivateKey(data.getBytes(), key, mode); + } + + /** + * 通过公钥获得加解密数据 + * + * @param data String + * @param key String + * @param mode int + * @return + */ + public static byte[] getDataByPublicKey(byte[] data, String key, int mode) + throws Exception { + // 取得私钥 + X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(key.getBytes("UTF-8"))); + KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); + Key privateKey = keyFactory.generatePublic(x509KeySpec); + // 对数据进行加密或解密 + Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); + cipher.init(mode, privateKey); + return cipher.doFinal(data); + } + + /** + * 通过私钥获得加解密数据 + * + * @param data String + * @param key String + * @param mode 加密或解密 + * @return + */ + public static byte[] getDataByPrivateKey(byte[] data, String key, int mode) + throws Exception { + // 取得私钥 + PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(key.getBytes("UTF-8"))); + KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); + Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec); + // 对数据解密 + Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); + cipher.init(mode, privateKey); + return cipher.doFinal(data); + } +} diff --git a/src/main/java/com/yexuejc/base/util/AlgorithmUtils.java b/src/main/java/com/yexuejc/base/util/AlgorithmUtils.java index 9daf60a..8917516 100644 --- a/src/main/java/com/yexuejc/base/util/AlgorithmUtils.java +++ b/src/main/java/com/yexuejc/base/util/AlgorithmUtils.java @@ -1,6 +1,8 @@ package com.yexuejc.base.util; +import sun.misc.BASE64Decoder; + /** * 算法工具类 * @@ -107,4 +109,47 @@ public class AlgorithmUtils { static class NextCodeException extends Exception { private static final long serialVersionUID = 8956943499144648985L; } + + /** + * 16进制转为2进制 + * + * @param hexString 16进制字符串 + */ + public static String x16ConvertTo2(String hexString) { + if (hexString == null || hexString.length() % 2 != 0) { + return null; + } + String bString = "", tmp; + for (int i = 0; i < hexString.length(); i++) { + tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16)); + bString += tmp.substring(tmp.length() - 4); + } + return bString; + } + + /** + * 16进制转为2进制byte[] + * + * @param hexString 16进制字符串 + * @return + */ + public static byte[] hexStringToBytes(String hexString) { + if (hexString == null || hexString.equals("")) { + return null; + } + hexString = hexString.toUpperCase(); + int length = hexString.length() / 2; + char[] hexChars = hexString.toCharArray(); + byte[] d = new byte[length]; + for (int i = 0; i < length; i++) { + int pos = i * 2; + d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1])); + } + return d; + } + + private static byte charToByte(char c) { + return (byte) "0123456789ABCDEF".indexOf(c); + } + } diff --git a/src/main/java/com/yexuejc/base/util/DateUtil.java b/src/main/java/com/yexuejc/base/util/DateUtil.java index b037fcf..e2016d2 100644 --- a/src/main/java/com/yexuejc/base/util/DateUtil.java +++ b/src/main/java/com/yexuejc/base/util/DateUtil.java @@ -6,7 +6,13 @@ import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; - +/** + * java.util.Date 时间工具类 + * @ClassName DateUtil + * @Description + * @author maxf + * @date 2018/9/3 15:27 + */ public class DateUtil { private DateUtil() { } @@ -71,7 +77,7 @@ public class DateUtil { /** * 日期字符串转date * - * @param date + * @param dateStr * @return Date * @throws ParseException */ diff --git a/src/main/java/com/yexuejc/base/util/ImgUtil.java b/src/main/java/com/yexuejc/base/util/ImgUtil.java new file mode 100644 index 0000000..55d5448 --- /dev/null +++ b/src/main/java/com/yexuejc/base/util/ImgUtil.java @@ -0,0 +1,419 @@ +package com.yexuejc.base.util; + +import sun.misc.BASE64Decoder; +import sun.misc.BASE64Encoder; + +import javax.imageio.ImageIO; +import javax.imageio.ImageReader; +import javax.imageio.stream.ImageInputStream; +import java.io.*; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.Proxy; +import java.net.URL; +import java.util.Iterator; + +/** + * 图片处理工具类 + * + * @author maxf + * @ClassName ImageUtil + * @Description + * @date 2018/9/3 15:25 + */ +public class ImgUtil { + + /** + * 将一张网络图片转化成Base64字符串 + * + * @param imgURL 网络图片url + * @return String Base64字符串 + */ + public static String getImageStrFromUrl(String imgURL) { + ByteArrayOutputStream data = new ByteArrayOutputStream(); + try { + byte[] by = new byte[1024]; + InputStream is = getImageInputStreamFromUrl(null, imgURL); + // 将内容读取内存中 + int len = -1; + while ((len = is.read(by)) != -1) { + data.write(by, 0, len); + } + // 关闭流 + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + // 对字节数组Base64编码 + BASE64Encoder encoder = new BASE64Encoder(); + return encoder.encode(data.toByteArray()); + } + + /** + * 读取网络图片url为输入流 + *

本方法未关闭io流,请自行关闭io流

+ *

is.close();

+ * + * @param imgURL 网络图片url + * @return InputStream 输入流 + * @throws IOException + */ + public static InputStream getImageInputStreamFromUrl(Proxy proxy, String imgURL) throws IOException { + // 创建URL + URL url = new URL(imgURL); + // 创建链接 + HttpURLConnection conn; + if (null == proxy) { + conn = (HttpURLConnection) url.openConnection(); + } else { + // 如果有代理则通过代理下载 + conn = (HttpURLConnection) url.openConnection(proxy); + } + conn.setRequestMethod("GET"); + conn.setConnectTimeout(5000); + InputStream is = conn.getInputStream(); + return is; + } + + /** + * 读取网络图片url为输入流 + *

本方法未关闭io流,请自行关闭io流

+ *

is.close();

+ * + * @param imgURL + * @return + * @throws IOException + */ + public static InputStream getImageInputStreamFromUrl(String imgURL) throws IOException { + return getImageInputStreamFromUrl(null, imgURL); + } + + + /** + * 将图片文件流转换成字节数组 + *

+ * 好处就是字节数组可以多次利用,而流一旦读取过一次之后就不能再使用了 + * + * @param proxy + * @param targetUrl + * @return + * @throws MalformedURLException + * @throws IOException + */ + public static byte[] getByteArrayFromInputStream(Proxy proxy, String targetUrl) + throws MalformedURLException, IOException { + InputStream is = getImageInputStreamFromUrl(proxy, targetUrl); + return getByteArray(is); + } + + /** + * 将图片文件流转换成字节数组 + *

+ * 好处就是字节数组可以多次利用,而流一旦读取过一次之后就不能再使用了 + * + * @param targetUrl + * @return + * @throws MalformedURLException + * @throws IOException + */ + public static byte[] getByteArrayFromInputStream(String targetUrl) + throws MalformedURLException, IOException { + return getByteArrayFromInputStream(null, targetUrl); + } + + /** + * 将图片文件流转换成字节数组 + * + * @return + * @throws MalformedURLException + * @throws IOException + */ + public static byte[] getByteArray(InputStream is) + throws MalformedURLException, IOException { + // 把文件写到字节数组保存起来 + ByteArrayOutputStream fos = getByteArrayFromInputStream(is); + byte[] bytes = fos.toByteArray(); + fos.close(); + return bytes; + } + + /** + * ByteArrayOutputStream转换成字节数组 + * + * @param fos + * @return + * @throws MalformedURLException + * @throws IOException + */ + public static byte[] getByteArray(ByteArrayOutputStream fos) + throws MalformedURLException, IOException { + // 把文件写到字节数组保存起来 + byte[] bytes = fos.toByteArray(); + fos.close(); + return bytes; + } + + /** + * 将图片文件流转换成ByteArrayOutputStream + *

本方法未关闭io流,请自行关闭io流

+ *

is.close();

+ * + * @param is + * @return + * @throws IOException + */ + public static ByteArrayOutputStream getByteArrayFromInputStream(InputStream is) throws IOException { + // 把文件写到字节数组保存起来 + BufferedInputStream bis = new BufferedInputStream(is); + ByteArrayOutputStream fos = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + int len = 0; + while ((len = bis.read(buffer)) != -1) { + fos.write(buffer, 0, len); + } + bis.close(); + return fos; + } + + /** + * 如果你已经将图片文件流InputStream读取出来放到一个字节数组 + *

+ * 那么根据这个字节数组也是可以转换成对应的图片流,并再次获取图片基本信息 + * + * @param imgBytes + * @return + */ + public static ImageInfo getImageInfoFromInputStream(byte[] imgBytes) { + ByteArrayInputStream in = new ByteArrayInputStream(imgBytes); + ImageInfo image = getImageInfoFromInputStream(in); + return image; + } + + /** + * 从图片文件流读取图片文件的基本信息 + * + * @param inputStream + * @return + */ + public static ImageInfo getImageInfoFromInputStream(InputStream inputStream) { + ImageInputStream imgStream = null; + try { + // 创建Image流 + imgStream = ImageIO.createImageInputStream(inputStream); + Iterator iter = ImageIO.getImageReaders(imgStream); + if (!iter.hasNext()) { + return null; + } + // 读取流中一帧就可以获取到高宽以及各式 + ImageReader reader = iter.next(); + reader.setInput(imgStream, true); + int width = reader.getWidth(0); + int height = reader.getHeight(0); + String type = reader.getFormatName(); + ImageInfo bean = new ImageInfo(); + bean.setWidth(width); + bean.setHeight(height); + bean.setType(type); + return bean; + } catch (IOException e) { + e.printStackTrace(); + return null; + } finally { + try { + imgStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + + /** + * 将byte数组以Base64方式编码为字符串 + * + * @param bytes 待编码的byte数组 + * @return String 编码后的字符串 + */ + public static String encode(byte[] bytes) { + return new BASE64Encoder().encode(bytes); + } + + /** + * 将以Base64方式编码的字符串解码为byte数组 + * + * @param encodeStr 待解码的字符串 + * @return byte[] 解码后的byte数组 + * @throws IOException + */ + public static byte[] decode(String encodeStr) throws IOException { + byte[] bt = null; + BASE64Decoder decoder = new BASE64Decoder(); + bt = decoder.decodeBuffer(encodeStr); + return bt; + } + + /** + * 将两个byte数组连接起来后,返回连接后的Byte数组 + * + * @param front 拼接后在前面的数组 + * @param after 拼接后在后面的数组 + * @return byte[] 拼接后的数组 + */ + public static byte[] connectBytes(byte[] front, byte[] after) { + byte[] result = new byte[front.length + after.length]; + System.arraycopy(front, 0, result, 0, after.length); + System.arraycopy(after, 0, result, front.length, after.length); + return result; + } + + /** + * 将流保存至本机或者图片服务器 + * + * @param in 图片流 + * @param saveUrl 目标地址 + * @throws IOException + */ + public static void saveImgFromInputStream(InputStream in, String saveUrl) throws IOException { + BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(saveUrl)); + byte[] buffer = new byte[1024]; + int len = 0; + while ((len = in.read(buffer)) != -1) { + bos.write(buffer, 0, len); + } + bos.close(); + in.close(); + } + + + /** + * 将图片以Base64方式编码为字符串 + * + * @param imgUrl 图片的绝对路径(例如:D:\\1.jpg) + * @return String 编码后的字符串 + * @throws IOException + */ + public static String encodeImage(String imgUrl) throws IOException { + FileInputStream fis = new FileInputStream(imgUrl); + byte[] rs = new byte[fis.available()]; + fis.read(rs); + fis.close(); + return encode(rs); + } + + /** + * 获取图片返回bate[] + * + * @param imgUrl 图片的绝对路径(例如:D:\\1.jpg) + * @return byte[] + * @throws IOException + */ + public static byte[] byteImage(String imgUrl) throws IOException { + FileInputStream fis = new FileInputStream(imgUrl); + byte[] rs = new byte[fis.available()]; + return rs; + } + + public static class ImageInfo { + /** + * 图片大小 + */ + private long size = 0; + /** + * 图片宽度 + */ + private int width = 0; + /** + * 图片高度 + */ + private int height = 0; + /** + * 图片类型 + */ + private String type = "jpg"; + /** + * 符号要求的图片类型 + */ + private String[] validTypes; + + /** + * 定义一个简单方法描述该图片是否符合要求 + * + * @param validImg + * @return + */ + public boolean isValidImg(ImageInfo validImg) { + if (null == validImg) { + return true; + } + return (this.getSize() <= validImg.getSize()) && (this.getWidth() <= validImg.getWidth()) + && (this.getHeight() <= validImg.getHeight()) && isValidType(validImg); + + } + + private boolean isValidType(ImageInfo validImg) { + if (null == validImg.getValidTypes()) { + return true; + } + boolean isValid = false; + for (String validType : validImg.getValidTypes()) { + if (type.equalsIgnoreCase(validType)) { + isValid = true; + break; + } + } + return isValid; + } + + private String validTypeToString() { + if (null == validTypes) { + return ""; + } + StringBuffer sb = new StringBuffer("["); + for (String type : validTypes) { + sb.append(type).append(" "); + } + sb.append("]"); + return sb.toString(); + } + + public long getSize() { + return size; + } + + public void setSize(long size) { + this.size = size; + } + + public int getWidth() { + return width; + } + + public void setWidth(int width) { + this.width = width; + } + + public int getHeight() { + return height; + } + + public void setHeight(int height) { + this.height = height; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String[] getValidTypes() { + return validTypes; + } + + public void setValidTypes(String[] validTypes) { + this.validTypes = validTypes; + } + } +} diff --git a/src/main/java/com/yexuejc/base/util/JsonUtil.java b/src/main/java/com/yexuejc/base/util/JsonUtil.java index 9b650da..5ca30e9 100644 --- a/src/main/java/com/yexuejc/base/util/JsonUtil.java +++ b/src/main/java/com/yexuejc/base/util/JsonUtil.java @@ -9,6 +9,14 @@ import com.fasterxml.jackson.databind.*; import java.io.IOException; import java.io.InputStream; +/** + * json工具类,基于jackson + * + * @author maxf + * @ClassName JsonUtil + * @Description + * @date 2018/9/3 15:28 + */ public class JsonUtil { private JsonUtil() { } diff --git a/src/main/java/com/yexuejc/base/util/JwtUtil.java b/src/main/java/com/yexuejc/base/util/JwtUtil.java index c855c61..600dab6 100644 --- a/src/main/java/com/yexuejc/base/util/JwtUtil.java +++ b/src/main/java/com/yexuejc/base/util/JwtUtil.java @@ -6,17 +6,71 @@ import io.jsonwebtoken.SignatureAlgorithm; import java.util.Date; import java.util.Map; +/** + * jwt工具类 + * + * @author maxf + * @ClassName JwtUtil + * @Description + * @date 2018/9/3 15:28 + */ public class JwtUtil { - /** 加密用KEY */ + /** + * 加密用KEY + */ private static String JWT_SIGNATURE_KEY = "h%OG8Y3WgA5AN7&6Ke7I#C1XvneW0N8a"; - /** token类型 */ + /** + * token类型 + */ private static String JWT_HEADER_TYP = "JWT"; - /** token发行商 */ + /** + * token发行商 + */ private static String JWT_CLAIMS_ISS = "yexuejc.com"; + /** + * 设置配置 + * + * @param key + * @param type + * @param iss + */ + public static void setConf(String key, String type, String iss) { + JWT_SIGNATURE_KEY = key; + JWT_HEADER_TYP = type; + JWT_CLAIMS_ISS = iss; + } + + /** + * 加密用KEY + * + * @param key + */ + public static void setSignatureKey(String key) { + JWT_SIGNATURE_KEY = key; + } + + /** + * token类型 + * + * @param type + */ + public static void setHeaderType(String type) { + JWT_HEADER_TYP = type; + } + + /** + * token发行商 + * + * @param iss + */ + public static void setClaimsIss(String iss) { + JWT_CLAIMS_ISS = iss; + } + /** * 加密内容生成token - * + * * @param subjectObj * @return */ @@ -48,7 +102,7 @@ public class JwtUtil { /** * 解密token为一个Map - * + * * @param token * @return */ @@ -58,7 +112,7 @@ public class JwtUtil { /** * 解密token为一个指定对象 - * + * * @param token * @param cls * @return diff --git a/src/main/java/com/yexuejc/base/util/MapRemoveNullUtil.java b/src/main/java/com/yexuejc/base/util/MapRemoveNullUtil.java index 1442a8f..0062329 100644 --- a/src/main/java/com/yexuejc/base/util/MapRemoveNullUtil.java +++ b/src/main/java/com/yexuejc/base/util/MapRemoveNullUtil.java @@ -5,6 +5,14 @@ import java.util.Iterator; import java.util.Map; import java.util.Set; +/** + * map相关工具 + * + * @author maxf + * @ClassName MapRemoveNullUtil + * @Description + * @date 2018/9/3 15:32 + */ public class MapRemoveNullUtil { private MapRemoveNullUtil() { } diff --git a/src/main/java/com/yexuejc/base/util/MoneyUtils.java b/src/main/java/com/yexuejc/base/util/MoneyUtils.java index 646dd80..7a4e23c 100644 --- a/src/main/java/com/yexuejc/base/util/MoneyUtils.java +++ b/src/main/java/com/yexuejc/base/util/MoneyUtils.java @@ -4,7 +4,7 @@ import java.math.BigDecimal; import java.text.DecimalFormat; /** - * q钱相关工具类 + * 钱相关工具类 * * @ClassName: MoneyUtils * @Description: diff --git a/src/main/java/com/yexuejc/base/util/ThreeDES.java b/src/main/java/com/yexuejc/base/util/ThreeDES.java new file mode 100644 index 0000000..665171d --- /dev/null +++ b/src/main/java/com/yexuejc/base/util/ThreeDES.java @@ -0,0 +1,101 @@ +package com.yexuejc.base.util; + +import org.apache.commons.codec.binary.Base64; + +import javax.crypto.Cipher; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.DESedeKeySpec; +import javax.crypto.spec.IvParameterSpec; +import java.io.UnsupportedEncodingException; +import java.security.InvalidKeyException; +import java.security.Key; + + +/** + * 3DES加解密 + * + * @author maxf + * @ClassName ThreeDES + * @Description + * @date 2018/9/3 17:09 + */ +public class ThreeDES { + + private static final String IV = "1234567-"; + private final static String encoding = "utf-8"; + + /** + * DESCBC加密 + * + * @param src 数据源 + * @param key 密钥 + * @return 返回加密后的数据 + * @throws Exception + */ + public static String encryptDESCBC(final String src, final String key) throws Exception { + if (key.length() < 24) { + throw new InvalidKeyException("key的length不得小于24"); + } + Key deskey = null; + DESedeKeySpec spec = new DESedeKeySpec(key.getBytes()); + SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede"); + deskey = keyfactory.generateSecret(spec); + + Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding"); + IvParameterSpec ips = new IvParameterSpec(IV.getBytes()); + cipher.init(Cipher.ENCRYPT_MODE, deskey, ips); + byte[] encryptData = cipher.doFinal(src.getBytes(encoding)); + return Base64.encodeBase64URLSafeString(encryptData); + } + + /** + * DESCBC解密 + * + * @param src 数据源 + * @param key 密钥 + * @return 返回解密后的原始数据 + * @throws Exception + */ + public static String decryptDESCBC(final String src, final String key) throws Exception { + if (key.length() < 24) { + throw new InvalidKeyException("key的length不得小于24"); + } + Key deskey = null; + DESedeKeySpec spec = new DESedeKeySpec(key.getBytes()); + SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede"); + deskey = keyfactory.generateSecret(spec); + Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding"); + IvParameterSpec ips = new IvParameterSpec(IV.getBytes()); + cipher.init(Cipher.DECRYPT_MODE, deskey, ips); + + byte[] decryptData = cipher.doFinal(Base64.decodeBase64(src)); + + return new String(decryptData, encoding); + } + + /** + * 填充,不是8的倍数会填充成8的倍数 + * + * @param str + * @return + */ + public static String padding(String str) { + byte[] oldByteArray; + try { + oldByteArray = str.getBytes("UTF8"); + int numberToPad = 8 - oldByteArray.length % 8; + byte[] newByteArray = new byte[oldByteArray.length + numberToPad]; + System.arraycopy(oldByteArray, 0, newByteArray, 0, + oldByteArray.length); + for (int i = oldByteArray.length; i < newByteArray.length; ++i) { + newByteArray[i] = 0; + } + return new String(newByteArray, "UTF8"); + } catch (UnsupportedEncodingException e) { + System.out.println("Crypter.padding UnsupportedEncodingException"); + } + return null; + } + +} + From 5545bcfc9f36a9525fd712b2d51f4fd63e2d9f5f Mon Sep 17 00:00:00 2001 From: yexuejc <940526mf> Date: Mon, 3 Sep 2018 19:30:04 +0800 Subject: [PATCH 02/27] 1.1.8 --- UPDATE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/UPDATE.md b/UPDATE.md index 5489860..ea37f9d 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -2,7 +2,7 @@ yexuejc-base 更新记录 ------------------ #### version :1.1.8 -**time:2018-8-17 11:22:50**
+**time:2018-9-3 19:29:56**
**branch:** master
**update:**
>1. 增肌图片处理工具类 From e890fd94c31f17dbc20ddc30459a571537cc21c9 Mon Sep 17 00:00:00 2001 From: yexuejc <1107047387@qq.com> Date: Sun, 23 Sep 2018 12:01:27 +0800 Subject: [PATCH 03/27] 1.1.9 --- ..._validation_validation_api_1_1_0_Final.xml | 6 +- README.md | 13 +++- UPDATE.md | 8 ++ pom.xml | 2 +- ...AlgorithmUtils.java => AlgorithmUtil.java} | 6 +- .../com/yexuejc/base/util/DateTimeUtil.java | 9 ++- .../java/com/yexuejc/base/util/DateUtil.java | 40 ++++++++-- ...lImportUtils.java => ExcelImportUtil.java} | 5 +- .../java/com/yexuejc/base/util/ImgUtil.java | 2 + .../java/com/yexuejc/base/util/JwtUtil.java | 74 +++++++++---------- .../util/{MoneyUtils.java => MoneyUtil.java} | 4 +- .../util/{RegexUtils.java => RegexUtil.java} | 4 +- .../java/com/yexuejc/base/util/StrUtil.java | 3 + .../base/util/{SysUtils.java => SysUtil.java} | 4 +- .../java/com/yexuejc/base/util/ThreeDES.java | 2 + 15 files changed, 117 insertions(+), 65 deletions(-) rename src/main/java/com/yexuejc/base/util/{AlgorithmUtils.java => AlgorithmUtil.java} (97%) rename src/main/java/com/yexuejc/base/util/{ExcelImportUtils.java => ExcelImportUtil.java} (93%) rename src/main/java/com/yexuejc/base/util/{MoneyUtils.java => MoneyUtil.java} (95%) rename src/main/java/com/yexuejc/base/util/{RegexUtils.java => RegexUtil.java} (97%) rename src/main/java/com/yexuejc/base/util/{SysUtils.java => SysUtil.java} (93%) diff --git a/.idea/libraries/Maven__javax_validation_validation_api_1_1_0_Final.xml b/.idea/libraries/Maven__javax_validation_validation_api_1_1_0_Final.xml index 940ce73..59561b6 100644 --- a/.idea/libraries/Maven__javax_validation_validation_api_1_1_0_Final.xml +++ b/.idea/libraries/Maven__javax_validation_validation_api_1_1_0_Final.xml @@ -1,13 +1,13 @@ - + - + - + \ No newline at end of file diff --git a/README.md b/README.md index b691406..b85f6dd 100644 --- a/README.md +++ b/README.md @@ -3,11 +3,20 @@ ### 说明 >1. 支持环境:java8 >2. 该工具包基于springboot提取,按理说适用于所有java工程 ->3. 其中依赖jjwt、validation-api,但不传递依赖 +>3. 其中依赖jjwt、validation-api,排除请使用 +``` + + + xxx + xxxx + + +``` +>4. 1.1.9升级JWT为单例类 ### 使用 ->yexuejc.base.version=1.1.7 +>yexuejc.base.version=1.1.9 pom.xml ``` diff --git a/UPDATE.md b/UPDATE.md index ea37f9d..eae03f6 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -1,6 +1,14 @@ yexuejc-base 更新记录 ------------------ +#### version :1.1.9 +**time:2018-9-23 11:57:36**
+**branch:** master
+**update:**
+>1. 优化工具类包名:不向下兼容,升级请修改 +>2. 升级JWT工具类:更改为单例模式,可配置参数 +# + #### version :1.1.8 **time:2018-9-3 19:29:56**
**branch:** master
diff --git a/pom.xml b/pom.xml index 30f0df3..15a43f6 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.yexuejc.base yexuejc-base - 1.1.8 + 1.1.9 ${project.artifactId} diff --git a/src/main/java/com/yexuejc/base/util/AlgorithmUtils.java b/src/main/java/com/yexuejc/base/util/AlgorithmUtil.java similarity index 97% rename from src/main/java/com/yexuejc/base/util/AlgorithmUtils.java rename to src/main/java/com/yexuejc/base/util/AlgorithmUtil.java index 8917516..206021f 100644 --- a/src/main/java/com/yexuejc/base/util/AlgorithmUtils.java +++ b/src/main/java/com/yexuejc/base/util/AlgorithmUtil.java @@ -1,8 +1,6 @@ package com.yexuejc.base.util; -import sun.misc.BASE64Decoder; - /** * 算法工具类 * @@ -11,13 +9,13 @@ import sun.misc.BASE64Decoder; * @author: maxf * @date: 2017年11月23日 下午3:17:58 */ -public class AlgorithmUtils { +public class AlgorithmUtil { private static final int LENGTH_1 = 1; private static final int LENGTH_2 = 2; private static final int LENGTH_3 = 3; private static final int LENGTH_36 = 36; - private AlgorithmUtils() { + private AlgorithmUtil() { } private static final String X36 = "0123456789abcdefghijklmnopqrstuvwxyz"; diff --git a/src/main/java/com/yexuejc/base/util/DateTimeUtil.java b/src/main/java/com/yexuejc/base/util/DateTimeUtil.java index abb4dd2..0bf9db1 100644 --- a/src/main/java/com/yexuejc/base/util/DateTimeUtil.java +++ b/src/main/java/com/yexuejc/base/util/DateTimeUtil.java @@ -13,6 +13,9 @@ import java.util.Date; * @date: 2018/3/27 10:44 */ public class DateTimeUtil { + private DateTimeUtil() { + } + /** * 获取本年第一天 * @@ -106,7 +109,8 @@ public class DateTimeUtil { * @return */ public static LocalDate getWeek4First(LocalDate date) { - TemporalAdjuster FIRST_OF_WEEK = TemporalAdjusters.ofDateAdjuster(localDate -> localDate.minusDays(localDate.getDayOfWeek().getValue() - DayOfWeek.MONDAY.getValue())); + TemporalAdjuster FIRST_OF_WEEK = + TemporalAdjusters.ofDateAdjuster(localDate -> localDate.minusDays(localDate.getDayOfWeek().getValue() - DayOfWeek.MONDAY.getValue())); return date.with(FIRST_OF_WEEK); } @@ -126,7 +130,8 @@ public class DateTimeUtil { * @return */ public static LocalDate getWeek4Last(LocalDate date) { - TemporalAdjuster LAST_OF_WEEK = TemporalAdjusters.ofDateAdjuster(localDate -> localDate.plusDays(DayOfWeek.SUNDAY.getValue() - localDate.getDayOfWeek().getValue())); + TemporalAdjuster LAST_OF_WEEK = + TemporalAdjusters.ofDateAdjuster(localDate -> localDate.plusDays(DayOfWeek.SUNDAY.getValue() - localDate.getDayOfWeek().getValue())); return date.with(LAST_OF_WEEK); } diff --git a/src/main/java/com/yexuejc/base/util/DateUtil.java b/src/main/java/com/yexuejc/base/util/DateUtil.java index e2016d2..3053c21 100644 --- a/src/main/java/com/yexuejc/base/util/DateUtil.java +++ b/src/main/java/com/yexuejc/base/util/DateUtil.java @@ -6,12 +6,14 @@ import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; + /** - * java.util.Date 时间工具类 - * @ClassName DateUtil + * java.util.Date 时间工具类 + * + * @author maxf + * @ClassName DateUtil * @Description - * @author maxf - * @date 2018/9/3 15:27 + * @date 2018/9/3 15:27 */ public class DateUtil { private DateUtil() { @@ -87,7 +89,7 @@ public class DateUtil { } /** - * 日期字符串转date + * date转字符串 * * @param date * @return Date @@ -101,6 +103,34 @@ public class DateUtil { } } + /** + * 日期字符串转dateTime + * + * @param dateStr + * @return + * @throws ParseException + */ + public static Date str2dateTime(String dateStr) throws ParseException { + Date date = DATE_TIME_FORMAT.parse(dateStr); + return date; + } + + /** + * dateTime转字符串 + * + * @param date + * @return Date + * @throws ParseException + */ + public static String dateTime2str(Date date) throws ParseException { + if (date != null) { + return DATE_TIME_FORMAT.format(date); + } else { + return "null"; + } + } + + /** * 获取本周的日期 * diff --git a/src/main/java/com/yexuejc/base/util/ExcelImportUtils.java b/src/main/java/com/yexuejc/base/util/ExcelImportUtil.java similarity index 93% rename from src/main/java/com/yexuejc/base/util/ExcelImportUtils.java rename to src/main/java/com/yexuejc/base/util/ExcelImportUtil.java index ecd599a..92ef717 100644 --- a/src/main/java/com/yexuejc/base/util/ExcelImportUtils.java +++ b/src/main/java/com/yexuejc/base/util/ExcelImportUtil.java @@ -8,8 +8,9 @@ package com.yexuejc.base.util; * @author: maxf * @date: 2017/12/27 16:42 */ -public class ExcelImportUtils { - +public class ExcelImportUtil { + private ExcelImportUtil() { + } /** * 是否是2003的excel,返回true是2003 diff --git a/src/main/java/com/yexuejc/base/util/ImgUtil.java b/src/main/java/com/yexuejc/base/util/ImgUtil.java index 55d5448..67a2b75 100644 --- a/src/main/java/com/yexuejc/base/util/ImgUtil.java +++ b/src/main/java/com/yexuejc/base/util/ImgUtil.java @@ -22,6 +22,8 @@ import java.util.Iterator; * @date 2018/9/3 15:25 */ public class ImgUtil { + private ImgUtil() { + } /** * 将一张网络图片转化成Base64字符串 diff --git a/src/main/java/com/yexuejc/base/util/JwtUtil.java b/src/main/java/com/yexuejc/base/util/JwtUtil.java index 600dab6..fde70fb 100644 --- a/src/main/java/com/yexuejc/base/util/JwtUtil.java +++ b/src/main/java/com/yexuejc/base/util/JwtUtil.java @@ -8,65 +8,59 @@ import java.util.Map; /** * jwt工具类 + *

+ * 升级2.0 + *
+ * 由静态类分装成单例类,可配置参数config() + *

* * @author maxf + * @version 2.0 * @ClassName JwtUtil * @Description * @date 2018/9/3 15:28 */ public class JwtUtil { - /** - * 加密用KEY - */ - private static String JWT_SIGNATURE_KEY = "h%OG8Y3WgA5AN7&6Ke7I#C1XvneW0N8a"; - /** - * token类型 - */ - private static String JWT_HEADER_TYP = "JWT"; - /** - * token发行商 - */ - private static String JWT_CLAIMS_ISS = "yexuejc.com"; + + private JwtUtil() { + } + + public static JwtUtil instace() { + return Instace.jwtUtil; + } /** - * 设置配置 + * 参数配置:设置一次即可,多次设置会覆盖之前的 * - * @param key - * @param type - * @param iss + * @param key 加密key 默认:h%OG8Y3WgA5AN7&6Ke7I#C1XvneW0N8a + * @param type 加密类型:默认JWT + * @param iss token发行商: 默认yexuejc.com + * @return */ - public static void setConf(String key, String type, String iss) { - JWT_SIGNATURE_KEY = key; - JWT_HEADER_TYP = type; - JWT_CLAIMS_ISS = iss; + public static JwtUtil config(String key, String type, String iss) { + JwtUtil jwtUtil = instace(); + jwtUtil.JWT_SIGNATURE_KEY = key; + jwtUtil.JWT_HEADER_TYP = type; + jwtUtil.JWT_CLAIMS_ISS = iss; + return jwtUtil; + } + + public static class Instace { + private static JwtUtil jwtUtil = new JwtUtil(); } /** * 加密用KEY - * - * @param key */ - public static void setSignatureKey(String key) { - JWT_SIGNATURE_KEY = key; - } - + private String JWT_SIGNATURE_KEY = "h%OG8Y3WgA5AN7&6Ke7I#C1XvneW0N8a"; /** * token类型 - * - * @param type */ - public static void setHeaderType(String type) { - JWT_HEADER_TYP = type; - } - + private String JWT_HEADER_TYP = "JWT"; /** * token发行商 - * - * @param iss */ - public static void setClaimsIss(String iss) { - JWT_CLAIMS_ISS = iss; - } + private String JWT_CLAIMS_ISS = "yexuejc.com"; /** * 加密内容生成token @@ -74,7 +68,7 @@ public class JwtUtil { * @param subjectObj * @return */ - public static String compact(Object subjectObj) { + public String compact(Object subjectObj) { String subject = null; if (subjectObj instanceof String) { subject = (String) subjectObj; @@ -106,7 +100,7 @@ public class JwtUtil { * @param token * @return */ - public static Map parse(String token) { + public Map parse(String token) { return parse(token, Map.class); } @@ -117,7 +111,7 @@ public class JwtUtil { * @param cls * @return */ - public static T parse(String token, Class cls) { + public T parse(String token, Class cls) { String subject = null; try { subject = Jwts.parser().setSigningKey(JWT_SIGNATURE_KEY).parseClaimsJws(token).getBody().getSubject(); diff --git a/src/main/java/com/yexuejc/base/util/MoneyUtils.java b/src/main/java/com/yexuejc/base/util/MoneyUtil.java similarity index 95% rename from src/main/java/com/yexuejc/base/util/MoneyUtils.java rename to src/main/java/com/yexuejc/base/util/MoneyUtil.java index 7a4e23c..7ed508d 100644 --- a/src/main/java/com/yexuejc/base/util/MoneyUtils.java +++ b/src/main/java/com/yexuejc/base/util/MoneyUtil.java @@ -11,8 +11,8 @@ import java.text.DecimalFormat; * @author: maxf * @date: 2017年12月1日 下午5:33:57 */ -public class MoneyUtils { - private MoneyUtils() { +public class MoneyUtil { + private MoneyUtil() { } /** diff --git a/src/main/java/com/yexuejc/base/util/RegexUtils.java b/src/main/java/com/yexuejc/base/util/RegexUtil.java similarity index 97% rename from src/main/java/com/yexuejc/base/util/RegexUtils.java rename to src/main/java/com/yexuejc/base/util/RegexUtil.java index 137e1b8..5c7daa6 100644 --- a/src/main/java/com/yexuejc/base/util/RegexUtils.java +++ b/src/main/java/com/yexuejc/base/util/RegexUtil.java @@ -10,8 +10,8 @@ import java.util.regex.Pattern; * @expl * @time 2017年11月9日 上午11:01:24 */ -public class RegexUtils { - private RegexUtils() { +public class RegexUtil { + private RegexUtil() { } /** diff --git a/src/main/java/com/yexuejc/base/util/StrUtil.java b/src/main/java/com/yexuejc/base/util/StrUtil.java index ab22cfe..7766a02 100644 --- a/src/main/java/com/yexuejc/base/util/StrUtil.java +++ b/src/main/java/com/yexuejc/base/util/StrUtil.java @@ -16,6 +16,9 @@ import java.util.regex.Pattern; * @date: 2018/5/12 19:13 */ public final class StrUtil { + private StrUtil() { + } + public static char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; /** diff --git a/src/main/java/com/yexuejc/base/util/SysUtils.java b/src/main/java/com/yexuejc/base/util/SysUtil.java similarity index 93% rename from src/main/java/com/yexuejc/base/util/SysUtils.java rename to src/main/java/com/yexuejc/base/util/SysUtil.java index b992c2c..0131308 100644 --- a/src/main/java/com/yexuejc/base/util/SysUtils.java +++ b/src/main/java/com/yexuejc/base/util/SysUtil.java @@ -10,10 +10,10 @@ import java.net.URL; * @author: maxf * @date: 2017/12/28 16:12 */ -public class SysUtils { +public class SysUtil { private static final String PROJECT_ROOT_PATH = "java.io.tmpdir"; - private SysUtils() { + private SysUtil() { } /** diff --git a/src/main/java/com/yexuejc/base/util/ThreeDES.java b/src/main/java/com/yexuejc/base/util/ThreeDES.java index 665171d..28e14e1 100644 --- a/src/main/java/com/yexuejc/base/util/ThreeDES.java +++ b/src/main/java/com/yexuejc/base/util/ThreeDES.java @@ -20,6 +20,8 @@ import java.security.Key; * @date 2018/9/3 17:09 */ public class ThreeDES { + private ThreeDES() { + } private static final String IV = "1234567-"; private final static String encoding = "utf-8"; From 5ecb759db998872d9fc5d95f1013d23cf7849a11 Mon Sep 17 00:00:00 2001 From: yexuejc <940526mf> Date: Fri, 19 Oct 2018 11:29:54 +0800 Subject: [PATCH 04/27] =?UTF-8?q?=E5=88=A0=E9=99=A4=E5=A4=9A=E4=BD=99?= =?UTF-8?q?=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ..._javax_validation_validation_api_1_1_0_Final.xml | 13 ------------- 1 file changed, 13 deletions(-) delete mode 100644 .idea/libraries/Maven__javax_validation_validation_api_1_1_0_Final.xml diff --git a/.idea/libraries/Maven__javax_validation_validation_api_1_1_0_Final.xml b/.idea/libraries/Maven__javax_validation_validation_api_1_1_0_Final.xml deleted file mode 100644 index 59561b6..0000000 --- a/.idea/libraries/Maven__javax_validation_validation_api_1_1_0_Final.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file From e00164f85b9b0daef998fb0b02f2aa2b01c56f0e Mon Sep 17 00:00:00 2001 From: yexuejc <940526mf> Date: Fri, 19 Oct 2018 11:40:19 +0800 Subject: [PATCH 05/27] =?UTF-8?q?1.2.0=20=E5=A2=9E=E5=8A=A0=E5=BC=82?= =?UTF-8?q?=E6=AD=A5=E7=BA=BF=E7=A8=8B=E5=A4=84=E7=90=86=E5=B7=A5=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- UPDATE.md | 12 ++++++ pom.xml | 9 +++- .../java/com/yexuejc/base/util/SysUtil.java | 41 +++++++++++++++++++ 4 files changed, 62 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b85f6dd..bc39205 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ ### 使用 ->yexuejc.base.version=1.1.9 +>yexuejc.base.version=1.2.0 pom.xml ``` diff --git a/UPDATE.md b/UPDATE.md index eae03f6..e92436b 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -1,6 +1,18 @@ yexuejc-base 更新记录 ------------------ +#### version :1.2.0 +**time:2018-10-19 11:38:20**
+**branch:** master
+**update:**
+>1. 增加异步线程处理工具 +```$java +SysUtil.threadRun(() -> { + //异步执行代码块 +} +``` +# + #### version :1.1.9 **time:2018-9-23 11:57:36**
**branch:** master
diff --git a/pom.xml b/pom.xml index 15a43f6..7cf1c16 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.yexuejc.base yexuejc-base - 1.1.9 + 1.2.0 ${project.artifactId} @@ -21,6 +21,7 @@ 1.10 2.6 1.60 + 20.0 @@ -55,6 +56,12 @@ bcprov-jdk15on ${bcprov-jdk15on.version} + + + com.google.guava + guava + ${guava.version} + diff --git a/src/main/java/com/yexuejc/base/util/SysUtil.java b/src/main/java/com/yexuejc/base/util/SysUtil.java index 0131308..5094146 100644 --- a/src/main/java/com/yexuejc/base/util/SysUtil.java +++ b/src/main/java/com/yexuejc/base/util/SysUtil.java @@ -1,6 +1,9 @@ package com.yexuejc.base.util; +import com.google.common.util.concurrent.ThreadFactoryBuilder; + import java.net.URL; +import java.util.concurrent.*; /** * 系统工具类 @@ -35,4 +38,42 @@ public class SysUtil { return clazz.getClass().getResource(StrUtil.setStr(filePath, "/")); } + /** + * 开启线程执行

+ * 异步处理代码 + * + * @param threadRun + */ + public static void threadRun(ThreadRun threadRun) { + threadRun(null, threadRun); + } + + /** + * 异步处理代码 + * + * @param poolName 开启线程名称 + * @param threadRun + */ + public static void threadRun(String poolName, ThreadRun threadRun) { + if (StrUtil.isEmpty(poolName)) { + poolName = "java-pool-%d"; + } + ThreadFactory namedThreadFactory = new ThreadFactoryBuilder() + .setNameFormat(poolName).build(); + ExecutorService singleThreadPool = new ThreadPoolExecutor(1, 1, + 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy()); + + singleThreadPool.execute(() -> { + threadRun.execute(); + }); + singleThreadPool.shutdown(); + } + + /** + * 异步执行代码块 + */ + public interface ThreadRun { + void execute(); + } } From 286c65b8688051562c68ba72e78852acb7008d71 Mon Sep 17 00:00:00 2001 From: maxf <1107047387@qq.com> Date: Fri, 9 Nov 2018 15:05:26 +0800 Subject: [PATCH 06/27] =?UTF-8?q?1.2.1=E6=9B=B4=E6=96=B0resps?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- UPDATE.md | 6 +++++ pom.xml | 2 +- .../java/com/yexuejc/base/http/Resps.java | 22 ++++++++++++++++--- 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/UPDATE.md b/UPDATE.md index e92436b..9919182 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -1,6 +1,12 @@ yexuejc-base 更新记录 ------------------ +#### version :1.2.1 +**time:2018-11-9 15:05:06**
+**branch:** master
+**update:**
+>1. 优化resps +# #### version :1.2.0 **time:2018-10-19 11:38:20**
**branch:** master
diff --git a/pom.xml b/pom.xml index 7cf1c16..4364178 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.yexuejc.base yexuejc-base - 1.2.0 + 1.2.1 ${project.artifactId} diff --git a/src/main/java/com/yexuejc/base/http/Resps.java b/src/main/java/com/yexuejc/base/http/Resps.java index ae2bf12..4a1c784 100644 --- a/src/main/java/com/yexuejc/base/http/Resps.java +++ b/src/main/java/com/yexuejc/base/http/Resps.java @@ -59,18 +59,18 @@ public class Resps implements Serializable { } public Resps setSucc(T t) { - setSucc(t, RespsConsts.MSG_SUCCESS_OPERATE); + this.data = t; return this; } public Resps setSucc(T t, String msg) { - setSucc(t, new String[]{msg}); + this.setMsg(new String[]{msg}); + this.setData(t); return this; } public Resps setSucc(T t, String[] msg) { this.setData(t); - this.setCode(RespsConsts.CODE_SUCCESS); this.setMsg(msg); return this; } @@ -81,6 +81,14 @@ public class Resps implements Serializable { return this; } + public static Resps success(String code, String msg) { + return new Resps(code, msg); + } + + public static Resps success(String code, String[] msg) { + return new Resps(code, msg); + } + public static Resps success(String[] msg) { return new Resps(RespsConsts.CODE_SUCCESS, msg); } @@ -93,6 +101,10 @@ public class Resps implements Serializable { return new Resps(RespsConsts.CODE_SUCCESS, RespsConsts.MSG_SUCCESS_OPERATE); } + public static Resps error() { + return new Resps(RespsConsts.CODE_ERROR, RespsConsts.MSG_ERROT_OPERATE); + } + public static Resps error(String msg) { return new Resps(RespsConsts.CODE_ERROR, msg); } @@ -109,6 +121,10 @@ public class Resps implements Serializable { return new Resps(code, msg); } + public static Resps fail() { + return new Resps(RespsConsts.CODE_FAIL, RespsConsts.MSG_FAIL_OPERATE); + } + public static Resps fail(String msg) { return new Resps(RespsConsts.CODE_FAIL, msg); } From 3ba0e22e65431812e379ebf7bdba833427a57fff Mon Sep 17 00:00:00 2001 From: maxf <1107047387@qq.com> Date: Tue, 20 Nov 2018 20:21:15 +0800 Subject: [PATCH 07/27] =?UTF-8?q?1.2.2=20=E5=A2=9E=E5=8A=A0RSA=E7=AD=BE?= =?UTF-8?q?=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- UPDATE.md | 7 ++ pom.xml | 2 +- .../java/com/yexuejc/base/encrypt/RSA.java | 114 +++++++++++++++++- .../yexuejc/base/encrypt/SignAlgorithm.java | 53 ++++++++ 4 files changed, 170 insertions(+), 6 deletions(-) create mode 100644 src/main/java/com/yexuejc/base/encrypt/SignAlgorithm.java diff --git a/UPDATE.md b/UPDATE.md index 9919182..fbc09a5 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -1,6 +1,13 @@ yexuejc-base 更新记录 ------------------ +#### version :1.2.2 +**time:2018-11-20 20:20:12**
+**branch:** master
+**update:**
+>1. 优化RSA 加解密 +>1. 增加RSA 签名 +# #### version :1.2.1 **time:2018-11-9 15:05:06**
**branch:** master
diff --git a/pom.xml b/pom.xml index 4364178..9115823 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.yexuejc.base yexuejc-base - 1.2.1 + 1.2.2 ${project.artifactId} diff --git a/src/main/java/com/yexuejc/base/encrypt/RSA.java b/src/main/java/com/yexuejc/base/encrypt/RSA.java index bbd5363..968d0fa 100644 --- a/src/main/java/com/yexuejc/base/encrypt/RSA.java +++ b/src/main/java/com/yexuejc/base/encrypt/RSA.java @@ -3,9 +3,12 @@ package com.yexuejc.base.encrypt; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; +import org.bouncycastle.jce.provider.BouncyCastleProvider; import javax.crypto.Cipher; +import javax.crypto.NoSuchPaddingException; import java.io.ByteArrayOutputStream; +import java.io.UnsupportedEncodingException; import java.security.*; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; @@ -27,6 +30,25 @@ public class RSA { public static final String CHARSET = "UTF-8"; public static final String RSA_ALGORITHM = "RSA"; + /** + * 加密方式 + *

+     *     RSA 可选择isChangeSign 是否每次改变加密结果
+     *     RSA/None/NoPadding 不改变加密结果
+     *     RSA/ECB/PKCS1Padding 改变加密结果
+     * 
+ */ + public static String RSA_ALGORITHM_ECB = "RSA"; + /** + * 是否每次改变加密结果 + * 只针对于RSA_ALGORITHM_ECB = "RSA"有效 + */ + public static boolean isChangeSign = true; + /** + * 签名算法 + */ + public static SignAlgorithm signAlgorithm = SignAlgorithm.SHA1withRSA; + public static Map initKeys(int keySize) { //为RSA算法创建一个KeyPairGenerator对象 @@ -61,7 +83,7 @@ public class RSA { * @param publicKey 密钥字符串(经过base64编码) * @throws Exception */ - public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException { + public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException{ //通过X509编码的Key指令获得公钥对象 KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey)); @@ -92,7 +114,7 @@ public class RSA { */ public static String publicEncrypt(String data, RSAPublicKey publicKey) { try { - Cipher cipher = Cipher.getInstance(RSA_ALGORITHM); + Cipher cipher = getCipher(); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength())); } catch (Exception e) { @@ -109,7 +131,7 @@ public class RSA { */ public static String privateDecrypt(String data, RSAPrivateKey privateKey) { try { - Cipher cipher = Cipher.getInstance(RSA_ALGORITHM); + Cipher cipher = getCipher(); cipher.init(Cipher.DECRYPT_MODE, privateKey); return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKey.getModulus().bitLength()), CHARSET); } catch (Exception e) { @@ -117,6 +139,7 @@ public class RSA { } } + /** * 私钥加密 * @@ -127,7 +150,7 @@ public class RSA { public static String privateEncrypt(String data, RSAPrivateKey privateKey) { try { - Cipher cipher = Cipher.getInstance(RSA_ALGORITHM); + Cipher cipher = getCipher(); cipher.init(Cipher.ENCRYPT_MODE, privateKey); return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength())); } catch (Exception e) { @@ -145,7 +168,7 @@ public class RSA { public static String publicDecrypt(String data, RSAPublicKey publicKey) { try { - Cipher cipher = Cipher.getInstance(RSA_ALGORITHM); + Cipher cipher = getCipher(); cipher.init(Cipher.DECRYPT_MODE, publicKey); return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), publicKey.getModulus().bitLength()), CHARSET); } catch (Exception e) { @@ -153,6 +176,25 @@ public class RSA { } } + /** + * 获取 Cipher + * + * @return + * @throws NoSuchPaddingException + * @throws NoSuchAlgorithmException + * @throws NoSuchProviderException + */ + private static Cipher getCipher() throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException { + Cipher cipher; + if ("RSA".equals(RSA_ALGORITHM_ECB) && isChangeSign) { + cipher = Cipher.getInstance(RSA_ALGORITHM_ECB); + } else { + Security.addProvider(new BouncyCastleProvider()); + cipher = Cipher.getInstance(RSA_ALGORITHM_ECB, "BC"); + } + return cipher; + } + private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) { int maxBlock = 0; if (opmode == Cipher.DECRYPT_MODE) { @@ -183,4 +225,66 @@ public class RSA { return resultDatas; } + private static Signature signature; + + /** + * 私钥签名:默认算法SHA1withRSA + *

+ * 签名算法 {@link SignAlgorithm} + *

+ * + * @param plaintext 签名字符串 + * @param privateKey 签名私钥 + * @return + * @throws NoSuchAlgorithmException + */ + public static String sign(String plaintext, RSAPrivateKey privateKey) throws NoSuchAlgorithmException { + signature = Signature.getInstance(signAlgorithm.getValue()); + String signBase64Str = ""; + + try { + signature.initSign(privateKey); + try { + signature.update(plaintext.getBytes(CHARSET)); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + throw new RuntimeException("签名字符串[" + plaintext + "]的数据时发生异常", e); + } + + signBase64Str = Base64.encodeBase64String(signature.sign()); + return signBase64Str; + } catch (InvalidKeyException var6) { + var6.printStackTrace(); + throw new RuntimeException("签名字符串[" + plaintext + "]的数据时发生异常", var6); + } catch (SignatureException var7) { + var7.printStackTrace(); + throw new RuntimeException("签名字符串[" + plaintext + "]的数据时发生异常", var7); + } + } + + /** + * 公钥校验签名 + * + * @param plaintext 原串 + * @param signStr 签名串 + * @param publicKey 公钥 + * @return + * @throws UnsupportedEncodingException + */ + public static boolean verify(String plaintext, String signStr, RSAPublicKey publicKey) throws UnsupportedEncodingException { + boolean isValid = false; + try { + signature.initVerify(publicKey); + signature.update(plaintext.getBytes(CHARSET)); + isValid = signature.verify(Base64.decodeBase64(signStr)); + } catch (InvalidKeyException var6) { + var6.printStackTrace(); + throw new RuntimeException("校验签名字符串[" + plaintext + "]的数据时发生异常", var6); + } catch (SignatureException var7) { + var7.printStackTrace(); + throw new RuntimeException("校验签名字符串[" + plaintext + "]的数据时发生异常", var7); + } + + return isValid; + } } diff --git a/src/main/java/com/yexuejc/base/encrypt/SignAlgorithm.java b/src/main/java/com/yexuejc/base/encrypt/SignAlgorithm.java new file mode 100644 index 0000000..efbda90 --- /dev/null +++ b/src/main/java/com/yexuejc/base/encrypt/SignAlgorithm.java @@ -0,0 +1,53 @@ +package com.yexuejc.base.encrypt; + +/** + * 签名算法类型 + * 参考Hutool + * see: https://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#Signature + */ +public enum SignAlgorithm { + // The RSA signature algorithm + NONEwithRSA("NONEwithRSA"), + + // The MD2/MD5 with RSA Encryption signature algorithm + MD2withRSA("MD2withRSA"), + MD5withRSA("MD5withRSA"), + + // The signature algorithm with SHA-* and the RSA + SHA1withRSA("SHA1withRSA"), + SHA256withRSA("SHA256withRSA"), + SHA384withRSA("SHA384withRSA"), + SHA512withRSA("SHA512withRSA"), + + // The Digital Signature Algorithm + NONEwithDSA("NONEwithDSA"), + // The DSA with SHA-1 signature algorithm + SHA1withDSA("SHA1withDSA"), + + // The ECDSA signature algorithms + NONEwithECDSA("NONEwithECDSA"), + SHA1withECDSA("SHA1withECDSA"), + SHA256withECDSA("SHA256withECDSA"), + SHA384withECDSA("SHA384withECDSA"), + SHA512withECDSA("SHA512withECDSA"); + + private String value; + + /** + * 构造 + * + * @param value 算法字符表示,区分大小写 + */ + private SignAlgorithm(String value) { + this.value = value; + } + + /** + * 获取算法字符串表示,区分大小写 + * + * @return 算法字符串表示 + */ + public String getValue() { + return this.value; + } +} From 047a7e24b68a0b93398d696fdbd85be59991bb8d Mon Sep 17 00:00:00 2001 From: maxf <1107047387@qq.com> Date: Fri, 23 Nov 2018 16:46:48 +0800 Subject: [PATCH 08/27] =?UTF-8?q?1.2.3=20RSA=20=E5=8A=A0=E5=AF=86=EF=BC=88?= =?UTF-8?q?=E7=AD=BE=E5=90=8D=EF=BC=89=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- UPDATE.md | 12 ++ pom.xml | 2 +- .../java/com/yexuejc/base/encrypt/RSA.java | 125 ++++++++++++++++-- 3 files changed, 127 insertions(+), 12 deletions(-) diff --git a/UPDATE.md b/UPDATE.md index fbc09a5..dd5e827 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -1,6 +1,18 @@ yexuejc-base 更新记录 ------------------ +#### version :1.2.3 +**time:2018-11-23 16:45:42**
+**branch:** master
+**update:**
+>1. 修复RSA加密(签名)时选择的Base64(encodeBase64URLSafeString、encodeBase64String)区分 +# +#### version :1.2.1 +**time:2018-11-9 15:05:06**
+**branch:** master
+**update:**
+>1. 优化resps +# #### version :1.2.2 **time:2018-11-20 20:20:12**
**branch:** master
diff --git a/pom.xml b/pom.xml index 9115823..122678c 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.yexuejc.base yexuejc-base - 1.2.2 + 1.2.3 ${project.artifactId} diff --git a/src/main/java/com/yexuejc/base/encrypt/RSA.java b/src/main/java/com/yexuejc/base/encrypt/RSA.java index 968d0fa..8df2e9a 100644 --- a/src/main/java/com/yexuejc/base/encrypt/RSA.java +++ b/src/main/java/com/yexuejc/base/encrypt/RSA.java @@ -18,6 +18,8 @@ import java.security.spec.X509EncodedKeySpec; import java.util.HashMap; import java.util.Map; +//import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; + /** * RSA加解密 配置模式 * @@ -44,12 +46,51 @@ public class RSA { * 只针对于RSA_ALGORITHM_ECB = "RSA"有效 */ public static boolean isChangeSign = true; + /** + * 是否使用 Base64URL 方式加密 默认正常加密 + *
+     *     关于 Base64URL 和正常加密的区别:Base64URL会把 '+', '/' 转换成 '-', '_' 来防止请求时url上的转义
+     *     private static final byte[] STANDARD_ENCODE_TABLE = {
+     *             'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
+     *             'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
+     *             'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
+     *             'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
+     *             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
+     *     };
+     *      private static final byte[] URL_SAFE_ENCODE_TABLE = {
+     *             'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
+     *             'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
+     *             'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
+     *             'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
+     *             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'
+     *     };
+     * 
+ */ + public static boolean encodeBase64URLSafe = false; /** * 签名算法 */ public static SignAlgorithm signAlgorithm = SignAlgorithm.SHA1withRSA; + /** + * 生成密钥对 + * + * @param keySize 生成长度 + * @param base64URLSafe 是否生成 base64URL 格式的密钥:默认false + * @return + */ + public static Map initKeys(int keySize, boolean base64URLSafe) { + encodeBase64URLSafe = base64URLSafe; + return initKeys(keySize); + } + + /** + * 生成密钥对 + * + * @param keySize 生成长度 + * @return + */ public static Map initKeys(int keySize) { //为RSA算法创建一个KeyPairGenerator对象 KeyPairGenerator kpg; @@ -65,10 +106,17 @@ public class RSA { KeyPair keyPair = kpg.generateKeyPair(); //得到公钥 Key publicKey = keyPair.getPublic(); - String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded()); //得到私钥 Key privateKey = keyPair.getPrivate(); - String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded()); + String privateKeyStr = null; + String publicKeyStr = null; + if (encodeBase64URLSafe) { + publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded()); + privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded()); + } else { + publicKeyStr = Base64.encodeBase64String(publicKey.getEncoded()); + privateKeyStr = Base64.encodeBase64String(privateKey.getEncoded()); + } Map keyPairMap = new HashMap(); keyPairMap.put("publicKey", publicKeyStr); keyPairMap.put("privateKey", privateKeyStr); @@ -83,7 +131,7 @@ public class RSA { * @param publicKey 密钥字符串(经过base64编码) * @throws Exception */ - public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException{ + public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException { //通过X509编码的Key指令获得公钥对象 KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey)); @@ -108,15 +156,32 @@ public class RSA { /** * 公钥加密 * - * @param data - * @param publicKey + * @param data 加密原串数据 + * @param publicKey 公钥 + * @param base64URLSafe 是否生成 base64URL 格式的密钥:默认false + * @return + */ + public static String publicEncrypt(String data, RSAPublicKey publicKey, boolean base64URLSafe) { + encodeBase64URLSafe = base64URLSafe; + return publicEncrypt(data, publicKey); + } + + /** + * 公钥加密 + * + * @param data 加密原串数据 + * @param publicKey 公钥 * @return */ public static String publicEncrypt(String data, RSAPublicKey publicKey) { try { Cipher cipher = getCipher(); cipher.init(Cipher.ENCRYPT_MODE, publicKey); - return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength())); + if (encodeBase64URLSafe) { + return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength())); + } else { + return Base64.encodeBase64String(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength())); + } } catch (Exception e) { throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e); } @@ -143,16 +208,32 @@ public class RSA { /** * 私钥加密 * - * @param data - * @param privateKey + * @param data 加密原串数据 + * @param privateKey 公钥 + * @param base64URLSafe 是否生成 base64URL 格式的密钥:默认false * @return */ + public static String privateEncrypt(String data, RSAPrivateKey privateKey, boolean base64URLSafe) { + encodeBase64URLSafe = base64URLSafe; + return privateEncrypt(data, privateKey); + } + /** + * 私钥加密 + * + * @param data 加密原串数据 + * @param privateKey 公钥 + * @return + */ public static String privateEncrypt(String data, RSAPrivateKey privateKey) { try { Cipher cipher = getCipher(); cipher.init(Cipher.ENCRYPT_MODE, privateKey); - return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength())); + if (encodeBase64URLSafe) { + return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength())); + } else { + return Base64.encodeBase64String(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength())); + } } catch (Exception e) { throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e); } @@ -227,6 +308,25 @@ public class RSA { private static Signature signature; + + /** + * /** + * 私钥签名:默认算法SHA1withRSA + *

+ * 签名算法 {@link SignAlgorithm} + *

+ * + * @param plaintext 签名字符串 + * @param privateKey 签名私钥 + * @param base64URLSafe 是否生成 base64URL 格式的密钥:默认false + * @return + * @throws NoSuchAlgorithmException + */ + public static String sign(String plaintext, RSAPrivateKey privateKey, boolean base64URLSafe) throws NoSuchAlgorithmException { + encodeBase64URLSafe = base64URLSafe; + return sign(plaintext, privateKey); + } + /** * 私钥签名:默认算法SHA1withRSA *

@@ -250,8 +350,11 @@ public class RSA { e.printStackTrace(); throw new RuntimeException("签名字符串[" + plaintext + "]的数据时发生异常", e); } - - signBase64Str = Base64.encodeBase64String(signature.sign()); + if (encodeBase64URLSafe) { + signBase64Str = Base64.encodeBase64URLSafeString(signature.sign()); + } else { + signBase64Str = Base64.encodeBase64String(signature.sign()); + } return signBase64Str; } catch (InvalidKeyException var6) { var6.printStackTrace(); From 616eefc06739c73539f886460ed181e37f023516 Mon Sep 17 00:00:00 2001 From: maxf <1107047387@qq.com> Date: Fri, 23 Nov 2018 16:48:42 +0800 Subject: [PATCH 09/27] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index bc39205..3bdd1c7 100644 --- a/README.md +++ b/README.md @@ -13,10 +13,11 @@ ``` >4. 1.1.9升级JWT为单例类 +>5. 1.2.3修复RSA加密(签名)Base64Url 问题,如需使用RSA请使用1.2.3+ ### 使用 ->yexuejc.base.version=1.2.0 +>yexuejc.base.version=1.2.3 pom.xml ``` From c85efeb4a67f3dd50516609ed2ab3de984de068b Mon Sep 17 00:00:00 2001 From: maxf <1107047387@qq.com> Date: Mon, 26 Nov 2018 18:13:05 +0800 Subject: [PATCH 10/27] =?UTF-8?q?1.=E4=BC=98=E5=8C=96=E4=BB=A3=E7=A0=81=20?= =?UTF-8?q?2.fileutil=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/yexuejc/base/encrypt/RSA.java | 10 +- .../java/com/yexuejc/base/encrypt/RSA2.java | 11 +- .../yexuejc/base/encrypt/SignAlgorithm.java | 8 +- .../com/yexuejc/base/util/AlgorithmUtil.java | 12 +- .../com/yexuejc/base/util/DateTimeUtil.java | 32 +-- .../yexuejc/base/util/ExcelImportUtil.java | 3 +- .../java/com/yexuejc/base/util/FileUtil.java | 262 +++++++++++++++++- .../yexuejc/base/util/IdcardValidator.java | 10 +- .../java/com/yexuejc/base/util/ImgUtil.java | 12 +- .../yexuejc/base/util/MapRemoveNullUtil.java | 20 +- .../java/com/yexuejc/base/util/StrUtil.java | 20 +- .../java/com/yexuejc/base/util/SysUtil.java | 5 +- .../java/com/yexuejc/base/util/ThreeDES.java | 8 +- 13 files changed, 343 insertions(+), 70 deletions(-) diff --git a/src/main/java/com/yexuejc/base/encrypt/RSA.java b/src/main/java/com/yexuejc/base/encrypt/RSA.java index 8df2e9a..d1f6ee2 100644 --- a/src/main/java/com/yexuejc/base/encrypt/RSA.java +++ b/src/main/java/com/yexuejc/base/encrypt/RSA.java @@ -2,12 +2,12 @@ package com.yexuejc.base.encrypt; import org.apache.commons.codec.binary.Base64; -import org.apache.commons.io.IOUtils; import org.bouncycastle.jce.provider.BouncyCastleProvider; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import java.io.ByteArrayOutputStream; +import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.*; import java.security.interfaces.RSAPrivateKey; @@ -18,7 +18,6 @@ import java.security.spec.X509EncodedKeySpec; import java.util.HashMap; import java.util.Map; -//import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; /** * RSA加解密 配置模式 @@ -117,7 +116,7 @@ public class RSA { publicKeyStr = Base64.encodeBase64String(publicKey.getEncoded()); privateKeyStr = Base64.encodeBase64String(privateKey.getEncoded()); } - Map keyPairMap = new HashMap(); + Map keyPairMap = new HashMap(2); keyPairMap.put("publicKey", publicKeyStr); keyPairMap.put("privateKey", privateKeyStr); @@ -302,7 +301,10 @@ public class RSA { throw new RuntimeException("加解密阀值为[" + maxBlock + "]的数据时发生异常", e); } byte[] resultDatas = out.toByteArray(); - IOUtils.closeQuietly(out); + try { + out.close(); + } catch (IOException e) { + } return resultDatas; } diff --git a/src/main/java/com/yexuejc/base/encrypt/RSA2.java b/src/main/java/com/yexuejc/base/encrypt/RSA2.java index 508dbdd..17adc07 100644 --- a/src/main/java/com/yexuejc/base/encrypt/RSA2.java +++ b/src/main/java/com/yexuejc/base/encrypt/RSA2.java @@ -16,6 +16,7 @@ import java.security.interfaces.RSAPublicKey; /** * RSA加解密 证书模式 * 依赖 {@link RSA} + * * @ClassName: RSA2 * @Description: * @author: maxf @@ -55,7 +56,15 @@ public class RSA2 { */ public static RSAPrivateKey getPrivateKey(String filepath, String alias, String password) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException { KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(new FileInputStream(filepath), password.toCharArray()); + FileInputStream fileInputStream = null; + try { + fileInputStream = new FileInputStream(filepath); + ks.load(fileInputStream, password.toCharArray()); + } finally { + if (fileInputStream != null) { + fileInputStream.close(); + } + } return (RSAPrivateKey) ks.getKey(alias, password.toCharArray()); } diff --git a/src/main/java/com/yexuejc/base/encrypt/SignAlgorithm.java b/src/main/java/com/yexuejc/base/encrypt/SignAlgorithm.java index efbda90..139f86e 100644 --- a/src/main/java/com/yexuejc/base/encrypt/SignAlgorithm.java +++ b/src/main/java/com/yexuejc/base/encrypt/SignAlgorithm.java @@ -2,8 +2,12 @@ package com.yexuejc.base.encrypt; /** * 签名算法类型 - * 参考Hutool - * see: https://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#Signature + * + * @author maxf + * @ClassName SignAlgorithm + * @Description 签名算法类型 参考Hutool https://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#Signature + * @date 2018/11/26 10:25 + * @see 1.0 */ public enum SignAlgorithm { // The RSA signature algorithm diff --git a/src/main/java/com/yexuejc/base/util/AlgorithmUtil.java b/src/main/java/com/yexuejc/base/util/AlgorithmUtil.java index 206021f..faef09f 100644 --- a/src/main/java/com/yexuejc/base/util/AlgorithmUtil.java +++ b/src/main/java/com/yexuejc/base/util/AlgorithmUtil.java @@ -77,7 +77,7 @@ public class AlgorithmUtil { * @throw */ public static int x36ConvertTo10(String pStr) { - if (pStr == "") { + if (StrUtil.isEmpty(pStr)) { return 0; } // 目标十进制数初始化为0 @@ -117,12 +117,12 @@ public class AlgorithmUtil { if (hexString == null || hexString.length() % 2 != 0) { return null; } - String bString = "", tmp; + StringBuffer buf = new StringBuffer(); for (int i = 0; i < hexString.length(); i++) { - tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16)); - bString += tmp.substring(tmp.length() - 4); + String tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16)); + buf.append(tmp.substring(tmp.length() - 4)); } - return bString; + return buf.toString(); } /** @@ -132,7 +132,7 @@ public class AlgorithmUtil { * @return */ public static byte[] hexStringToBytes(String hexString) { - if (hexString == null || hexString.equals("")) { + if (hexString == null || "".equals(hexString)) { return null; } hexString = hexString.toUpperCase(); diff --git a/src/main/java/com/yexuejc/base/util/DateTimeUtil.java b/src/main/java/com/yexuejc/base/util/DateTimeUtil.java index 0bf9db1..50533e5 100644 --- a/src/main/java/com/yexuejc/base/util/DateTimeUtil.java +++ b/src/main/java/com/yexuejc/base/util/DateTimeUtil.java @@ -109,9 +109,9 @@ public class DateTimeUtil { * @return */ public static LocalDate getWeek4First(LocalDate date) { - TemporalAdjuster FIRST_OF_WEEK = - TemporalAdjusters.ofDateAdjuster(localDate -> localDate.minusDays(localDate.getDayOfWeek().getValue() - DayOfWeek.MONDAY.getValue())); - return date.with(FIRST_OF_WEEK); + TemporalAdjuster firstOfWeek = TemporalAdjusters.ofDateAdjuster(localDate -> + localDate.minusDays(localDate.getDayOfWeek().getValue() - DayOfWeek.MONDAY.getValue())); + return date.with(firstOfWeek); } /** @@ -130,9 +130,9 @@ public class DateTimeUtil { * @return */ public static LocalDate getWeek4Last(LocalDate date) { - TemporalAdjuster LAST_OF_WEEK = - TemporalAdjusters.ofDateAdjuster(localDate -> localDate.plusDays(DayOfWeek.SUNDAY.getValue() - localDate.getDayOfWeek().getValue())); - return date.with(LAST_OF_WEEK); + TemporalAdjuster lastOfWeek = TemporalAdjusters.ofDateAdjuster(localDate -> + localDate.plusDays(DayOfWeek.SUNDAY.getValue() - localDate.getDayOfWeek().getValue())); + return date.with(lastOfWeek); } /** @@ -273,22 +273,22 @@ public class DateTimeUtil { return df.format(dateTime); } - public static void main(String[] args) { -// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); -// System.out.println(df.format(zonedDateTime2Date(ZonedDateTime.now()))); -// System.out.println(df2.format(date2ZonedDateTime(new Date()))); + /** public static void main(String[] args) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + System.out.println(df.format(zonedDateTime2Date(ZonedDateTime.now()))); + System.out.println(df2.format(date2ZonedDateTime(new Date()))); -// System.out.println(getWeek4First()); + System.out.println(getWeek4First()); System.out.println(format(getWeek4First(LocalDate.parse("2018-02-10")).atTime(LocalTime.MIN))); System.out.println(format(getWeek4Last(LocalDate.parse("2018-02-10")).atTime(LocalTime.MAX))); -// System.out.println(format(getMonth4First().atTime(LocalTime.MIN))); -// System.out.println(format(getMonth4Last().atTime(LocalTime.MAX))); + System.out.println(format(getMonth4First().atTime(LocalTime.MIN))); + System.out.println(format(getMonth4Last().atTime(LocalTime.MAX))); -// System.out.println(format(getYear4First().atTime(LocalTime.MIN))); -// System.out.println(format(getYear4Last().atTime(LocalTime.MAX))); + System.out.println(format(getYear4First().atTime(LocalTime.MIN))); + System.out.println(format(getYear4Last().atTime(LocalTime.MAX))); - } + }*/ } diff --git a/src/main/java/com/yexuejc/base/util/ExcelImportUtil.java b/src/main/java/com/yexuejc/base/util/ExcelImportUtil.java index 92ef717..bf4e6af 100644 --- a/src/main/java/com/yexuejc/base/util/ExcelImportUtil.java +++ b/src/main/java/com/yexuejc/base/util/ExcelImportUtil.java @@ -41,7 +41,8 @@ public class ExcelImportUtil { * @return */ public static boolean validateExcel(String filePath) { - if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) { + boolean b = filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath)); + if (b) { return false; } return true; diff --git a/src/main/java/com/yexuejc/base/util/FileUtil.java b/src/main/java/com/yexuejc/base/util/FileUtil.java index ed99e4b..c8419a1 100644 --- a/src/main/java/com/yexuejc/base/util/FileUtil.java +++ b/src/main/java/com/yexuejc/base/util/FileUtil.java @@ -1,9 +1,21 @@ package com.yexuejc.base.util; +import sun.misc.BASE64Encoder; + import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.IOException; +import java.math.BigInteger; +import java.nio.MappedByteBuffer; +import java.nio.channels.FileChannel; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.zip.CRC32; /** + * 文件工具类 + * * @author maxf:yexue * @className FileUtil * @description 工具类 @@ -16,14 +28,31 @@ public class FileUtil { private static final String TYPE_TAR_GZ = ".tar.gz"; private static final String TAR_GZ = "tar.gz"; - public static String getFileType(String fileName) { - if (fileName.lastIndexOf(TYPE_TAR_GZ) > 0) { - return TAR_GZ; + /** + * 获取文件类型:不适合所有 + *

+ * 根据文件名称截取.后的文件格式 + *

+ * + * @param fileName + * @return + */ + public static String getFileType(String fileName) throws FileNotFoundException { + try { + if (fileName.lastIndexOf(TYPE_TAR_GZ) > 0) { + return TAR_GZ; + } + return fileName.substring(fileName.lastIndexOf(".") + 1); + } catch (Exception e) { + throw new FileNotFoundException("文件类型未能解析"); } - return fileName.substring(fileName.lastIndexOf(".") + 1); } - // 判断文件是否存在 + /** + * 判断文件是否存在 + * + * @param file + */ public static void judeFileExists(File file) { if (file.exists()) { @@ -49,9 +78,10 @@ public class FileUtil { * 4、File类的createTempFile方法创建临时文件,可以制定临时文件的文件名前缀、后缀及文件所在的目录,如果不指定目录,则存放在系统的临时文件夹下。 * 5、除mkdirs方法外,以上方法在创建文件和目录时,必须保证目标文件不存在,而且父目录存在,否则会创建失败 * + * + * @return 创建成功、失败 */ - public static void judeDirExists(File file) { - + public static boolean judeDirExists(File file) { if (file.exists()) { if (file.isDirectory()) { System.out.println("dir exists"); @@ -60,9 +90,223 @@ public class FileUtil { } } else { System.out.println("dir not exists, create it ..."); - file.mkdirs(); + return file.mkdirs(); } - + return false; } + /** + * 获取文件sha1 + * + * @param file + * @return + */ + public static String sha1(File file) { + FileInputStream in = null; + try { + in = new FileInputStream(file); + MessageDigest digest = MessageDigest.getInstance("SHA-1"); + byte[] buffer = new byte[1024 * 1024 * 10]; + + int len = 0; + while ((len = in.read(buffer)) > 0) { + digest.update(buffer, 0, len); + } + String sha1 = new BigInteger(1, digest.digest()).toString(16); + int length = 40 - sha1.length(); + if (length > 0) { + for (int i = 0; i < length; i++) { + sha1 = "0" + sha1; + } + } + return sha1; + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (in != null) { + in.close(); + } + } catch (IOException e) { + } + } + return null; + } + + + /*** + * 计算SHA1码 + * + * @return String 适用于上G大的文件 + * @throws NoSuchAlgorithmException + * */ + public static String sha1ByBigFile(File file) { + MessageDigest messagedigest = null; + try { + messagedigest = MessageDigest.getInstance("SHA-1"); + FileInputStream in = new FileInputStream(file); + FileChannel ch = in.getChannel(); + MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length()); + messagedigest.update(byteBuffer); + return StrUtil.toHex(messagedigest.digest()); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + /** + * 文件md5 + * + * @param file + * @return + */ + public static String md5(File file) { + FileInputStream in = null; + try { + in = new FileInputStream(file); + MessageDigest digest = MessageDigest.getInstance("MD5"); + byte[] buffer = new byte[1024 * 1024 * 10]; + + int len = 0; + while ((len = in.read(buffer)) > 0) { + digest.update(buffer, 0, len); + } + String md5 = new BigInteger(1, digest.digest()).toString(16); + int length = 32 - md5.length(); + if (length > 0) { + for (int i = 0; i < length; i++) { + md5 = "0" + md5; + } + } + return md5; + } catch (IOException e) { + System.out.println(e); + } catch (NoSuchAlgorithmException e) { + System.out.println(e); + } finally { + try { + if (in != null) { + in.close(); + } + } catch (IOException e) { + System.out.println(e); + } + } + return null; + } + + /** + * 对一个文件获取md5值 + * + * @return md5串 + * @throws NoSuchAlgorithmException + */ + public static String md5ByBigFile(File file) { + + MessageDigest messagedigest = null; + try { + messagedigest = MessageDigest.getInstance("MD5"); + FileInputStream in = new FileInputStream(file); + FileChannel ch = in.getChannel(); + MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, + file.length()); + messagedigest.update(byteBuffer); + return StrUtil.toHex(messagedigest.digest()); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + /** + * 获取文件CRC32码 + * + * @return String + */ + public static String crc32(File file) { + CRC32 crc32 = new CRC32(); + // MessageDigest.get + FileInputStream fileInputStream = null; + try { + fileInputStream = new FileInputStream(file); + byte[] buffer = new byte[8192]; + int length; + while ((length = fileInputStream.read(buffer)) != -1) { + crc32.update(buffer, 0, length); + } + return crc32.getValue() + ""; + } catch (FileNotFoundException e) { + e.printStackTrace(); + return null; + } catch (IOException e) { + e.printStackTrace(); + return null; + } finally { + try { + if (fileInputStream != null) { + fileInputStream.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + /** + * 获取文件base64 + * + * @param file + * @return + */ + public static String base64(File file) { + FileInputStream fileInputStream = null; + byte[] data = null; + // 读取图片字节数组 + try { + fileInputStream = new FileInputStream(file); + data = new byte[fileInputStream.available()]; + fileInputStream.read(data); + fileInputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + // 对字节数组Base64编码 + BASE64Encoder encoder = new BASE64Encoder(); + return encoder.encode(data); + } + + + /* public static void main(String[] args) { + + String s1 = base64(new File("C:\\Users\\Administrator\\Desktop\\a.html")); + System.out.println(s1); + + String s = sha1(new File("C:\\Users\\Administrator\\Desktop\\a.html")); + String s2 = sha1ByBigFile(new File("C:\\Users\\Administrator\\Desktop\\a.html")); + System.out.println(s); + System.out.println(s2); + + + String md5 = md5(new File("C:\\Users\\Administrator\\Desktop\\a.html")); + String md52 = md5ByBigFile(new File("C:\\Users\\Administrator\\Desktop\\a.html")); + System.out.println(md5); + System.out.println(md52); + + + String crc32 = crc32(new File("C:\\Users\\Administrator\\Desktop\\a.html")); + System.out.println(crc32); + }*/ } diff --git a/src/main/java/com/yexuejc/base/util/IdcardValidator.java b/src/main/java/com/yexuejc/base/util/IdcardValidator.java index a13a6eb..816ec9b 100644 --- a/src/main/java/com/yexuejc/base/util/IdcardValidator.java +++ b/src/main/java/com/yexuejc/base/util/IdcardValidator.java @@ -47,7 +47,7 @@ public class IdcardValidator { /** * 每位加权因子 */ - private static int power[] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}; + private static int[] power = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}; /** * 验证所有的身份证的合法性 @@ -167,9 +167,9 @@ public class IdcardValidator { // 获取第18位 String idcard18Code = idcard.substring(17, 18); - char c[] = idcard17.toCharArray(); + char[] c = idcard17.toCharArray(); - int bit[] = converCharToInt(c); + int[] bit = converCharToInt(c); int sum17 = 0; @@ -290,11 +290,11 @@ public class IdcardValidator { String idcard17 = idcard.substring(0, 6) + year + idcard.substring(8); - char c[] = idcard17.toCharArray(); + char[] c = idcard17.toCharArray(); String checkCode = ""; // 将字符数组转为整型数组 - int bit[] = converCharToInt(c); + int[] bit = converCharToInt(c); int sum17 = 0; sum17 = getPowerSum(bit); diff --git a/src/main/java/com/yexuejc/base/util/ImgUtil.java b/src/main/java/com/yexuejc/base/util/ImgUtil.java index 67a2b75..7aa3dbc 100644 --- a/src/main/java/com/yexuejc/base/util/ImgUtil.java +++ b/src/main/java/com/yexuejc/base/util/ImgUtil.java @@ -310,8 +310,16 @@ public class ImgUtil { * @throws IOException */ public static byte[] byteImage(String imgUrl) throws IOException { - FileInputStream fis = new FileInputStream(imgUrl); - byte[] rs = new byte[fis.available()]; + byte[] rs; + FileInputStream fis = null; + try { + fis = new FileInputStream(imgUrl); + rs = new byte[fis.available()]; + } finally { + if (fis != null) { + fis.close(); + } + } return rs; } diff --git a/src/main/java/com/yexuejc/base/util/MapRemoveNullUtil.java b/src/main/java/com/yexuejc/base/util/MapRemoveNullUtil.java index 0062329..f71bf32 100644 --- a/src/main/java/com/yexuejc/base/util/MapRemoveNullUtil.java +++ b/src/main/java/com/yexuejc/base/util/MapRemoveNullUtil.java @@ -3,7 +3,6 @@ package com.yexuejc.base.util; import java.util.Collection; import java.util.Iterator; import java.util.Map; -import java.util.Set; /** * map相关工具 @@ -36,10 +35,11 @@ public class MapRemoveNullUtil { * @return */ public static Map removeNullKey(Map map) { - Set set = map.keySet(); - for (Iterator iterator = set.iterator(); iterator.hasNext(); ) { - Object obj = (Object) iterator.next(); - remove(obj, iterator); + for (Iterator it = map.entrySet().iterator(); it.hasNext(); ) { + Map.Entry item = (Map.Entry) it.next(); + if (StrUtil.isEmpty(item.getKey())) { + it.remove(); + } } return map; } @@ -51,11 +51,11 @@ public class MapRemoveNullUtil { * @return */ public static Map removeNullValue(Map map) { - Set set = map.keySet(); - for (Iterator iterator = set.iterator(); iterator.hasNext(); ) { - Object obj = (Object) iterator.next(); - Object value = (Object) map.get(obj); - remove(value, iterator); + for (Iterator it = map.entrySet().iterator(); it.hasNext(); ) { + Map.Entry item = (Map.Entry) it.next(); + if (StrUtil.isEmpty(item.getValue())) { + it.remove(); + } } return map; } diff --git a/src/main/java/com/yexuejc/base/util/StrUtil.java b/src/main/java/com/yexuejc/base/util/StrUtil.java index 7766a02..9664005 100644 --- a/src/main/java/com/yexuejc/base/util/StrUtil.java +++ b/src/main/java/com/yexuejc/base/util/StrUtil.java @@ -126,7 +126,7 @@ public final class StrUtil { return null; } - Map map = new HashMap(); + Map map = new HashMap(16); String[] kv = null; for (String entry : entrys) { if (isEmpty(entry)) { @@ -151,7 +151,7 @@ public final class StrUtil { * @param buf 初始字节数组 * @return 转换后字符串 */ - public static String toHex(byte buf[]) { + public static String toHex(byte[] buf) { StringBuffer strbuf = new StringBuffer(buf.length * 2); int i; for (i = 0; i < buf.length; i++) { @@ -181,7 +181,7 @@ public final class StrUtil { return null; } md.update(str.getBytes()); - byte tmp[] = md.digest(); + byte[] tmp = md.digest(); return toHex(tmp); } @@ -215,7 +215,7 @@ public final class StrUtil { return null; } messageDigest.update(str.getBytes()); - byte tmp[] = messageDigest.digest(); + byte[] tmp = messageDigest.digest(); return toHex(tmp); } @@ -241,8 +241,9 @@ public final class StrUtil { * @param str * @return */ + private static Pattern pattern = Pattern.compile("[0-9]*"); + public static boolean isNumeric(String str) { - Pattern pattern = Pattern.compile("[0-9]*"); Matcher isNum = pattern.matcher(str); if (!isNum.matches()) { return false; @@ -262,16 +263,17 @@ public final class StrUtil { } StringBuilder coded = new StringBuilder(); + Random random = new Random(); for (int i = 0; i < 13; i++) { - coded.append(HEX_CHAR[(int) (Math.random() * 15L) + 1]); + coded.append(HEX_CHAR[random.nextInt(16)]); } coded.append(id.substring(0, 11)); for (int i = 0; i < 7; i++) { - coded.append(HEX_CHAR[(int) (Math.random() * 15L) + 1]); + coded.append(HEX_CHAR[random.nextInt(16)]); } coded.append(id.substring(11)); for (int i = 0; i < 12; i++) { - coded.append(HEX_CHAR[(int) (Math.random() * 15L) + 1]); + coded.append(HEX_CHAR[random.nextInt(16)]); } return coded.toString(); @@ -338,7 +340,7 @@ public final class StrUtil { * @return */ public static Map mapSort(Map sortedParams) { - Map map = new HashMap<>(); + Map map = new HashMap<>(16); List keys = new ArrayList<>(sortedParams.keySet()); Collections.sort(keys); int index = 0; diff --git a/src/main/java/com/yexuejc/base/util/SysUtil.java b/src/main/java/com/yexuejc/base/util/SysUtil.java index 5094146..4b0758f 100644 --- a/src/main/java/com/yexuejc/base/util/SysUtil.java +++ b/src/main/java/com/yexuejc/base/util/SysUtil.java @@ -71,9 +71,12 @@ public class SysUtil { } /** - * 异步执行代码块 + * 异步执行接口 */ public interface ThreadRun { + /** + * 执行代码块 + */ void execute(); } } diff --git a/src/main/java/com/yexuejc/base/util/ThreeDES.java b/src/main/java/com/yexuejc/base/util/ThreeDES.java index 28e14e1..ba8e630 100644 --- a/src/main/java/com/yexuejc/base/util/ThreeDES.java +++ b/src/main/java/com/yexuejc/base/util/ThreeDES.java @@ -23,8 +23,8 @@ public class ThreeDES { private ThreeDES() { } - private static final String IV = "1234567-"; - private final static String encoding = "utf-8"; + public static String IV = "1234567-"; + public static String ENCODING = "utf-8"; /** * DESCBC加密 @@ -46,7 +46,7 @@ public class ThreeDES { Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding"); IvParameterSpec ips = new IvParameterSpec(IV.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, deskey, ips); - byte[] encryptData = cipher.doFinal(src.getBytes(encoding)); + byte[] encryptData = cipher.doFinal(src.getBytes(ENCODING)); return Base64.encodeBase64URLSafeString(encryptData); } @@ -72,7 +72,7 @@ public class ThreeDES { byte[] decryptData = cipher.doFinal(Base64.decodeBase64(src)); - return new String(decryptData, encoding); + return new String(decryptData, ENCODING); } /** From a9f8c7aca3875d22c62c42cf8b00c8a599a640a5 Mon Sep 17 00:00:00 2001 From: maxf <1107047387@qq.com> Date: Tue, 27 Nov 2018 14:45:04 +0800 Subject: [PATCH 11/27] =?UTF-8?q?=E4=BC=98=E5=8C=96fileUtil?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/yexuejc/base/util/FileUtil.java | 99 ++++++++++++++++--- 1 file changed, 88 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/yexuejc/base/util/FileUtil.java b/src/main/java/com/yexuejc/base/util/FileUtil.java index c8419a1..e23ae2f 100644 --- a/src/main/java/com/yexuejc/base/util/FileUtil.java +++ b/src/main/java/com/yexuejc/base/util/FileUtil.java @@ -11,6 +11,7 @@ import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.util.logging.Logger; import java.util.zip.CRC32; /** @@ -22,6 +23,8 @@ import java.util.zip.CRC32; * @time 2017年11月3日 下午3:12:49 */ public class FileUtil { + static Logger logger = Logger.getLogger(FileUtil.class.getName()); + private FileUtil() { } @@ -37,15 +40,16 @@ public class FileUtil { * @param fileName * @return */ - public static String getFileType(String fileName) throws FileNotFoundException { + public static String getFileType(String fileName) { try { if (fileName.lastIndexOf(TYPE_TAR_GZ) > 0) { return TAR_GZ; } return fileName.substring(fileName.lastIndexOf(".") + 1); } catch (Exception e) { - throw new FileNotFoundException("文件类型未能解析"); + logger.severe("file doesn't exist or is not a file"); } + return null; } /** @@ -56,12 +60,13 @@ public class FileUtil { public static void judeFileExists(File file) { if (file.exists()) { - System.out.println("file exists"); + logger.severe("file exists"); } else { - System.out.println("file not exists, create it ..."); + logger.info("file not exists, create it ..."); try { file.createNewFile(); } catch (IOException e) { + logger.severe("file create fail"); e.printStackTrace(); } } @@ -84,12 +89,12 @@ public class FileUtil { public static boolean judeDirExists(File file) { if (file.exists()) { if (file.isDirectory()) { - System.out.println("dir exists"); + logger.severe("dir exists"); } else { - System.out.println("the same name file exists, can not create dir"); + logger.severe("the same name file exists, can not create dir"); } } else { - System.out.println("dir not exists, create it ..."); + logger.info("dir not exists, create it ..."); return file.mkdirs(); } return false; @@ -121,10 +126,13 @@ public class FileUtil { } return sha1; } catch (NoSuchAlgorithmException e) { + logger.severe("system algorithm error."); e.printStackTrace(); } catch (FileNotFoundException e) { + logger.severe("file doesn't exist or is not a file"); e.printStackTrace(); } catch (IOException e) { + logger.severe("The operation file is an IO exception."); e.printStackTrace(); } finally { try { @@ -132,6 +140,7 @@ public class FileUtil { in.close(); } } catch (IOException e) { + logger.severe("close FileInputStream IO exception."); } } return null; @@ -154,10 +163,13 @@ public class FileUtil { messagedigest.update(byteBuffer); return StrUtil.toHex(messagedigest.digest()); } catch (NoSuchAlgorithmException e) { + logger.severe("system algorithm error."); e.printStackTrace(); } catch (FileNotFoundException e) { + logger.severe("file doesn't exist or is not a file"); e.printStackTrace(); } catch (IOException e) { + logger.severe("The operation file is an IO exception."); e.printStackTrace(); } return null; @@ -189,16 +201,16 @@ public class FileUtil { } return md5; } catch (IOException e) { - System.out.println(e); + logger.severe("The operation file is an IO exception."); } catch (NoSuchAlgorithmException e) { - System.out.println(e); + logger.severe("system algorithm error."); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { - System.out.println(e); + logger.severe("close FileInputStream IO exception."); } } return null; @@ -222,10 +234,13 @@ public class FileUtil { messagedigest.update(byteBuffer); return StrUtil.toHex(messagedigest.digest()); } catch (NoSuchAlgorithmException e) { + logger.severe("system algorithm error."); e.printStackTrace(); } catch (FileNotFoundException e) { + logger.severe("file doesn't exist or is not a file"); e.printStackTrace(); } catch (IOException e) { + logger.severe("The operation file is an IO exception."); e.printStackTrace(); } return null; @@ -249,9 +264,11 @@ public class FileUtil { } return crc32.getValue() + ""; } catch (FileNotFoundException e) { + logger.severe("file doesn't exist or is not a file"); e.printStackTrace(); return null; } catch (IOException e) { + logger.severe("The operation file is an IO exception."); e.printStackTrace(); return null; } finally { @@ -260,6 +277,7 @@ public class FileUtil { fileInputStream.close(); } } catch (IOException e) { + logger.severe("close FileInputStream IO exception."); e.printStackTrace(); } } @@ -281,6 +299,7 @@ public class FileUtil { fileInputStream.read(data); fileInputStream.close(); } catch (IOException e) { + logger.severe("The operation file is an IO exception."); e.printStackTrace(); } // 对字节数组Base64编码 @@ -288,8 +307,66 @@ public class FileUtil { return encoder.encode(data); } + /** + * 获取文件大小 :直接返回大小 + * + * @param f + * @return f.length() + */ + public static long size(File f) { + if (f.exists() && f.isFile()) { + return f.length(); + } else { + logger.info("file doesn't exist or is not a file"); + } + return 0; + } - /* public static void main(String[] args) { + /** + * 获取文件大小 : 用流的方式获取 + * + * @param f + * @return + */ + public static long size4Stream(File f) { + FileChannel fc = null; + try { + if (f.exists() && f.isFile()) { + FileInputStream fis = new FileInputStream(f); + fc = fis.getChannel(); + return fc.size(); + } else { + logger.info("file doesn't exist or is not a file"); + } + } catch (FileNotFoundException e) { + logger.severe("file doesn't exist or is not a file"); + } catch (IOException e) { + logger.severe("The operation file is an IO exception."); + } finally { + if (null != fc) { + try { + fc.close(); + } catch (IOException e) { + logger.severe("close FileInputStream IO exception."); + } + } + } + return 0; + } + + /*public static void main(String[] args) { + long size = FileUtil.size(new File("E:\\OS\\deepin-15.6-amd64\\DeepinCloudPrintServerInstaller_1.0.0.1.exe")); + System.out.println(size); + System.out.println(1024 * 1024 * 5); + if (size > 1024 * 1024 * 5) { + System.out.println("文件最大5M"); + return; + } + + long s1 = fileSize(new File("E:\\OS\\cn_windows_10_consumer_editions_version_1803_updated_march_2018_x64_dvd_12063766.iso")); + System.out.println(s1); + long s2 = fileSize4Stream(new File("E:\\OS\\cn_windows_10_consumer_editions_version_1803_updated_march_2018_x64_dvd_12063766.iso")); + System.out.println(s2); String s1 = base64(new File("C:\\Users\\Administrator\\Desktop\\a.html")); System.out.println(s1); From f2e8bc624b3139c7de3041a2941eb037d3582557 Mon Sep 17 00:00:00 2001 From: maxf <1107047387@qq.com> Date: Tue, 27 Nov 2018 14:46:28 +0800 Subject: [PATCH 12/27] 1.2.4 --- README.md | 2 +- UPDATE.md | 8 ++++++++ pom.xml | 2 +- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3bdd1c7..c6f19de 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ ### 使用 ->yexuejc.base.version=1.2.3 +>yexuejc.base.version=1.2.4 pom.xml ``` diff --git a/UPDATE.md b/UPDATE.md index dd5e827..7b34301 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -1,6 +1,14 @@ yexuejc-base 更新记录 ------------------ +#### version :1.2.4 +**time:2018-11-27 14:46:04**
+**branch:** master
+**update:**
+>1. 工具类的优化 +>2.规范代码 + +# #### version :1.2.3 **time:2018-11-23 16:45:42**
**branch:** master
diff --git a/pom.xml b/pom.xml index 122678c..9e7e257 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.yexuejc.base yexuejc-base - 1.2.3 + 1.2.4 ${project.artifactId} From cb78538c01ac13aa9b4b5b9969cf3ceb4adba73c Mon Sep 17 00:00:00 2001 From: maxf <1107047387@qq.com> Date: Thu, 20 Dec 2018 13:14:01 +0800 Subject: [PATCH 13/27] =?UTF-8?q?1.2.5=20JsonUtil=20=E6=94=AF=E6=8C=81Map?= =?UTF-8?q?=E6=B3=9B=E5=9E=8B=E8=BD=AC=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- UPDATE.md | 7 +++ pom.xml | 2 +- .../java/com/yexuejc/base/util/JsonUtil.java | 59 +++++++++++++++++-- 4 files changed, 62 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index c6f19de..66a87b2 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ ### 使用 ->yexuejc.base.version=1.2.4 +>yexuejc.base.version=1.2.5 pom.xml ``` diff --git a/UPDATE.md b/UPDATE.md index 7b34301..3d98d3b 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -1,6 +1,13 @@ yexuejc-base 更新记录 ------------------ +#### version :1.2.5 +**time:2018-12-20 13:13:23**
+**branch:** master
+**update:**
+>1. 丰富[JsonUtil](src/main/java/com/yexuejc/base/util/JsonUtil.java),支持直接对Map泛型转换 + +# #### version :1.2.4 **time:2018-11-27 14:46:04**
**branch:** master
diff --git a/pom.xml b/pom.xml index 9e7e257..1ac8939 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.yexuejc.base yexuejc-base - 1.2.4 + 1.2.5 ${project.artifactId} diff --git a/src/main/java/com/yexuejc/base/util/JsonUtil.java b/src/main/java/com/yexuejc/base/util/JsonUtil.java index 5ca30e9..479288b 100644 --- a/src/main/java/com/yexuejc/base/util/JsonUtil.java +++ b/src/main/java/com/yexuejc/base/util/JsonUtil.java @@ -5,9 +5,11 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.type.MapType; import java.io.IOException; import java.io.InputStream; +import java.util.Map; /** * json工具类,基于jackson @@ -95,12 +97,13 @@ public class JsonUtil { return pojo; } + /** * Json字符串转换为Java对象 * - * @param json - * @param parametrized - * @param parameterClasses + * @param json 字符串 + * @param parametrized 容器类 + * @param parameterClasses 实际类 * @return */ public static T json2Obj(String json, Class parametrized, Class... parameterClasses) { @@ -116,12 +119,56 @@ public class JsonUtil { return pojo; } + /** + * Json字符串转换为Java-Map对象 + * + * @param json 字符串 + * @param mapClass Map 继承类 + * @param keyClass Key 类 + * @param valueClass Value 类 + * @param + * @return + */ + public static T json2Obj(String json, Class mapClass, Class keyClass, Class valueClass) { + T pojo = null; + MapType mapType = objectMapper.getTypeFactory().constructMapType(mapClass, keyClass, valueClass); + try { + pojo = objectMapper.readValue(json, mapType); + } catch (JsonParseException e) { + } catch (JsonMappingException e) { + } catch (IOException e) { + } + return pojo; + } + + /** + * Json字符串转换为Java-Map对象 + * + * @param json 字符串 + * @param mapClass Map 继承类 + * @param keyType Key 类 + * @param valueType Value 类 + * @param + * @return + */ + public static T json2Obj(String json, Class mapClass, JavaType keyType, JavaType valueType) { + T pojo = null; + MapType mapType = objectMapper.getTypeFactory().constructMapType(mapClass, keyType, valueType); + try { + pojo = objectMapper.readValue(json, mapType); + } catch (JsonParseException e) { + } catch (JsonMappingException e) { + } catch (IOException e) { + } + return pojo; + } + /** * Json字符串转换为Java对象 * - * @param json - * @param parametrized - * @param parameterClasses + * @param json 字符串 + * @param parametrized 容器类 + * @param parameterClasses 实际类 * @return */ public static T json2Obj(InputStream json, Class parametrized, Class... parameterClasses) { From 7368baf553a252b7696f252d877d47daaf07c97e Mon Sep 17 00:00:00 2001 From: maxf <1107047387@qq.com> Date: Thu, 20 Dec 2018 17:03:54 +0800 Subject: [PATCH 14/27] =?UTF-8?q?=E6=94=AF=E6=8C=81=E8=AF=BB=E5=8F=96PKCS1?= =?UTF-8?q?2=E6=A0=BC=E5=BC=8F=E7=9A=84key=EF=BC=88=E7=A7=81=E9=92=A5?= =?UTF-8?q?=EF=BC=89pfx=E6=A0=BC=E5=BC=8F=E7=9A=84=E8=AF=81=E4=B9=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/yexuejc/base/encrypt/RSA2.java | 50 ++++++++++++++++++- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/yexuejc/base/encrypt/RSA2.java b/src/main/java/com/yexuejc/base/encrypt/RSA2.java index 17adc07..20f516b 100644 --- a/src/main/java/com/yexuejc/base/encrypt/RSA2.java +++ b/src/main/java/com/yexuejc/base/encrypt/RSA2.java @@ -1,5 +1,7 @@ package com.yexuejc.base.encrypt; +import com.yexuejc.base.util.StrUtil; + import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; @@ -12,6 +14,7 @@ import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; +import java.util.Enumeration; /** * RSA加解密 证书模式 @@ -42,7 +45,7 @@ public class RSA2 { } /** - * 得到私钥 + * 读取JKS格式的key(私钥)keystore格式 * * @param filepath 私钥路径 * @param alias 证书别名 @@ -55,11 +58,54 @@ public class RSA2 { * @throws UnrecoverableKeyException */ public static RSAPrivateKey getPrivateKey(String filepath, String alias, String password) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException { - KeyStore ks = KeyStore.getInstance("JKS"); + return getPrivateKey(filepath, alias, password, "JKS"); + } + + /** + * 读取PKCS12格式的key(私钥)pfx格式 + * + * @param filepath 私钥路径 + * @param alias 证书别名 可空 + * @param password 证书密码 + * @return + * @throws NoSuchAlgorithmException + * @throws KeyStoreException + * @throws IOException + * @throws CertificateException + * @throws UnrecoverableKeyException + */ + public static RSAPrivateKey getPrivateKeyFromPKCS12(String filepath, String alias, String password) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException { + return getPrivateKey(filepath, alias, password, "PKCS12"); + } + + /** + * 读取key(私钥) + * + * @param filepath 私钥路径 + * @param alias 证书别名 可空 + * @param password 证书密码 + * @param type 证书格式 + * @return + * @throws NoSuchAlgorithmException + * @throws KeyStoreException + * @throws IOException + * @throws CertificateException + * @throws UnrecoverableKeyException + */ + public static RSAPrivateKey getPrivateKey(String filepath, String alias, String password, String type) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException { + KeyStore ks = KeyStore.getInstance(type); FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(filepath); ks.load(fileInputStream, password.toCharArray()); + if (StrUtil.isEmpty(alias)) { + Enumeration aliases = ks.aliases(); + if (aliases != null) { + if (aliases.hasMoreElements()) { + alias = (String) aliases.nextElement(); + } + } + } } finally { if (fileInputStream != null) { fileInputStream.close(); From a250530fd10c704a0b62c0ab6d1268728d7a5d50 Mon Sep 17 00:00:00 2001 From: maxf <1107047387@qq.com> Date: Fri, 21 Dec 2018 14:57:32 +0800 Subject: [PATCH 15/27] =?UTF-8?q?RSA=E9=AA=8C=E7=AD=BE=E6=96=B9=E5=BC=8F?= =?UTF-8?q?=E8=AE=BE=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/yexuejc/base/encrypt/RSA.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/yexuejc/base/encrypt/RSA.java b/src/main/java/com/yexuejc/base/encrypt/RSA.java index d1f6ee2..6fc9010 100644 --- a/src/main/java/com/yexuejc/base/encrypt/RSA.java +++ b/src/main/java/com/yexuejc/base/encrypt/RSA.java @@ -376,7 +376,8 @@ public class RSA { * @return * @throws UnsupportedEncodingException */ - public static boolean verify(String plaintext, String signStr, RSAPublicKey publicKey) throws UnsupportedEncodingException { + public static boolean verify(String plaintext, String signStr, RSAPublicKey publicKey) throws UnsupportedEncodingException, NoSuchAlgorithmException { + signature = Signature.getInstance(signAlgorithm.getValue()); boolean isValid = false; try { signature.initVerify(publicKey); From be42378156e46dfbb8dbc4185594cf762a2c30eb Mon Sep 17 00:00:00 2001 From: maxf <1107047387@qq.com> Date: Fri, 21 Dec 2018 14:58:59 +0800 Subject: [PATCH 16/27] =?UTF-8?q?RSA=E9=AA=8C=E7=AD=BE=E6=96=B9=E5=BC=8F?= =?UTF-8?q?=E8=AE=BE=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- UPDATE.md | 7 +++++++ pom.xml | 2 +- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 66a87b2..045fdf4 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ ### 使用 ->yexuejc.base.version=1.2.5 +>yexuejc.base.version=1.2.6 pom.xml ``` diff --git a/UPDATE.md b/UPDATE.md index 3d98d3b..fbe52df 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -1,6 +1,13 @@ yexuejc-base 更新记录 ------------------ +#### version :1.2.6 +**time:2018-12-21 14:58:49**
+**branch:** master
+**update:**
+>1. RSA 验签增加初始化方法 + +# #### version :1.2.5 **time:2018-12-20 13:13:23**
**branch:** master
diff --git a/pom.xml b/pom.xml index 1ac8939..bdd8b05 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.yexuejc.base yexuejc-base - 1.2.5 + 1.2.6 ${project.artifactId} From 30ce976b27af73c33ce9d7ad253156243d0fd994 Mon Sep 17 00:00:00 2001 From: maxf <1107047387@qq.com> Date: Mon, 24 Dec 2018 15:25:42 +0800 Subject: [PATCH 17/27] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/yexuejc/base/util/ImgUtil.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/main/java/com/yexuejc/base/util/ImgUtil.java b/src/main/java/com/yexuejc/base/util/ImgUtil.java index 7aa3dbc..48ed6ad 100644 --- a/src/main/java/com/yexuejc/base/util/ImgUtil.java +++ b/src/main/java/com/yexuejc/base/util/ImgUtil.java @@ -323,6 +323,33 @@ public class ImgUtil { return rs; } + /** + * base64转文件 + * + * @param decode baseByte + * @param fileName 文件名称(包含路径) + * @return 返回保存地址 + */ + public static String base64ToFile(byte[] decode, String fileName) { + + FileOutputStream out = null; + try { + out = new FileOutputStream(fileName); + out.write(decode); + } catch (IOException ioe) { + ioe.printStackTrace(); + } finally { + try { + if (out != null) { + out.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + return fileName; + } + public static class ImageInfo { /** * 图片大小 From 5b79c1b383f0ef2ce6a0d37afb0bbe33e8890698 Mon Sep 17 00:00:00 2001 From: maxf <1107047387@qq.com> Date: Mon, 24 Dec 2018 15:32:22 +0800 Subject: [PATCH 18/27] =?UTF-8?q?1.2.7=20FileUtil=E5=A2=9E=E5=8A=A0base64?= =?UTF-8?q?=E8=BD=ACFile?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- UPDATE.md | 7 ++++ pom.xml | 2 +- .../java/com/yexuejc/base/util/FileUtil.java | 36 ++++++++++++++++--- .../java/com/yexuejc/base/util/ImgUtil.java | 27 -------------- 4 files changed, 40 insertions(+), 32 deletions(-) diff --git a/UPDATE.md b/UPDATE.md index fbe52df..1b254dc 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -1,6 +1,13 @@ yexuejc-base 更新记录 ------------------ +#### version :1.2.7 +**time:2018-12-24 15:31:01**
+**branch:** master
+**update:**
+>1. FileUtil增加base64转File `base64ToFile()` + +# #### version :1.2.6 **time:2018-12-21 14:58:49**
**branch:** master
diff --git a/pom.xml b/pom.xml index bdd8b05..00a2e9d 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.yexuejc.base yexuejc-base - 1.2.6 + 1.2.7 ${project.artifactId} diff --git a/src/main/java/com/yexuejc/base/util/FileUtil.java b/src/main/java/com/yexuejc/base/util/FileUtil.java index e23ae2f..337b895 100644 --- a/src/main/java/com/yexuejc/base/util/FileUtil.java +++ b/src/main/java/com/yexuejc/base/util/FileUtil.java @@ -2,10 +2,7 @@ package com.yexuejc.base.util; import sun.misc.BASE64Encoder; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; +import java.io.*; import java.math.BigInteger; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; @@ -307,6 +304,37 @@ public class FileUtil { return encoder.encode(data); } + /** + * base64转文件 + *

+ * + * 文件转base64请使用 {@link FileUtil#base64(File)} + * + * + * @param decode baseByte + * @param fileName 文件名称(包含路径) + * @return 返回保存地址 + */ + public static String base64ToFile(byte[] decode, String fileName) { + + FileOutputStream out = null; + try { + out = new FileOutputStream(fileName); + out.write(decode); + } catch (IOException ioe) { + ioe.printStackTrace(); + } finally { + try { + if (out != null) { + out.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + return fileName; + } + /** * 获取文件大小 :直接返回大小 * diff --git a/src/main/java/com/yexuejc/base/util/ImgUtil.java b/src/main/java/com/yexuejc/base/util/ImgUtil.java index 48ed6ad..7aa3dbc 100644 --- a/src/main/java/com/yexuejc/base/util/ImgUtil.java +++ b/src/main/java/com/yexuejc/base/util/ImgUtil.java @@ -323,33 +323,6 @@ public class ImgUtil { return rs; } - /** - * base64转文件 - * - * @param decode baseByte - * @param fileName 文件名称(包含路径) - * @return 返回保存地址 - */ - public static String base64ToFile(byte[] decode, String fileName) { - - FileOutputStream out = null; - try { - out = new FileOutputStream(fileName); - out.write(decode); - } catch (IOException ioe) { - ioe.printStackTrace(); - } finally { - try { - if (out != null) { - out.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - return fileName; - } - public static class ImageInfo { /** * 图片大小 From 25ddef3bbf39fa5dfdb5289f6f2798786a10d360 Mon Sep 17 00:00:00 2001 From: maxf <1107047387@qq.com> Date: Fri, 28 Dec 2018 20:15:10 +0800 Subject: [PATCH 19/27] =?UTF-8?q?1.2.8=20=E6=96=B0=E5=A2=9EObjUtil=20?= =?UTF-8?q?=E5=AF=B9=E7=B1=BB=EF=BC=88=E5=AF=B9=E8=B1=A1=EF=BC=89=E8=BF=9B?= =?UTF-8?q?=E8=A1=8C=E5=A4=84=E7=90=86=EF=BC=8C=E6=8F=90=E4=BE=9B=E6=B7=B1?= =?UTF-8?q?=E5=BA=A6=E5=85=8B=E9=9A=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- UPDATE.md | 14 +++ WIKI.md | 7 ++ pom.xml | 2 +- .../java/com/yexuejc/base/util/ObjUtil.java | 101 ++++++++++++++++++ 5 files changed, 124 insertions(+), 2 deletions(-) create mode 100644 src/main/java/com/yexuejc/base/util/ObjUtil.java diff --git a/README.md b/README.md index 045fdf4..db6ecaa 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ ### 使用 ->yexuejc.base.version=1.2.6 +>yexuejc.base.version=1.2.8 pom.xml ``` diff --git a/UPDATE.md b/UPDATE.md index 1b254dc..aff1f9f 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -1,6 +1,20 @@ yexuejc-base 更新记录 ------------------ +#### version :1.2.8 +**time:2018-12-28 20:10:14**
+**branch:** master
+**update:**
+>1. 新增[ObjUtil](src/main/java/com/yexuejc/base/util/ObjUtil.java) 对类(对象)进行处理,提供深度克隆 + +# +#### version :1.2.6 +**time:2018-12-21 14:58:49**
+**branch:** master
+**update:**
+>1. RSA 验签增加初始化方法 + +# #### version :1.2.7 **time:2018-12-24 15:31:01**
**branch:** master
diff --git a/WIKI.md b/WIKI.md index 598c021..2278248 100644 --- a/WIKI.md +++ b/WIKI.md @@ -24,5 +24,12 @@ yexuejc-base 文档 ##### 17. RegexUtils 常用正则 ##### 18. StrUtil 字符串工具 ##### 19. SysUtils 常用java系统操作封装 +##### 20. ObjUtil 对象的操作(深度克隆) + +> com.yexuejc.base.encrypt 加密相关 +##### 21. RSA 加密 +##### 22. RSA2 RSA加密获取文件密钥 +##### 23. RSACoder RSA工具 +##### 24. SignAlgorithm 签名算法类型 待完善...... \ No newline at end of file diff --git a/pom.xml b/pom.xml index 00a2e9d..791015d 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.yexuejc.base yexuejc-base - 1.2.7 + 1.2.8 ${project.artifactId} diff --git a/src/main/java/com/yexuejc/base/util/ObjUtil.java b/src/main/java/com/yexuejc/base/util/ObjUtil.java new file mode 100644 index 0000000..172568a --- /dev/null +++ b/src/main/java/com/yexuejc/base/util/ObjUtil.java @@ -0,0 +1,101 @@ +package com.yexuejc.base.util; + +import com.fasterxml.jackson.databind.util.BeanUtil; +import com.sun.org.apache.xml.internal.serializer.OutputPropertyUtils; + +import java.io.*; + +/** + * 对象工具:对类的操作 + * + * @author maxf + * @version 1.0 + * @ClassName ObjUtil + * @Description + * @date 2018/12/28 15:54 + */ +public class ObjUtil { + private ObjUtil() { + } + + /** + *

深度克隆对象

+ *

+ * 将该对象序列化成流,因为写在流里的是对象的一个拷贝,而原对象仍然存在于JVM里面。所以利用这个特性可以实现对象的深拷贝 + *

+ * 注:克隆对象必须序列化 + * + * @param t + * @param + * @return + */ + public static T depthClone(T t) { + T outer = null; + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(t); + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + ObjectInputStream ois = new ObjectInputStream(bais); + outer = (T) ois.readObject(); + } catch (IOException e) { + e.printStackTrace(); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + return outer; + } + +// public static void main(String[] args) { +//// test1(); +//// test2(); +// +// } +// +// private static void test2() { +// B t = new B(); +// t.sex = "男"; +// t.age = 18; +// A test = new A(); +// test.name = "张三"; +// t.test = test; +// B b = depthClone(t); +// System.out.println(JsonUtil.obj2Json(b)); +// } +// +// static class A implements Serializable { +// private static final long serialVersionUID = -8462118058721865488L; +// public String name; +// } +// +// static class B implements Serializable { +// private static final long serialVersionUID = 3297717505428005316L; +// public int age; +// public String sex; +// public A test; +// } +// +// static class C implements Serializable { +// private static final long serialVersionUID = 3297717505428005316L; +// public int age; +// public String sex; +// public A test; +// } +// +// private static void test1() { +// ApiVO apiVO = new ApiVO(ApiVO.STATUS.S); +// apiVO.setMsg("asdsadsad"); +// apiVO.setObject1("sadsadsad"); +// +// Resps obj = new Resps<>(); +// obj.setSucc("安达圣斗士", "ok"); +// System.out.println(obj); +// apiVO.setObject2(obj); +// ApiVO apiVO1 = depthClone(apiVO); +// System.out.println(apiVO == apiVO1); +// System.out.println(JsonUtil.obj2Json(apiVO1)); +// System.out.println(JsonUtil.obj2Json(apiVO1.getObject1(String.class))); +// System.out.println(JsonUtil.obj2Json(apiVO1.getObject2(Resps.class))); +// System.out.println(apiVO1.getObject2(Resps.class) == obj); +// } +} From f77ae05ffe201478099ed03b25016571938b3e30 Mon Sep 17 00:00:00 2001 From: maxf <1107047387@qq.com> Date: Sat, 29 Dec 2018 11:14:20 +0800 Subject: [PATCH 20/27] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/yexuejc/base/util/JsonUtil.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/main/java/com/yexuejc/base/util/JsonUtil.java b/src/main/java/com/yexuejc/base/util/JsonUtil.java index 479288b..f92a315 100644 --- a/src/main/java/com/yexuejc/base/util/JsonUtil.java +++ b/src/main/java/com/yexuejc/base/util/JsonUtil.java @@ -10,6 +10,7 @@ import com.fasterxml.jackson.databind.type.MapType; import java.io.IOException; import java.io.InputStream; import java.util.Map; +import java.util.logging.Logger; /** * json工具类,基于jackson @@ -20,6 +21,8 @@ import java.util.Map; * @date 2018/9/3 15:28 */ public class JsonUtil { + private static Logger log = Logger.getLogger(JsonUtil.class.getName()); + private JsonUtil() { } @@ -70,8 +73,11 @@ public class JsonUtil { try { pojo = objectMapper.readValue(json, cls); } catch (JsonParseException e) { + log.warning("json to Object JsonParseException.\n" + e.getMessage()); } catch (JsonMappingException e) { + log.warning("json to Object JsonMappingException.\n" + e.getMessage()); } catch (IOException e) { + log.warning("json to Object IOException.\n" + e.getMessage()); } return pojo; @@ -90,8 +96,11 @@ public class JsonUtil { try { pojo = objectMapper.readValue(json, cls); } catch (JsonParseException e) { + log.warning("json to Object JsonParseException.\n" + e.getMessage()); } catch (JsonMappingException e) { + log.warning("json to Object JsonMappingException.\n" + e.getMessage()); } catch (IOException e) { + log.warning("json to Object IOException.\n" + e.getMessage()); } return pojo; @@ -113,8 +122,11 @@ public class JsonUtil { try { pojo = objectMapper.readValue(json, javaType); } catch (JsonParseException e) { + log.warning("json to Object JsonParseException.\n" + e.getMessage()); } catch (JsonMappingException e) { + log.warning("json to Object JsonMappingException.\n" + e.getMessage()); } catch (IOException e) { + log.warning("json to Object IOException.\n" + e.getMessage()); } return pojo; } @@ -135,8 +147,11 @@ public class JsonUtil { try { pojo = objectMapper.readValue(json, mapType); } catch (JsonParseException e) { + log.warning("json to Object JsonParseException.\n" + e.getMessage()); } catch (JsonMappingException e) { + log.warning("json to Object JsonMappingException.\n" + e.getMessage()); } catch (IOException e) { + log.warning("json to Object IOException.\n" + e.getMessage()); } return pojo; } @@ -157,8 +172,11 @@ public class JsonUtil { try { pojo = objectMapper.readValue(json, mapType); } catch (JsonParseException e) { + log.warning("json to Object JsonParseException.\n" + e.getMessage()); } catch (JsonMappingException e) { + log.warning("json to Object JsonMappingException.\n" + e.getMessage()); } catch (IOException e) { + log.warning("json to Object IOException.\n" + e.getMessage()); } return pojo; } @@ -178,8 +196,11 @@ public class JsonUtil { try { pojo = objectMapper.readValue(json, javaType); } catch (JsonParseException e) { + log.warning("json to Object JsonParseException.\n" + e.getMessage()); } catch (JsonMappingException e) { + log.warning("json to Object JsonMappingException.\n" + e.getMessage()); } catch (IOException e) { + log.warning("json to Object IOException.\n" + e.getMessage()); } return pojo; } @@ -195,6 +216,7 @@ public class JsonUtil { try { json = objectMapper.writeValueAsString(pojo); } catch (JsonProcessingException e) { + log.warning("json to Object JsonProcessingException.\n" + e.getMessage()); } return json; } From 13328f35f31e2ba778118f4e0a109a184c120553 Mon Sep 17 00:00:00 2001 From: maxf <1107047387@qq.com> Date: Sat, 29 Dec 2018 14:52:38 +0800 Subject: [PATCH 21/27] =?UTF-8?q?1.2.9=20=E8=8E=B7=E5=8F=96RSA=E5=AF=86?= =?UTF-8?q?=E9=92=A5=E5=A2=9E=E5=8A=A0=E4=BB=A5=E8=BE=93=E5=85=A5=E6=B5=81?= =?UTF-8?q?=E7=9A=84=E5=BD=A2=E5=BC=8F=E8=8E=B7=E5=8F=96=E5=AF=86=E9=92=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- UPDATE.md | 14 ++++ pom.xml | 2 +- .../java/com/yexuejc/base/encrypt/RSA2.java | 78 +++++++++++++++++++ 4 files changed, 94 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index db6ecaa..8f14f65 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ ### 使用 ->yexuejc.base.version=1.2.8 +>yexuejc.base.version=1.2.9 pom.xml ``` diff --git a/UPDATE.md b/UPDATE.md index aff1f9f..7e601bd 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -1,6 +1,20 @@ yexuejc-base 更新记录 ------------------ +#### version :1.2.9 +**time:2018-12-29 14:51:33**
+**branch:** master
+**update:**
+>1. 获取RSA密钥增加以输入流的形式获取密钥 + +# +#### version :1.2.6 +**time:2018-12-21 14:58:49**
+**branch:** master
+**update:**
+>1. RSA 验签增加初始化方法 + +# #### version :1.2.8 **time:2018-12-28 20:10:14**
**branch:** master
diff --git a/pom.xml b/pom.xml index 791015d..aa6f90f 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.yexuejc.base yexuejc-base - 1.2.8 + 1.2.9 ${project.artifactId} diff --git a/src/main/java/com/yexuejc/base/encrypt/RSA2.java b/src/main/java/com/yexuejc/base/encrypt/RSA2.java index 20f516b..2e86afd 100644 --- a/src/main/java/com/yexuejc/base/encrypt/RSA2.java +++ b/src/main/java/com/yexuejc/base/encrypt/RSA2.java @@ -5,6 +5,7 @@ import com.yexuejc.base.util.StrUtil; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; +import java.io.InputStream; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; @@ -44,6 +45,21 @@ public class RSA2 { return (RSAPublicKey) c.getPublicKey(); } + /** + * 得到公钥 + * + * @param pubKeyIn 密钥文件流 + * @return + * @throws CertificateException + */ + public static RSAPublicKey getPublicKey(InputStream pubKeyIn) throws CertificateException { + //通过证书,获取公钥 + CertificateFactory cf = null; + cf = CertificateFactory.getInstance("X.509"); + Certificate c = cf.generateCertificate(pubKeyIn); + return (RSAPublicKey) c.getPublicKey(); + } + /** * 读取JKS格式的key(私钥)keystore格式 * @@ -61,6 +77,23 @@ public class RSA2 { return getPrivateKey(filepath, alias, password, "JKS"); } + /** + * 读取JKS格式的key(私钥)keystore格式 + * + * @param priKeyIn 私钥文件流 + * @param alias 证书别名 + * @param password 证书密码 + * @return + * @throws NoSuchAlgorithmException + * @throws KeyStoreException + * @throws IOException + * @throws CertificateException + * @throws UnrecoverableKeyException + */ + public static RSAPrivateKey getPrivateKey(InputStream priKeyIn, String alias, String password) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException { + return getPrivateKey(priKeyIn, alias, password, "JKS"); + } + /** * 读取PKCS12格式的key(私钥)pfx格式 * @@ -78,6 +111,23 @@ public class RSA2 { return getPrivateKey(filepath, alias, password, "PKCS12"); } + /** + * 读取PKCS12格式的key(私钥)pfx格式 + * + * @param priKeyIn 私钥文件流 + * @param alias 证书别名 可空 + * @param password 证书密码 + * @return + * @throws NoSuchAlgorithmException + * @throws KeyStoreException + * @throws IOException + * @throws CertificateException + * @throws UnrecoverableKeyException + */ + public static RSAPrivateKey getPrivateKeyFromPKCS12(InputStream priKeyIn, String alias, String password) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException { + return getPrivateKey(priKeyIn, alias, password, "PKCS12"); + } + /** * 读取key(私钥) * @@ -114,4 +164,32 @@ public class RSA2 { return (RSAPrivateKey) ks.getKey(alias, password.toCharArray()); } + /** + * 读取key(私钥) + * + * @param priKeyIn 私钥文件流 + * @param alias 证书别名 可空 + * @param password 证书密码 + * @param type 证书格式 + * @return + * @throws NoSuchAlgorithmException + * @throws KeyStoreException + * @throws IOException + * @throws CertificateException + * @throws UnrecoverableKeyException + */ + public static RSAPrivateKey getPrivateKey(InputStream priKeyIn, String alias, String password, String type) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException { + KeyStore ks = KeyStore.getInstance(type); + ks.load(priKeyIn, password.toCharArray()); + if (StrUtil.isEmpty(alias)) { + Enumeration aliases = ks.aliases(); + if (aliases != null) { + if (aliases.hasMoreElements()) { + alias = (String) aliases.nextElement(); + } + } + } + return (RSAPrivateKey) ks.getKey(alias, password.toCharArray()); + } + } From ccfad81f6bd38dcfdb0b76eee188ef361d6f0457 Mon Sep 17 00:00:00 2001 From: Shawn <1971049930@qq.com> Date: Sun, 30 Dec 2018 18:20:37 +0800 Subject: [PATCH 22/27] =?UTF-8?q?=E6=8E=A5=E5=8F=97=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E6=8E=A7=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 111 +++++++++------- UPDATE.md | 361 +++++++++++++++++++++++++------------------------- pom.xml | 384 ++++++++++++++++++++++++++++++++++-------------------- 3 files changed, 496 insertions(+), 360 deletions(-) diff --git a/README.md b/README.md index 8f14f65..e9fc362 100644 --- a/README.md +++ b/README.md @@ -1,44 +1,67 @@ -通用工具包 - -### 说明 ->1. 支持环境:java8 ->2. 该工具包基于springboot提取,按理说适用于所有java工程 ->3. 其中依赖jjwt、validation-api,排除请使用 -``` - - - xxx - xxxx - - -``` ->4. 1.1.9升级JWT为单例类 ->5. 1.2.3修复RSA加密(签名)Base64Url 问题,如需使用RSA请使用1.2.3+ - - -### 使用 ->yexuejc.base.version=1.2.9 - -pom.xml -``` - - - com.yexuejc.base - yexuejc-base - ${yexuejc.base.version} - - - - - yexuejc-nexus-public - yexuejc-nexus-public - https://nexus.yexuejc.club/repository/maven-public/ - - -``` - -### 工具文档 -[Wiki](WIKI.md) - -### 更新日志 -[更新记录](UPDATE.md) \ No newline at end of file +yexuejc-base 基于jdk8常用工具包 +---------------------- +源码地址:
+github:https://github.com/yexuejc/yexuejc-base +gitee:https://gitee.com/jzsw-it/yexuejc-base + +### 说明 +>1. 支持环境:java8 +>2. 该工具包基于springboot提取,按理说适用于所有java工程 +>3. 其中依赖jjwt、validation-api,排除请使用 +> ``` +> +> +> xxx +> xxxx +> +> +> ``` +> +>4. `1.1.9` 升级JWT为单例类 +>5. `1.2.3` 修复RSA加密(签名)Base64Url 问题,如需使用RSA请使用1.2.3+ +>##### 6. 从`1.3.0`开始,版本维护转由`成都极致思维网络科技有限公司`向maven中央仓库发布版本,同时变更组织`groupId`为`top.yexuejc`。使用者请尽快升级到`1.3.0`以上(1.3.0代码向下兼容) + + +### 使用 +>yexuejc.base.version=1.3.0 + +pom.xml +``` + + + top.yexuejc + yexuejc-base + ${yexuejc.base.version} + + +``` + +#### 附:1.3.0之前的使用方式 +pom.xml +``` + + + com.yexuejc.base + yexuejc-base + 1.3.0以下 + + + + + yexuejc-nexus-public + yexuejc-nexus-public + https://nexus.yexuejc.club/repository/maven-public/ + + +``` + +### 工具文档 +[Wiki](WIKI.md) + +### 更新日志 +[更新记录](UPDATE.md) + +#### 项目发展 +本工程项目由maxf基于日常使用,从[yexuejc-springboot](https://github.com/yexuejc/yexuejc-springboot.git)(_准备移交版本控制_)中抽离开源独立发展,后续增加许多常用工具包。 +使用者逐渐增多后考虑可靠性和稳定性原则,移交版本控制给`成都极致思维网络科技有限公司`管理,maven包直接发布到中央仓库。 +开源工程项目仍然保持继续维护和欢迎更多愿意贡献的小伙伴参与。 diff --git a/UPDATE.md b/UPDATE.md index 7e601bd..cbfbed6 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -1,177 +1,186 @@ -yexuejc-base 更新记录 ------------------- - -#### version :1.2.9 -**time:2018-12-29 14:51:33**
-**branch:** master
-**update:**
->1. 获取RSA密钥增加以输入流的形式获取密钥 - -# -#### version :1.2.6 -**time:2018-12-21 14:58:49**
-**branch:** master
-**update:**
->1. RSA 验签增加初始化方法 - -# -#### version :1.2.8 -**time:2018-12-28 20:10:14**
-**branch:** master
-**update:**
->1. 新增[ObjUtil](src/main/java/com/yexuejc/base/util/ObjUtil.java) 对类(对象)进行处理,提供深度克隆 - -# -#### version :1.2.6 -**time:2018-12-21 14:58:49**
-**branch:** master
-**update:**
->1. RSA 验签增加初始化方法 - -# -#### version :1.2.7 -**time:2018-12-24 15:31:01**
-**branch:** master
-**update:**
->1. FileUtil增加base64转File `base64ToFile()` - -# -#### version :1.2.6 -**time:2018-12-21 14:58:49**
-**branch:** master
-**update:**
->1. RSA 验签增加初始化方法 - -# -#### version :1.2.5 -**time:2018-12-20 13:13:23**
-**branch:** master
-**update:**
->1. 丰富[JsonUtil](src/main/java/com/yexuejc/base/util/JsonUtil.java),支持直接对Map泛型转换 - -# -#### version :1.2.4 -**time:2018-11-27 14:46:04**
-**branch:** master
-**update:**
->1. 工具类的优化 ->2.规范代码 - -# -#### version :1.2.3 -**time:2018-11-23 16:45:42**
-**branch:** master
-**update:**
->1. 修复RSA加密(签名)时选择的Base64(encodeBase64URLSafeString、encodeBase64String)区分 -# -#### version :1.2.1 -**time:2018-11-9 15:05:06**
-**branch:** master
-**update:**
->1. 优化resps -# -#### version :1.2.2 -**time:2018-11-20 20:20:12**
-**branch:** master
-**update:**
->1. 优化RSA 加解密 ->1. 增加RSA 签名 -# -#### version :1.2.1 -**time:2018-11-9 15:05:06**
-**branch:** master
-**update:**
->1. 优化resps -# -#### version :1.2.0 -**time:2018-10-19 11:38:20**
-**branch:** master
-**update:**
->1. 增加异步线程处理工具 -```$java -SysUtil.threadRun(() -> { - //异步执行代码块 -} -``` -# - -#### version :1.1.9 -**time:2018-9-23 11:57:36**
-**branch:** master
-**update:**
->1. 优化工具类包名:不向下兼容,升级请修改 ->2. 升级JWT工具类:更改为单例模式,可配置参数 -# - -#### version :1.1.8 -**time:2018-9-3 19:29:56**
-**branch:** master
-**update:**
->1. 增肌图片处理工具类 ->2. 增肌3des工具类 ->3. 增肌RSA工具类 ->4. 优化其他工具类 -# -#### version :1.1.7 -**time:2018-8-17 11:22:50**
-**branch:** master
-**update:**
->1. 优化ApiVO -# - -#### version :1.1.6 -**time:2018-7-7 11:32:56**
-**branch:** master
-**update:**
->1. maven仓库更新 -# - -#### version :1.1.5 -**time:2018-6-19 22:16:34**
-**branch:** master
-**update:**
->1. 优化ApiVO - -# -#### version :1.1.4 -**time:2018-6-14 22:27:59**
-**branch:** master
-**update:**
->1. 统一编码:UTF-8 - -# -#### version :1.1.3 -**time:2018年6月2日12:16:58**
-**branch:** master
-**update:**
->1. 修改正则RegexUtils.java ->2. 修改正则StrUtil.java->扩展genUUID() - -# -#### version :1.1.2 -**time:** 2018-5-16 15:03:28
-**branch:** master
-**update:**
->1. 修改依赖 - -# -#### version :1.1.1 -**time:** 2018-5-12 22:25:05
-**branch:** master
-**update:**
->1. 添加RSA -# - -##### version :1.1.0 -**time:** 2018-5-12 22:25:05
-**branch:** master
-**update:**
->1. 添加支持加密功能 -# - -#### version :1.0.0 -**time:** 2018-1-31 12:16:10
-**branch:** master
-**update:**
->1. 基于java8开发的web应用工具包 +yexuejc-base 更新记录 +------------------ + +#### version :1.3.0 +**time:2018-12-30 16:47:50**
+**branch:** master
+**update:**
+>1. 移交发布到maven中央仓库 +>2. 移交后变更groupId 为`top.yexuejc` +>3. 源码发布由`成都极致思维网络科技有限公司`维护,github开源地址不变,gitee从组织[ICC(InCloudCode)](https://gitee.com/incloudcode)转移到[成都极致思维网络科技有限公司/yexuejc-base](https://gitee.com/jzsw-it/yexuejc-base) + +# +#### version :1.2.9 +**time:2018-12-29 14:51:33**
+**branch:** master
+**update:**
+>1. 获取RSA密钥增加以输入流的形式获取密钥 + +# +#### version :1.2.6 +**time:2018-12-21 14:58:49**
+**branch:** master
+**update:**
+>1. RSA 验签增加初始化方法 + +# +#### version :1.2.8 +**time:2018-12-28 20:10:14**
+**branch:** master
+**update:**
+>1. 新增[ObjUtil](src/main/java/com/yexuejc/base/util/ObjUtil.java) 对类(对象)进行处理,提供深度克隆 + +# +#### version :1.2.6 +**time:2018-12-21 14:58:49**
+**branch:** master
+**update:**
+>1. RSA 验签增加初始化方法 + +# +#### version :1.2.7 +**time:2018-12-24 15:31:01**
+**branch:** master
+**update:**
+>1. FileUtil增加base64转File `base64ToFile()` + +# +#### version :1.2.6 +**time:2018-12-21 14:58:49**
+**branch:** master
+**update:**
+>1. RSA 验签增加初始化方法 + +# +#### version :1.2.5 +**time:2018-12-20 13:13:23**
+**branch:** master
+**update:**
+>1. 丰富[JsonUtil](src/main/java/com/yexuejc/base/util/JsonUtil.java),支持直接对Map泛型转换 + +# +#### version :1.2.4 +**time:2018-11-27 14:46:04**
+**branch:** master
+**update:**
+>1. 工具类的优化 +>2.规范代码 + +# +#### version :1.2.3 +**time:2018-11-23 16:45:42**
+**branch:** master
+**update:**
+>1. 修复RSA加密(签名)时选择的Base64(encodeBase64URLSafeString、encodeBase64String)区分 +# +#### version :1.2.1 +**time:2018-11-9 15:05:06**
+**branch:** master
+**update:**
+>1. 优化resps +# +#### version :1.2.2 +**time:2018-11-20 20:20:12**
+**branch:** master
+**update:**
+>1. 优化RSA 加解密 +>1. 增加RSA 签名 +# +#### version :1.2.1 +**time:2018-11-9 15:05:06**
+**branch:** master
+**update:**
+>1. 优化resps +# +#### version :1.2.0 +**time:2018-10-19 11:38:20**
+**branch:** master
+**update:**
+>1. 增加异步线程处理工具 +```$java +SysUtil.threadRun(() -> { + //异步执行代码块 +} +``` +# + +#### version :1.1.9 +**time:2018-9-23 11:57:36**
+**branch:** master
+**update:**
+>1. 优化工具类包名:不向下兼容,升级请修改 +>2. 升级JWT工具类:更改为单例模式,可配置参数 +# + +#### version :1.1.8 +**time:2018-9-3 19:29:56**
+**branch:** master
+**update:**
+>1. 增肌图片处理工具类 +>2. 增肌3des工具类 +>3. 增肌RSA工具类 +>4. 优化其他工具类 +# +#### version :1.1.7 +**time:2018-8-17 11:22:50**
+**branch:** master
+**update:**
+>1. 优化ApiVO +# + +#### version :1.1.6 +**time:2018-7-7 11:32:56**
+**branch:** master
+**update:**
+>1. maven仓库更新 +# + +#### version :1.1.5 +**time:2018-6-19 22:16:34**
+**branch:** master
+**update:**
+>1. 优化ApiVO + +# +#### version :1.1.4 +**time:2018-6-14 22:27:59**
+**branch:** master
+**update:**
+>1. 统一编码:UTF-8 + +# +#### version :1.1.3 +**time:2018年6月2日12:16:58**
+**branch:** master
+**update:**
+>1. 修改正则RegexUtils.java +>2. 修改正则StrUtil.java->扩展genUUID() + +# +#### version :1.1.2 +**time:** 2018-5-16 15:03:28
+**branch:** master
+**update:**
+>1. 修改依赖 + +# +#### version :1.1.1 +**time:** 2018-5-12 22:25:05
+**branch:** master
+**update:**
+>1. 添加RSA +# + +##### version :1.1.0 +**time:** 2018-5-12 22:25:05
+**branch:** master
+**update:**
+>1. 添加支持加密功能 +# + +#### version :1.0.0 +**time:** 2018-1-31 12:16:10
+**branch:** master
+**update:**
+>1. 基于java8开发的web应用工具包 # \ No newline at end of file diff --git a/pom.xml b/pom.xml index aa6f90f..983db4a 100644 --- a/pom.xml +++ b/pom.xml @@ -1,141 +1,245 @@ - - - 4.0.0 - - com.yexuejc.base - yexuejc-base - 1.2.9 - - ${project.artifactId} - - - https://nexus.yexuejc.club/repository/ - http://maven.aliyun.com/nexus/content/groups/public - https://jitpack.io - 0.7.0 - true - 1.8 - 1.1.0.Final - 1.10 - 2.6 - 1.60 - 20.0 - - - - - - io.jsonwebtoken - jjwt - ${jjwt.version} - - - - javax.validation - validation-api - ${validation-api.version} - - - - commons-codec - commons-codec - ${commons-codec.version} - compile - - - - commons-io - commons-io - ${commons-io.version} - - - - org.bouncycastle - bcprov-jdk15on - ${bcprov-jdk15on.version} - - - - com.google.guava - guava - ${guava.version} - - - - - - ${project.artifactId} - - - org.apache.maven.plugins - maven-compiler-plugin - - UTF-8 - 8 - 8 - - - - - org.apache.maven.plugins - maven-source-plugin - 3.0.1 - - - attach-sources - - jar-no-fork - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - build-info - - - - - - true - - - - - - - yexuejc-nexus-public - yexuejc-nexus-public - ${repos.yexuejc.url}maven-public/ - - - aliyun-nexus-public - aliyun-nexus-public - ${repos.aliyun.url} - - - jitpack.io - ${repos.jitpack.url} - - - - - - releases - nexus-release - ${repos.yexuejc.url}maven-releases/ - - - snapshots - nexus-snapshots - ${repos.yexuejc.url}maven-snapshots/ - - + + + 4.0.0 + + top.yexuejc + yexuejc-base + 1.3.0 + + ${project.artifactId} + https://github.com/yexuejc/yexuejc-base + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + + + + + + yexuejc + yexuejc@gmail.com + Chengdu Ultimate Thinking Network Technology Co., Ltd. + +8 + + + + + + scm:git:https://github.com/yexuejc/yexuejc-base.git + + + scm:git:https://github.com/yexuejc/yexuejc-base.git + + https://github.com/yexuejc/yexuejc-base + + + + https://nexus.yexuejc.club/repository/ + http://maven.aliyun.com/nexus/content/groups/public + https://jitpack.io + 0.7.0 + true + 1.8 + 1.1.0.Final + 1.10 + 2.6 + 1.60 + 20.0 + + + + + + io.jsonwebtoken + jjwt + ${jjwt.version} + + + + javax.validation + validation-api + ${validation-api.version} + + + + commons-codec + commons-codec + ${commons-codec.version} + compile + + + + commons-io + commons-io + ${commons-io.version} + + + + org.bouncycastle + bcprov-jdk15on + ${bcprov-jdk15on.version} + + + + com.google.guava + guava + ${guava.version} + + + + + + ${project.artifactId} + + + org.apache.maven.plugins + maven-compiler-plugin + + UTF-8 + 8 + 8 + + + + + org.apache.maven.plugins + maven-source-plugin + 3.0.1 + + + attach-sources + + jar-no-fork + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + build-info + + + + + + true + + + + + + + + + + + + + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.6 + + + verify + + sign + + + + + + + + + yexuejc-nexus-public + yexuejc-nexus-public + ${repos.yexuejc.url}maven-public/ + + + aliyun-nexus-public + aliyun-nexus-public + ${repos.aliyun.url} + + + jitpack.io + ${repos.jitpack.url} + + + + + + + + sonatype-nexus-snapshots + Sonatype Nexus Snapshots + https://oss.sonatype.org/content/repositories/snapshots/ + + + sonatype-nexus-staging + Nexus Release Repository + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + + + + + + sonatype-oss-release + + + + org.apache.maven.plugins + maven-source-plugin + + + attach-sources + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-gpg-plugin + + + sign-artifacts + verify + + sign + + + + + + + + \ No newline at end of file From 67d6f27cae490049ea18e75cfab38e7ff9f04366 Mon Sep 17 00:00:00 2001 From: maxf <1107047387@qq.com> Date: Wed, 2 Jan 2019 09:20:46 +0800 Subject: [PATCH 23/27] =?UTF-8?q?=E5=86=8D=E6=89=A9=E5=B1=95=E5=88=86?= =?UTF-8?q?=E8=BD=AC=E5=85=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/yexuejc/base/util/MoneyUtil.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/main/java/com/yexuejc/base/util/MoneyUtil.java b/src/main/java/com/yexuejc/base/util/MoneyUtil.java index 7ed508d..a5464aa 100644 --- a/src/main/java/com/yexuejc/base/util/MoneyUtil.java +++ b/src/main/java/com/yexuejc/base/util/MoneyUtil.java @@ -34,6 +34,25 @@ public class MoneyUtil { return str; } + /** + * 分转元 + * + * @param num + * @return String + * @Title: formatPrice + * @Description:分转元 + * @throw + */ + public static String toYuan(Long num) { + if (num == null) { + return "0.00"; + } + DecimalFormat df = new DecimalFormat("0.00"); + BigDecimal bigDecimal = new BigDecimal(num).divide(new BigDecimal(100)); + String str = df.format(bigDecimal); + return str; + } + /** * 元转分 * From 5129cdd162d95d9a224a4968013e9878711e1f1e Mon Sep 17 00:00:00 2001 From: maxf <1107047387@qq.com> Date: Wed, 2 Jan 2019 14:08:21 +0800 Subject: [PATCH 24/27] 1.3.1 --- UPDATE.md | 6 + pom.xml | 60 +++--- .../java/com/yexuejc/base/util/ObjUtil.java | 185 +++++++++++++++++- .../java/com/yexuejc/base/util/StrUtil.java | 53 +++++ .../com/yexuejc/base/util/ToUeProperty.java | 14 ++ 5 files changed, 291 insertions(+), 27 deletions(-) create mode 100644 src/main/java/com/yexuejc/base/util/ToUeProperty.java diff --git a/UPDATE.md b/UPDATE.md index cbfbed6..12058d8 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -1,6 +1,12 @@ yexuejc-base 更新记录 ------------------ +#### version :1.3.1 +**time:2019-1-2 14:06:47**
+**branch:** master
+**update:**
+>1. objUtil 增加类字段(驼峰)转换成下划线 +# #### version :1.3.0 **time:2018-12-30 16:47:50**
**branch:** master
diff --git a/pom.xml b/pom.xml index 983db4a..a47dae6 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ top.yexuejc yexuejc-base - 1.3.0 + 1.3.1 ${project.artifactId} https://github.com/yexuejc/yexuejc-base @@ -39,6 +39,7 @@ https://nexus.yexuejc.club/repository/ + https://nexus.mcworle.com/repository/ http://maven.aliyun.com/nexus/content/groups/public https://jitpack.io 0.7.0 @@ -148,19 +149,19 @@ - - org.apache.maven.plugins - maven-gpg-plugin - 1.6 - - - verify - - sign - - - - + + + + + + + + + + + + + @@ -183,16 +184,16 @@ - - sonatype-nexus-snapshots - Sonatype Nexus Snapshots - https://oss.sonatype.org/content/repositories/snapshots/ - - - sonatype-nexus-staging - Nexus Release Repository - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - + + + + + + + + + + + + + releases + nexus-release + ${repos.mcworle.url}maven-releases/ + + + snapshots + nexus-snapshots + ${repos.mcworle.url}maven-snapshots/ + diff --git a/src/main/java/com/yexuejc/base/util/ObjUtil.java b/src/main/java/com/yexuejc/base/util/ObjUtil.java index 172568a..36fa98b 100644 --- a/src/main/java/com/yexuejc/base/util/ObjUtil.java +++ b/src/main/java/com/yexuejc/base/util/ObjUtil.java @@ -1,9 +1,8 @@ package com.yexuejc.base.util; -import com.fasterxml.jackson.databind.util.BeanUtil; -import com.sun.org.apache.xml.internal.serializer.OutputPropertyUtils; - import java.io.*; +import java.lang.reflect.Field; +import java.util.*; /** * 对象工具:对类的操作 @@ -18,6 +17,186 @@ public class ObjUtil { private ObjUtil() { } + /** + *

把对象按照{@link ToUeProperty}注解转换

+ * 字段值为空不输出 + * + * @param obj 要转换的对象 + * @return 转换后的值以Map返回 + */ + public static Map getToUeMap(Object obj) { + return getUnderlineMap(obj, true, false); + } + + /** + *

把对象按照注解转换

+ * 字段值为空不输出 + * + * @param obj 要转换的对象 + * @return 转换后的值toJson以String返回 + */ + public static String getToUeStr(Object obj) { + return JsonUtil.obj2Json(getUnderlineMap(obj, true, false)); + } + + /** + *

把对象驼峰字段转换成下划线输出,支持继承和字段类型为对象

+ * 字段值为空不输出 + * + * @param obj 要转换的对象 + * @return 转换后的值以Map返回 + */ + public static Map getUnderlineMap(Object obj) { + return getUnderlineMap(obj, true, false); + } + + /** + *

把对象驼峰字段转换成下划线输出,支持继承和字段类型为对象

+ * 字段值为空不输出 + * + * @param obj 要转换的对象 + * @return 转换后的值toJson以String返回 + */ + public static String getUnderlineStr(Object obj) { + return JsonUtil.obj2Json(getUnderlineMap(obj, true, false)); + } + + /** + * 把对象字段按{@link ToUeProperty}注解规则转换输出,支持继承和字段类型为对象 + * + * @param obj 要转换的对象 + * @param isAnnotationAll 是否全部依赖注解转换。全部依赖注解转换:true 只有字段上有注解的才转换,没有注解的默认不转换;false 有注解的依照注解转换,没有的全传下划线 + * @param putNull 是否映射null + * @return 转换后的值toJson以String返回 + */ + public static String getUnderlineStr(Object obj, boolean isAnnotationAll, boolean putNull) { + return JsonUtil.obj2Json(getUnderlineMap(obj, isAnnotationAll, putNull)); + } + + /** + * 把对象字段按{@link ToUeProperty}注解规则转换成输出,支持继承和字段类型为对象 + *

主要功能:解决输出时驼峰-下划线的转换

+ * + * @param obj 要转换的对象 + * @param isAnnotationAll 是否全部依赖注解转换。全部依赖注解转换:true 只有字段上有注解的才转换,没有注解的默认不转换;false 有注解的依照注解转换,没有的全传下划线 + * @param putNull 是否映射null + * @return + */ + public static Map getUnderlineMap(Object obj, boolean isAnnotationAll, boolean putNull) { + Class bindClass = obj.getClass(); + Map objMap = new HashMap<>(0); + /* + * 得到类中的所有属性集合 + */ + try { + List fieldList = new ArrayList<>(); + //当父类为null的时候说明到达了最上层的父类(Object类). + while (bindClass != null) { + fieldList.addAll(Arrays.asList(bindClass.getDeclaredFields())); + //得到父类,然后赋给自己 + bindClass = bindClass.getSuperclass(); + } + for (Field f : fieldList) { + //排除序列化 + if ("serialVersionUID".equals(f.getName())) { + continue; + } + //设置些属性是可以访问的 + f.setAccessible(true); + String fName = f.getName(); + if (!isAnnotationAll) { + fName = StrUtil.camelToUnderline(f.getName()); + } + boolean annotationPresent = f.isAnnotationPresent(ToUeProperty.class); + if (annotationPresent) { + ToUeProperty annotation = f.getAnnotation(ToUeProperty.class); + String value = annotation.value(); + if (StrUtil.isNotEmpty(value)) { + fName = value; + } + } + Object o = f.get(obj); + if (null == o || o.getClass().isPrimitive() || o instanceof String) { + if (null == o && !putNull) { + continue; + } + objMap.put(fName, f.get(obj)); + } else { + Map underlineMap = getUnderlineMap(o, isAnnotationAll, putNull); + objMap.put(fName, underlineMap); + } + } + } catch (IllegalAccessException e) { + System.out.println(e.getMessage()); + } + return objMap; + } + + + public static void main(String[] args) { + B a = new B(); + a.nameFirst = "张三"; + a.ageInt = "5165458"; + a.testAss = "asdasdsad"; + a.setaM1("method1"); + a.setbM1("b1Mthod1"); + a.protectedStr = "protectedStr"; + a.c = new C(); + a.c.ageInt = "test"; + Map underlineMap = getUnderlineMap(a, false, false); + System.out.println(JsonUtil.obj2Json(underlineMap)); + } + + static class A implements Serializable { + private static final long serialVersionUID = -8462118058721865488L; + public String nameFirst; + public String ageInt; + private String aM1; + @ToUeProperty("p_str") + protected String protectedStr; + + public String getaM1() { + return aM1; + } + + public A setaM1(String aM1) { + this.aM1 = aM1; + return this; + } + } + + static class B extends A { + private static final long serialVersionUID = -8462118058721865488L; + public String testAss; + private String bM1; + private C c; + + public String getbM1() { + return bM1; + } + + public B setbM1(String bM1) { + this.bM1 = bM1; + return this; + } + } + + static class C extends A { + private static final long serialVersionUID = -8462118058721865488L; + public String testAss; + private String bM1; + + public String getbM1() { + return bM1; + } + + public C setbM1(String bM1) { + this.bM1 = bM1; + return this; + } + } + + /** *

深度克隆对象

*

diff --git a/src/main/java/com/yexuejc/base/util/StrUtil.java b/src/main/java/com/yexuejc/base/util/StrUtil.java index 9664005..55c07c2 100644 --- a/src/main/java/com/yexuejc/base/util/StrUtil.java +++ b/src/main/java/com/yexuejc/base/util/StrUtil.java @@ -366,4 +366,57 @@ public final class StrUtil { } return msg; } + + /** + * 下划线字符 + */ + public static final char UNDERLINE = '_'; + + /** + * 字符串下划线转驼峰格式 + * + * @param param 需要转换的字符串 + * @return 转换好的字符串 + */ + public static String underlineToCamel(String param) { + if (isEmpty(param)) { + return ""; + } + String temp = param.toLowerCase(); + int len = temp.length(); + StringBuilder sb = new StringBuilder(len); + for (int i = 0; i < len; i++) { + char c = temp.charAt(i); + if (c == UNDERLINE) { + if (++i < len) { + sb.append(Character.toUpperCase(temp.charAt(i))); + } + } else { + sb.append(c); + } + } + return sb.toString(); + } + + /** + * 字符串驼峰转下划线格式 + * + * @param param 需要转换的字符串 + * @return 转换好的字符串 + */ + public static String camelToUnderline(String param) { + if (isEmpty(param)) { + return ""; + } + int len = param.length(); + StringBuilder sb = new StringBuilder(len); + for (int i = 0; i < len; i++) { + char c = param.charAt(i); + if (Character.isUpperCase(c) && i > 0) { + sb.append(UNDERLINE); + } + sb.append(Character.toLowerCase(c)); + } + return sb.toString(); + } } diff --git a/src/main/java/com/yexuejc/base/util/ToUeProperty.java b/src/main/java/com/yexuejc/base/util/ToUeProperty.java new file mode 100644 index 0000000..4398c63 --- /dev/null +++ b/src/main/java/com/yexuejc/base/util/ToUeProperty.java @@ -0,0 +1,14 @@ +package com.yexuejc.base.util; + +import java.lang.annotation.*; + +@Target({ElementType.FIELD, ElementType.TYPE, ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface ToUeProperty { + /** + * 字段名,默认该字段转下划线 + * @return + */ + String value() default ""; +} \ No newline at end of file From 93488c6fff5bc524a444ea11072831a6028b468d Mon Sep 17 00:00:00 2001 From: maxf <1107047387@qq.com> Date: Wed, 2 Jan 2019 14:48:55 +0800 Subject: [PATCH 25/27] 1.3.2 --- UPDATE.md | 6 ++++++ pom.xml | 2 +- src/main/java/com/yexuejc/base/util/ObjUtil.java | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/UPDATE.md b/UPDATE.md index 12058d8..b847a01 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -1,6 +1,12 @@ yexuejc-base 更新记录 ------------------ +#### version :1.3.2 +**time:2019-1-2 14:06:47**
+**branch:** master
+**update:**
+>1. objUtil 枚举类型修复 +# #### version :1.3.1 **time:2019-1-2 14:06:47**
**branch:** master
diff --git a/pom.xml b/pom.xml index a47dae6..7f9f328 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ top.yexuejc yexuejc-base - 1.3.1 + 1.3.2 ${project.artifactId} https://github.com/yexuejc/yexuejc-base diff --git a/src/main/java/com/yexuejc/base/util/ObjUtil.java b/src/main/java/com/yexuejc/base/util/ObjUtil.java index 36fa98b..b98c753 100644 --- a/src/main/java/com/yexuejc/base/util/ObjUtil.java +++ b/src/main/java/com/yexuejc/base/util/ObjUtil.java @@ -116,7 +116,7 @@ public class ObjUtil { } } Object o = f.get(obj); - if (null == o || o.getClass().isPrimitive() || o instanceof String) { + if (null == o || o.getClass().isPrimitive() || o instanceof String || o instanceof Enum) { if (null == o && !putNull) { continue; } From a639d6162490b75f9ee2683fe4a60711cd0b28bd Mon Sep 17 00:00:00 2001 From: maxf <1107047387@qq.com> Date: Wed, 2 Jan 2019 15:23:40 +0800 Subject: [PATCH 26/27] 1.3.3 --- UPDATE.md | 6 ++++++ pom.xml | 2 +- .../java/com/yexuejc/base/util/MoneyUtil.java | 19 +++++++++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/UPDATE.md b/UPDATE.md index b847a01..15fd707 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -1,6 +1,12 @@ yexuejc-base 更新记录 ------------------ +#### version :1.3.3 +**time:2019-1-2 14:06:47**
+**branch:** master
+**update:**
+>1. MoneyUtil 扩展元转分 +# #### version :1.3.2 **time:2019-1-2 14:06:47**
**branch:** master
diff --git a/pom.xml b/pom.xml index 7f9f328..3b2f3e0 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ top.yexuejc yexuejc-base - 1.3.2 + 1.3.3 ${project.artifactId} https://github.com/yexuejc/yexuejc-base diff --git a/src/main/java/com/yexuejc/base/util/MoneyUtil.java b/src/main/java/com/yexuejc/base/util/MoneyUtil.java index a5464aa..8222c15 100644 --- a/src/main/java/com/yexuejc/base/util/MoneyUtil.java +++ b/src/main/java/com/yexuejc/base/util/MoneyUtil.java @@ -71,4 +71,23 @@ public class MoneyUtil { String str = df.format(bigDecimal); return Integer.parseInt(str); } + + /** + * 元转分 + * + * @param num + * @return int + * @Title: formatPrice + * @Description: 元转分 + * @throw + */ + public static Long toFen4Long(String num) { + if (num == null) { + return 0L; + } + DecimalFormat df = new DecimalFormat("#0"); + BigDecimal bigDecimal = new BigDecimal(num).multiply(new BigDecimal(100)); + String str = df.format(bigDecimal); + return Long.parseLong(str); + } } From ceb7b77a7181e71847ab4f464cfa42db2582867d Mon Sep 17 00:00:00 2001 From: maxf <1107047387@qq.com> Date: Wed, 2 Jan 2019 20:32:51 +0800 Subject: [PATCH 27/27] 1.3.4 --- UPDATE.md | 6 ++++++ pom.xml | 2 +- .../java/com/yexuejc/base/util/ObjUtil.java | 20 +++++++++++++++++-- 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/UPDATE.md b/UPDATE.md index 15fd707..4be0bb5 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -1,6 +1,12 @@ yexuejc-base 更新记录 ------------------ +#### version :1.3.4 +**time:2019-1-2 20:32:12**
+**branch:** master
+**update:**
+>1. objUtil list类型修复 +# #### version :1.3.3 **time:2019-1-2 14:06:47**
**branch:** master
diff --git a/pom.xml b/pom.xml index 3b2f3e0..6bd77e8 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ top.yexuejc yexuejc-base - 1.3.3 + 1.3.4 ${project.artifactId} https://github.com/yexuejc/yexuejc-base diff --git a/src/main/java/com/yexuejc/base/util/ObjUtil.java b/src/main/java/com/yexuejc/base/util/ObjUtil.java index b98c753..c2f3bee 100644 --- a/src/main/java/com/yexuejc/base/util/ObjUtil.java +++ b/src/main/java/com/yexuejc/base/util/ObjUtil.java @@ -121,6 +121,18 @@ public class ObjUtil { continue; } objMap.put(fName, f.get(obj)); + } else if (o instanceof List) { + List list = (List) o; + List bodyList = new ArrayList(); + list.forEach(it -> { + if (null != it) { + Map underlineMap = getUnderlineMap(it, isAnnotationAll, putNull); + bodyList.add(underlineMap); + } + }); + if (bodyList.size() > 0) { + objMap.put(fName, bodyList); + } } else { Map underlineMap = getUnderlineMap(o, isAnnotationAll, putNull); objMap.put(fName, underlineMap); @@ -141,8 +153,11 @@ public class ObjUtil { a.setaM1("method1"); a.setbM1("b1Mthod1"); a.protectedStr = "protectedStr"; - a.c = new C(); - a.c.ageInt = "test"; + C c = new C(); + c.ageInt = "test"; + a.c = c; + a.list = new ArrayList<>(); + a.list.add(c); Map underlineMap = getUnderlineMap(a, false, false); System.out.println(JsonUtil.obj2Json(underlineMap)); } @@ -170,6 +185,7 @@ public class ObjUtil { public String testAss; private String bM1; private C c; + List list; public String getbM1() { return bM1;