概述
ThreadLocal
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class ThreadLocalUtil {
private static final ThreadLocal<Map<String, Object>> threadLocal = ThreadLocal.withInitial(() -> new HashMap<>(10));
public static Map<String, Object> getThreadLocal() {
return threadLocal.get();
}
public static <T> T get(String key) {
Map<String, Object> map = threadLocal.get();
return get(key, null);
}
@SuppressWarnings("unchecked")
public static <T> T get(String key, T defaultValue) {
Map<String, Object> map = threadLocal.get();
return (T) Optional.ofNullable(map.get(key)).orElse(defaultValue);
}
public static void set(String key, Object value) {
Map<String, Object> map = threadLocal.get();
map.put(key, value);
}
public static void set(Map<String, Object> keyValueMap) {
Map<String, Object> map = threadLocal.get();
map.putAll(keyValueMap);
}
public static void remove() {
threadLocal.remove();
}
@SuppressWarnings("unchecked")
public static <T> T remove(String key) {
Map<String, Object> map = threadLocal.get();
return (T) map.remove(key);
}
}
对象复制
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
/**
* 对象复制注解
* CopyUtil对象复制工具类使用
*/
@Target({FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CopyAnnotation {
/**
* 目标字段
* @return
*/
String value();
/**
* 目标字段所在类型
* @return
*/
Class type();
}
import com.tencent.finance.enums.CopyAnnotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class CopyBeanUtil {
private static Class myAnnotation = CopyAnnotation.class;
/**
* 对象属性赋值方法
* 将 V 中的属性值,按照属性名的对应关系,复制到 K 中去
* @param target K 目标类
* @param source V 源对象
* @param <K> 泛型
* @param <V> 泛型
*/
public static <K, V> void copyProperties(V source,K target) {
// 1.通过反射获取到b的属性值列表
Field[] fields = target.getClass().getDeclaredFields();
try {
for (Field field : fields) {
// 1.获取属性名到源对象中的属性值(getter方式)
Object value = getFieldValueByName(field.getName(), source);
// 2.如果属性值为null,跳过该属性复制
if (value == null) {
continue;
}
// 3.获取属性CopyAnnotation注解(自定义)的value值(对应的是目标对象的属性名)
// 没有自定义注解,或者自定义注解没有对value属性赋值:使用原有的属性名
String annotationName = getMyAnnotationValue(field);
// 4.使用setter的方式将值复制到目标对象
setTargetFieldValueByNameAndValue(target, annotationName, field.getType(), value);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
System.out.println("====================对象属性赋值完成====================");
}
/**
* 根据属性名,对象获取对象的属性值
*
* @param name 属性名
* @param v 对象
* @param <V> 泛型方法
* @return Object 属性值
* @throws IllegalAccessException IllegalAccessException
* @throws NoSuchMethodException NoSuchMethodException
* @throws InvocationTargetException InvocationTargetException
*/
private static <V> Object getFieldValueByName(String name, V v)
throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
String firstLetter = name.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + name.substring(1);
Method method = v.getClass().getMethod(getter, new Class[]{});
return method.invoke(v, new Class[]{});
}
/**
* 根据对象、属性名、参数类型、参数值
* 使用反射调用setter进行对象属性的赋值操作
*
* @param k 对象
* @param fieldName 属性名
* @param parameterClass 参数类型
* @param value 参数值
* @param <K> 泛型
* @throws NoSuchMethodException NoSuchMethodException
* @throws InvocationTargetException InvocationTargetException
* @throws IllegalAccessException IllegalAccessException
*/
private static <K> void setTargetFieldValueByNameAndValue(K k, String fieldName, Class parameterClass, Object value)
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String setter = "set" + firstLetter + fieldName.substring(1);
Method method;
method = k.getClass().getMethod(setter, new Class[]{parameterClass});
method.invoke(k, value);
}
/**
* 获取属性上自定义注解的value值
*
* @param field Field
* @return String
*/
private static String getMyAnnotationValue(Field field) {
CopyAnnotation annotation = (CopyAnnotation) field.getAnnotation(myAnnotation);
if (annotation == null || annotation.value() == null) {
return field.getName();
}
return annotation.value();
}
}
加解密
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.interfaces.ECPrivateKey;
import org.bouncycastle.jce.interfaces.ECPublicKey;
import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class ECCUtil {
static {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
}
//生成秘钥对
public static KeyPair getKeyPair() throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", "BC");
keyPairGenerator.initialize(256, new SecureRandom());
KeyPair keyPair = keyPairGenerator.generateKeyPair();
return keyPair;
}
//获取公钥(Base64编码)
public static String getPublicKey(KeyPair keyPair){
ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();
byte[] bytes = publicKey.getEncoded();
return Base64.encodeBase64String(bytes);
}
//获取私钥(Base64编码)
public static String getPrivateKey(KeyPair keyPair){
ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate();
byte[] bytes = privateKey.getEncoded();
return Base64.encodeBase64String(bytes);
}
//将Base64编码后的公钥转换成PublicKey对象
public static ECPublicKey string2PublicKey(String pubStr) throws Exception{
byte[] keyBytes = Base64.decodeBase64(pubStr);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("EC", "BC");
ECPublicKey publicKey = (ECPublicKey) keyFactory.generatePublic(keySpec);
return publicKey;
}
//将Base64编码后的私钥转换成PrivateKey对象
public static ECPrivateKey string2PrivateKey(String priStr) throws Exception{
byte[] keyBytes = Base64.decodeBase64(priStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("EC", "BC");
ECPrivateKey privateKey = (ECPrivateKey) keyFactory.generatePrivate(keySpec);
return privateKey;
}
//公钥加密
public static byte[] publicEncrypt(byte[] content, PublicKey publicKey) throws Exception{
Cipher cipher = Cipher.getInstance("ECIES", "BC");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] bytes = cipher.doFinal(content);
return bytes;
}
//私钥解密
public static byte[] privateDecrypt(byte[] content, PrivateKey privateKey) throws Exception{
Cipher cipher = Cipher.getInstance("ECIES", "BC");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] bytes = cipher.doFinal(content);
return bytes;
}
}
import cn.hutool.core.codec.Base64Decoder;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
public class EncryptUtils {
private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
/**
* base 64 encode
*
* @param bytes 待编码的byte[]
* @return 编码后的base 64 code
*/
private static String base64Encode(byte[] bytes) {
return Base64.encodeBase64String(bytes);
}
/**
* base 64 decode
*
* @param base64Code 待解码的base 64 code
* @return 解码后的byte[]
* @throws Exception 抛出异常
*/
private static byte[] base64Decode(String base64Code) throws Exception {
return StringUtils.isEmpty(base64Code) ? null : Base64Decoder.decode(base64Code);
}
/**
* AES加密
*
* @param content 待加密的内容
* @param encryptKey 加密密钥
* @return 加密后的byte[]
*/
private static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
return cipher.doFinal(content.getBytes("utf-8"));
}
/**
* AES加密为base 64 code
*
* @param content 待加密的内容
* @param encryptKey 加密密钥
* @return 加密后的base 64 code
*/
public static String aesEncrypt(String content, String encryptKey) throws Exception {
return base64Encode(aesEncryptToBytes(content, encryptKey));
}
/**
* AES解密
*
* @param encryptBytes 待解密的byte[]
* @param decryptKey 解密密钥
* @return 解密后的String
*/
private static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
byte[] decryptBytes = cipher.doFinal(encryptBytes);
return new String(decryptBytes);
}
/**
* 将base 64 code AES解密
*
* @param encryptStr 待解密的base 64 code
* @param decryptKey 解密密钥
* @return 解密后的string
*/
public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
}
}
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
public class RSAEncryptUtil {
private static Map<Integer, String> keyMap = new HashMap<Integer, String>(); //用于封装随机产生的公钥与私钥
/**
* 随机生成密钥对
* @throws NoSuchAlgorithmException
*/
public static Map<String,String> genKeyPair() throws NoSuchAlgorithmException {
// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
// 初始化密钥对生成器,密钥大小为96-1024位
keyPairGen.initialize(1024,new SecureRandom());
// 生成一个密钥对,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 得到私钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 得到公钥
String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
// 得到私钥字符串
String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
// 将公钥和私钥保存到Map
keyMap.put(0,publicKeyString); //0表示公钥
keyMap.put(1,privateKeyString); //1表示私钥
Map<String, String> map = new HashMap<>();
map.put("publicKeyString", publicKeyString);
map.put("privateKeyString", privateKeyString);
return map;
}
/**
* RSA公钥加密
*
* @param str 加密字符串
* @param publicKey 公钥
* @return 密文
* @throws Exception 加密过程中的异常信息
*/
public static String encrypt( String str, String publicKey ) throws Exception{
//base64编码的公钥
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
//RSA加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
return outStr;
}
/**
* RSA私钥解密
*
* @param str 加密字符串
* @param privateKey 私钥
* @return 密文
* @throws Exception 解密过程中的异常信息
*/
public static String decrypt(String str, String privateKey) throws Exception{
//64位解码加密后的字符串
byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
//base64编码的私钥
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
//Cipher cipher = Cipher.getInstance("RSA");
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, priKey);
String outStr = new String(cipher.doFinal(inputByte));
return outStr;
}
}
id生成
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* id生成工具类
*/
@Slf4j
@Component
public class IdUtil {
@Value("${redis_prefix}")
private static String redisPrefix;
private static final String PREFIX = "SF";
// 默认redisKey
private static final String DEFAULT_KEY = redisPrefix + IdUtil.class.getSimpleName() + "_";
// 默认有序序号长度
private static final int DEFAULT_LENGTH = 6;
// 天的毫秒值
private static final long DAY = 24 * 60 * 60 * 1000;
@Resource
private RedisUtil redisUtil;
@Resource
private Snowflake snowflake;
// 获取当前时间年月日字符串
private static String getNowDateStr() {
return DateUtils.format(new Date(), "yyyyMMdd");
}
/**
* 获取随机雪花id
*
* @return 获取随机雪花id
*/
public String randomId() {
return String.valueOf(snowflake.nextId());
}
/**
* 获取随机UUID
*
* @return 随机UUID
*/
public static String randomUUID() {
return UUID.randomUUID().toString();
}
/**
* 简化的UUID,去掉了横线
*
* @return 简化的UUID,去掉了横线
*/
public static String simpleUUID() {
return UUID.randomUUID().toString(true);
}
/**
* 获取随机UUID,使用性能更好的ThreadLocalRandom生成UUID
*
* @return 随机UUID
* @since 4.1.19
*/
public static String fastUUID() {
return UUID.fastUUID().toString();
}
/**
* 简化的UUID,去掉了横线,使用性能更好的ThreadLocalRandom生成UUID
*
* @return 简化的UUID,去掉了横线
* @since 4.1.19
*/
public static String fastSimpleUUID() {
return UUID.fastUUID().toString(true);
}
/**
* 获取下一个自增有序id
*
* @param key 自增id的key,不同的key之间自增长数不会互相影响
* @return 自增有序id
*/
public String nextId(String key) {
return nextId(key, DEFAULT_LENGTH);
}
/**
* 获取融资申请编号
* @return
*/
public String applyNo(){
// 获取当前年月日字符串
String newDateStr = getNowDateStr();
// redis键值(关键字+当前时间年月日)
String redisKey = DEFAULT_KEY + PREFIX + newDateStr;
// 自增数
Long count = redisUtil.increment(redisKey, 1);
if (redisUtil.getExpire(redisKey) == -1) {
redisUtil.expire(redisKey, DAY, TimeUnit.MILLISECONDS);
}
return PREFIX + newDateStr + "-" + StringUtils.leftPad(String.valueOf(count), 4, "0");
}
/**
* 获取下一个自增有序id
*
* @param key 自增id的key,不同的key之间自增长数不会互相影响
* @param length 自增有序id长度(不是返回id的长度)
* @return 自增有序id
*/
public String nextId(String key, int length) {
// 获取当前年月日字符串
String newDateStr = getNowDateStr();
// redis键值(关键字+当前时间年月日)
String redisKey = DEFAULT_KEY + key + newDateStr;
// 自增数
Long count = redisUtil.increment(redisKey, 1);
String serialNumber = StringUtils.leftPad(String.valueOf(count), length, "0");
String nextId = DateUtils.format(new Date(), "yyyyMMddHHmmssSSS")
+ RandomUtil.randomInt(100000) + serialNumber;
if (redisUtil.getExpire(redisKey) == -1) {
redisUtil.expire(redisKey, DAY, TimeUnit.MILLISECONDS);
}
return nextId;
}
}
ExceptionUtil
@Slf4j
public class ExceptionUtil {
private ExceptionUtil() {
}
/**
* 获取异常信息
*
* @param e 异常
*/
public static String getErrorMessage(Exception e) {
StringWriter sw = null;
PrintWriter pw = null;
try {
sw = new StringWriter();
pw = new PrintWriter(sw);
// 将出错的栈信息输出到printWriter中
e.printStackTrace(pw);
pw.flush();
sw.flush();
} finally {
if (sw != null) {
try {
sw.close();
} catch (IOException e1) {
log.info(e1.getMessage());
}
}
if (pw != null) {
pw.close();
}
}
return sw.toString();
}
/**
* 异常信息-->json
*
*/
/*public static String resultOf(ResultStatusCode resultStatusCode) {
SerializeConfig config = new SerializeConfig();
config.configEnumAsJavaBean(ResultStatusCode.class);
return JSON.toJSONString(resultStatusCode, config);
}*/
}
public class commonUtils {
public static boolean prosHandle(Object source, Object target, String type) {
log.info("type={}",type);
if (Objects.equals(type, "remove") && source == null) {
return false;
}
if (Objects.equals(type, "copy")) {
if (!(target != null && source != null)) {
return false;
}
String oName = source.getClass().getName();
String o1Name = target.getClass().getName();
log.info("oName={},o1Name={},type={}", oName, o1Name, type);
if (!oName.equals(o1Name)) {
return false;
}
}
Field[] fields = source.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field f = fields[i];
try {
switch (type) {
case "remove": f.set(source, null);break;
case "copy": f.set(target, f.get(source));break;
}
} catch (Exception e) {
//return false;
}
}
return true;
}
}
最后
以上就是感性电话为你收集整理的工具类常用的全部内容,希望文章能够帮你解决工具类常用所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复