提交 65a34929 authored 作者: renjianyu's avatar renjianyu

--no commit message

上级 ce7e7ceb
package com.zrqx.core.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/*
* AES对称加密和解密
*/
public class ASCUtil {
/** 是否需要加密 */
private static final boolean NEED = true;
/** 加密密钥 */
private static final String ENCODE_RULES = "rsks2018";
private final static Logger logger = LoggerFactory.getLogger(ASCUtil.class);
/**
* 使用默认密钥加密
* @param content 待加密内容
* @return
* @author lpf
* @date: 2018年11月16日 下午2:02:16
*/
public static String addAESEncode(String content) {
return AESEncode(ENCODE_RULES, content);
}
/**
* 加密 1.构造密钥生成器 2.根据ecnodeRules规则初始化密钥生成器 3.产生密钥 4.创建和初始化密码器 5.内容加密 6.返回字符串
* @param encodeRules 加密密钥
* @param content 待加密内容
* @return
* @author lpf
* @date: 2018年11月16日 上午9:38:41
*/
public static String AESEncode(String encodeRules, String content) {
if (!NEED) {
return content;
}
try {
// 1.构造密钥生成器,指定为AES算法,不区分大小写
KeyGenerator keygen = KeyGenerator.getInstance("AES");
// 2.根据ecnodeRules规则初始化密钥生成器
// 生成一个128位的随机源,根据传入的字节数组
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(encodeRules.getBytes());
keygen.init(128, secureRandom);
// 3.产生原始对称密钥
SecretKey original_key = keygen.generateKey();
// 4.获得原始对称密钥的字节数组
byte[] raw = original_key.getEncoded();
// 5.根据字节数组生成AES密钥
SecretKey key = new SecretKeySpec(raw, "AES");
// 6.根据指定算法AES自成密码器
Cipher cipher = Cipher.getInstance("AES");
// 7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY
cipher.init(Cipher.ENCRYPT_MODE, key);
// 8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
byte[] byte_encode = content.getBytes("utf-8");
// 9.根据密码器的初始化方式--加密:将数据加密
byte[] byte_AES = cipher.doFinal(byte_encode);
// 10.将加密后的数据转换为字符串
// 这里用Base64Encoder中会找不到包
// 解决办法:
// 在项目的Build path中先移除JRE System Library,再添加库JRE System
// Library,重新编译后就一切正常了。
String AES_encode = new String(new BASE64Encoder().encode(byte_AES));
// 11.将字符串返回
return AES_encode;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 如果有错就返回原文
return content;
}
/**
* 根据默认密钥解密
* @param content 待解密内容
* @return
* @author lpf
* @date: 2018年11月16日 下午2:03:13
*/
public static String disAESDncode(String content) {
return AESDncode(ENCODE_RULES, content);
}
/**
* 解密 解密过程: 1.同加密1-4步 2.将加密后的字符串反纺成byte[]数组 3.将加密内容解密
* @param encodeRules 解密密钥
* @param content 待解密内容
* @return
* @author lpf
* @date: 2018年11月16日 上午9:39:34
*/
public static String AESDncode(String encodeRules, String content) {
if (!NEED) {
return content;
}
try {
// 1.构造密钥生成器,指定为AES算法,不区分大小写
KeyGenerator keygen = KeyGenerator.getInstance("AES");
// 2.根据ecnodeRules规则初始化密钥生成器
// 生成一个128位的随机源,根据传入的字节数组
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(encodeRules.getBytes());
keygen.init(128, secureRandom);
// 3.产生原始对称密钥
SecretKey original_key = keygen.generateKey();
// 4.获得原始对称密钥的字节数组
byte[] raw = original_key.getEncoded();
// 5.根据字节数组生成AES密钥
SecretKey key = new SecretKeySpec(raw, "AES");
// 6.根据指定算法AES自成密码器
Cipher cipher = Cipher.getInstance("AES");
// 7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作,第二个参数为使用的KEY
cipher.init(Cipher.DECRYPT_MODE, key);
// 8.将加密并编码后的内容解码成字节数组
byte[] byte_content = new BASE64Decoder().decodeBuffer(content);
/*
* 解密
*/
byte[] byte_decode = cipher.doFinal(byte_content);
String AES_decode = new String(byte_decode, "utf-8");
return AES_decode;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
logger.info("要解密的参数(" + content + ")异常");
} catch (BadPaddingException e) {
e.printStackTrace();
}
// 如果有错就返回原文
return content;
}
public static void main(String[] args) {
/*
* 加密
*/
String encodeRules = "rsks2018";
String content = "13335881155";
String str = ASCUtil.AESEncode(encodeRules, content);
System.out.println("密钥" + encodeRules + "加密后的密文是:" + str);
str = "7P2/fNSjJGaRvUebdNzvxw==";
str = "aaqe+HJCiTeUwjQhGqr1XuJ+5GaLdEhlMOwdlsdmbxZiHR+NfoIwkvhRSojT09+N";
str = "zTDBo4QyX/JFPSM4gF6cDA==";
/*
* 解密
*/
str = ASCUtil.AESDncode(encodeRules, str);
System.out.println("密钥" + encodeRules + "解密后的明文是:" + str);
String context1 = "cxc";
String str1 = ASCUtil.AESEncode(encodeRules, context1);
System.out.println("密钥" + encodeRules + "加密后的密文是:" + str1);
str = ASCUtil.AESDncode(encodeRules, str1);
System.out.println("密钥" + encodeRules + "解密后的明文是:" + str);
}
}
package com.zrqx.core.util;
public class ArrayUtils {
/**
* 省份对比
*
* @param array
* @param objectToFind
* @return
* @author Conan
* @date: 2018年10月24日 下午6:02:05
*/
public static boolean contains(String[] array, String objectToFind) {
if (objectToFind == null) {
for (int i = 0; i < array.length; i++) {
if (array[i] == null) {
return true;
}
}
}
String str = (String)objectToFind;
objectToFind = str.substring(0, 2);
for (int i = 0; i < array.length; i++) {
if (array[i].startsWith(objectToFind)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
String[] s = {"新疆維吾爾族自治區","上海","香港"};
String str = "香港特別行政區";
System.out.println(contains(s, str));
}
}
package com.zrqx.core.util;
import java.util.Random;
public class CardUtil {
static final char[] STR = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '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' };
/**
* 数字数组
*/
static final char[] STR_NUMBER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
/**
* 小写字母数组
*/
static final char[] STR_XZM = { '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' };
/**
* 大写字母数组
*/
static final char[] STR_DZM = { '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' };
/**
* 纯数字
*/
static final int LEVEL_ONE = 1;
/**
* 小写字母加数字
*/
static final int LEVEL_TOW = 2;
/**
* 大小写字母加数字
*/
static final int LEVEL_THREE = 3;
static Random rand = new Random();
public static void main(String[] args) {
String pwd = createPassword(8, 1);
System.out.println(pwd);
}
public static String createPassword(int length, int level) {
char[] chars = new char[length];
for (int i = 0; i < length; i++) {
if (i % level == 2) {
chars[i] = randomChar(STR_DZM);
} else if (i % level == 1) {
chars[i] = randomChar(STR_XZM);
} else {
chars[i] = randomChar(STR_NUMBER);
}
}
if(LEVEL_THREE != level){
for (int i = 0; i < chars.length; i++) {
int p = rand.nextInt(i+1);
char tmp = chars[i];
chars[i] = chars[p];
chars[p] = tmp;
}
}
return new String(chars);
}
public static char randomChar(char[] str) {
// 从字符数组中随机取出 对应下标字符拼接
return str[rand.nextInt(str.length)];
}
public static String[] chars = new String[] { "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", "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" };
public static String[] base24 = new String[] {
"B", "C", "D", "F", "G",
"H", "J", "K", "M", "P",
"Q", "R", "T", "V", "W",
"X", "Y","2", "3", "4",
"6", "7", "8", "9"};
public static String generateShortUuid() {
StringBuffer shortBuffer = new StringBuffer();
String uuid = UUIDUtil.getUUID();
for (int i = 0; i < 8; i++) {
String str = uuid.substring(i * 4, i * 4 + 4);
int x = Integer.parseInt(str, 16);
shortBuffer.append(chars[x % 0x3E]);
}
return shortBuffer.toString();
}
public static String generateShortUuid(int length) {
StringBuffer shortBuffer = new StringBuffer();
for (int i = 0; i < length; i++) {
shortBuffer.append(base24[rand.nextInt(24)]);
}
return shortBuffer.toString();
}
}
package com.zrqx.core.util;
import javax.servlet.http.HttpServletRequest;
public class CusAccessObjectUtil {
/**
* 获取用户真实IP地址,不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址,
*
* 可是,如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值,究竟哪个才是真正的用户端的真实IP呢?
* 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。
*
* 如:X-Forwarded-For:192.168.1.110, 192.168.1.120, 192.168.1.130, 192.168.1.100
*
* 用户真实IP为: 192.168.1.110
*
* @param request
* @return
*/
public static String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
package com.zrqx.core.util.JsonUtil;
import java.io.IOException;
import java.io.StringWriter;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtil {
private static ObjectMapper mapper = new ObjectMapper();
@SuppressWarnings("deprecation")
public static String bean2Json(Object obj) throws IOException {
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
mapper.writeValue(gen, obj);
gen.close();
return sw.toString();
}
public static <T> T json2Bean(String jsonStr, Class<T> objClass)
throws JsonParseException, JsonMappingException, IOException {
return mapper.readValue(jsonStr, objClass);
}
}
package com.zrqx.core.util;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.ibatis.javassist.ClassClassPath;
import org.apache.ibatis.javassist.ClassPool;
import org.apache.ibatis.javassist.CtClass;
import org.apache.ibatis.javassist.CtMethod;
import org.apache.ibatis.javassist.Modifier;
import org.apache.ibatis.javassist.bytecode.CodeAttribute;
import org.apache.ibatis.javassist.bytecode.LocalVariableAttribute;
import org.apache.ibatis.javassist.bytecode.MethodInfo;
import org.aspectj.lang.ProceedingJoinPoint;
import com.zrqx.core.model.sysuser.log.Log;
import io.swagger.annotations.ApiOperation;
/**
*日志工具类
*/
public class LogUtils {
/**
* 主要在切面中调用,返回一个当前执行方法的日志记录。获取ApiOperation的value作为描述
* @param pjp
* @param annotation
* @param thisClass
* @param Account
* @param IP
* @return 设置好值的日志对象,目标方法的返回值放在result属性中
* @throws Throwable
*/
public static Log getLog(ProceedingJoinPoint pjp, ApiOperation annotation,Class thisClass , String Account, String IP) throws Throwable{
String classType = pjp.getTarget().getClass().getName();
Class<?> clazz = Class.forName(classType);
String clazzName = clazz.getName();
// 获取方法名称
String methodName = pjp.getSignature().getName();
StringBuffer resourceId =new StringBuffer();
Object[] args = pjp.getArgs();
// 获取参数名称和值
Map<String, Object> nameAndArgs = getFieldsName(thisClass, clazzName, methodName, args);
StringBuffer param = new StringBuffer();
nameAndArgs.forEach((k,v)->{
param.append("{"+ k + ":" + v + "}");
if(k.equals("id")) {
resourceId.append(v);
}
});
// 得到方法返回结果
Object o = pjp.proceed();
// 保存日志
Boolean success = true;
String resultStr = "成功";
if(o instanceof CallBack){
CallBack callBack = (CallBack) o;
if(callBack.getData() instanceof Boolean){
success = (Boolean) callBack.getData();
}
if(!success || !callBack.isStatus()){
resultStr = "失败";
}
}
Log log = new Log();
log.setCreaterAccount(Account);
log.setCreateTime(new Date());
log.setDescription(annotation.value()+ "["+param.toString()+"]" + resultStr);
log.setIp(IP);
log.setResult(o);
log.setResourceId(resourceId.toString());
log.setName(annotation.notes());
return log;
}
/**
* @Description 获取字段名和字段值
* @return Map<String,Object>
*/
public static Map<String, Object> getFieldsName(Class cls, String clazzName, String methodName, Object[] args)
throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
ClassPool pool = ClassPool.getDefault();
ClassClassPath classPath = new ClassClassPath(cls);
pool.insertClassPath(classPath);
CtClass cc = pool.get(clazzName);
CtMethod cm = cc.getDeclaredMethod(methodName);
MethodInfo methodInfo = cm.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
if (attr == null) {
return map;
// exception
}
int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
for (int i = 0; i < cm.getParameterTypes().length; i++) {
Object object = args[i];
// paramNames即参数名
map.put(attr.variableName(i + pos), ArrayUtils.toString(object));
}
return map;
}
}
package com.zrqx.core.util;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
* 二维码生成和读的工具类
*
*/
public class QrCodeCreateUtil {
private static String TYPE = "JPEG";
private static int SIZE = 300;
/**
* 生成包含字符串信息的二维码图片
*
* @param outputStream
* 文件输出流路径
* @param content
* 二维码携带信息
* @param qrCodeSize
* 二维码图片大小
* @param imageFormat
* 二维码的格式
* @throws WriterException
* @throws IOException
*/
public static boolean createQrCode(OutputStream outputStream, String content, int qrCodeSize, String imageFormat)
throws WriterException, IOException {
if(qrCodeSize < 130){
qrCodeSize = 130;
}
// 设置二维码纠错级别MAP
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); // 矫错级别
QRCodeWriter qrCodeWriter = new QRCodeWriter();
// 创建比特矩阵(位矩阵)的QR码编码的字符串
BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap);
// 使BufferedImage勾画QRCode (matrixWidth 是行二维码像素点)
int matrixWidth = byteMatrix.getWidth();
BufferedImage image = new BufferedImage(matrixWidth - 50, matrixWidth - 50, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, matrixWidth, matrixWidth);
// 使用比特矩阵画并保存图像
graphics.setColor(Color.BLACK);
for (int i = 0; i < matrixWidth; i++) {
for (int j = 0; j < matrixWidth; j++) {
if (byteMatrix.get(i, j)) {
graphics.fillRect(i-25, j-25, 1, 1);
}
}
}
return ImageIO.write(image, imageFormat, outputStream);
}
public static boolean createQrCode(OutputStream outputStream, String content, int qrCodeSize)
throws WriterException, IOException {
return createQrCode(outputStream, content, qrCodeSize, TYPE);
}
public static boolean createQrCode(OutputStream outputStream, String content, String imageFormat)
throws WriterException, IOException {
return createQrCode(outputStream, content, SIZE, imageFormat);
}
public static boolean createQrCode(OutputStream outputStream, String content) throws WriterException, IOException {
return createQrCode(outputStream, content, SIZE, TYPE);
}
public static boolean createQrCode(String file, String content) throws WriterException, IOException {
return createQrCode(new FileOutputStream(new File(file)), content, SIZE, TYPE);
}
public static boolean createQrCode(File file, String content) throws WriterException, IOException {
return createQrCode(new FileOutputStream(file), content, SIZE, TYPE);
}
/**
* 读二维码并输出携带的信息
*/
public static String readQrCode(InputStream inputStream) throws IOException {
// 从输入流中获取字符串信息
BufferedImage image = ImageIO.read(inputStream);
// 将图像转换为二进制位图源
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
QRCodeReader reader = new QRCodeReader();
Result result = null;
try {
result = reader.decode(bitmap);
} catch (ReaderException e) {
e.printStackTrace();
}
return result.getText();
}
/**
* 测试代码
*
* @throws WriterException
*/
public static void main(String[] args) throws IOException, WriterException {
createQrCode(new FileOutputStream(new File("d:\\qrcode.jpg")), "WE11111111111111111111111111111111111111111111");
readQrCode(new FileInputStream(new File("d:\\qrcode.jpg")));
}
}
\ No newline at end of file
package com.zrqx.core.util;
/**
* 字符串的一些公共方法
* @ClassName: StringUtils
* @author
* @date 2014-7-14 上午11:14:00
*
*/
public class StringUtils {
private final static String[] agent = { "Android", "iPhone", "iPod","iPad", "Windows Phone", "MQQBrowser" };
private final static String[] enletters = {"a","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","t","u","v","w","x","y","z"};
/**
* 判断User-Agent 是不是来自于手机
* @param ua
* @return
*/
public static boolean checkAgentIsMobile(String ua) {
boolean flag = false;
if (!ua.contains("Windows NT") || (ua.contains("Windows NT") && ua.contains("compatible; MSIE 9.0;"))) {
// 排除 苹果桌面系统
if (!ua.contains("Windows NT") && !ua.contains("Macintosh")) {
for (String item : agent) {
if (ua.contains(item)) {
flag = true;
break;
}
}
}
}
return flag;
}
/**
* 给定指定字符串res,去除字符串首尾的指定字符c
* @Title: trim
* @param res 原字符串
* @param c 要删除的字符,只删除首尾,且不能截取Unicode 大于 'A'的字符
* @return
* @return String 返回类型
* @author
* @date 2014-7-14 上午11:21:21
*/
public static String trim(String res,char c) {
int count = res.toCharArray().length;
int len = res.toCharArray().length;
int st = 0;
int off = 0; /* avoid getfield opcode */
char[] val = res.toCharArray(); /* avoid getfield opcode */
while ((st < len) && (val[off + st] <= c)) {
st++;
}
while ((st < len) && (val[off + len - 1] <= c)) {
len--;
}
return ((st > 0) || (len < count)) ? res.substring(st, len) : res;
}
/**
* 获取setter方法名称
* @Title: getSetterMethodName
* @param key
* @return
* @return String 返回类型
* @author
* @date 2014年7月24日 下午3:43:22
*/
public static String getMethodName(String begin,String key) {
StringBuilder result = new StringBuilder(begin);
result.append(key.substring(0,1).toUpperCase()).append(key.substring(1));
return result.toString();
}
/**
* 获取随机英文字符串
* @param caseType 1大写,其他小写
* @param length 返回字符串长度
* @param hasRepeat 是否包含重复字符 1包含0不包含
* @return
* @author ydm
* @date: 2018年7月11日 上午11:33:25
*/
public static String getRandomEnSign(int caseType,int length,int hasRepeat){
StringBuffer resultBuffer = new StringBuffer();
for(int i = 0 ; i < length ; i ++ ){
int x=1+(int)(Math.random()*enletters.length-1);
if(hasRepeat * 1 == 0){
if(resultBuffer.toString().toLowerCase().indexOf(enletters[x].toLowerCase())>0){
continue;
}
}
resultBuffer.append(caseType*1==1 ? enletters[x].toUpperCase() : enletters[x].toLowerCase());
}
return resultBuffer.toString();
}
}
package com.zrqx.core.util;
import java.util.UUID;
import com.zrqx.core.exception.BaseException;
public class UUIDUtil {
/**
* 获得指定数目的UUID
*
* @param number
* int 需要获得的UUID数量
* @return String[] UUID数组
*/
public static String[] getUUID(int number) {
if (number < 1) {
return null;
}
String[] retArray = new String[number];
for (int i = 0; i < number; i++) {
retArray[i] = getUUID();
}
return retArray;
}
/**
* 获得一个UUID
*
* @return String UUID
*/
public static String getUUID() {
String uuid = UUID.randomUUID().toString();
// 去掉“-”符号
return uuid.replaceAll("-", "");
}
/**
* 有序生成代号
* @param code
* @return
*/
public static String newCode(String code){
if(code != null){
Integer numCode = Integer.parseInt(code.substring(code.length()-2, code.length()));
numCode+=1;
code = code.substring(0, code.length()-2);
if((numCode+"").length()==2){
return code + "" + numCode;
}else{
return code + "0" + numCode + "";
}
}else{
throw new BaseException("同级子分类 分类编号 为空,无法自动生成分类编号。");
}
}
}
package com.zrqx.core.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
/**
* 图形验证码生成
*/
public class VerifyUtil {
// 验证码字符集
private static final char[] chars = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'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'};
// 字符数量
private static final int SIZE = 4;
// 干扰线数量
private static final int LINES = 5;
// 宽度
private static final int WIDTH = 80;
// 高度
private static final int HEIGHT = 40;
// 字体大小
private static final int FONT_SIZE = 30;
/**
* 生成随机验证码及图片
* Object[0]:验证码字符串;
* Object[1]:验证码图片。
*/
public static Object[] createImage() {
StringBuffer sb = new StringBuffer();
// 1.创建空白图片
BufferedImage image = new BufferedImage(
WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
// 2.获取图片画笔
Graphics graphic = image.getGraphics();
// 3.设置背景颜色
graphic.setColor(Color.WHITE);
// 4.绘制矩形背景
graphic.fillRect(0, 0, WIDTH, HEIGHT);
// 5.画随机字符
Random ran = new Random();
for (int i = 0; i <SIZE; i++) {
// 取随机字符索引
int n = ran.nextInt(chars.length);
// 随机设置画笔颜色
graphic.setColor(getRandomColor());
// 设置字体大小
graphic.setFont(new Font(
null, Font.BOLD + Font.ITALIC, FONT_SIZE));
// 画字符
graphic.drawString(
chars[n] + "", i * WIDTH / SIZE, HEIGHT*2/3);
// 记录字符
sb.append(chars[n]);
}
// 6.画干扰线
for (int i = 0; i < LINES; i++) {
// 设置随机颜色
graphic.setColor(getRandomColor());
// 随机画线
graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT),
ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
}
// 7.返回验证码和图片
return new Object[]{sb.toString(), image};
}
/**
* 随机取色
*/
public static Color getRandomColor() {
Random ran = new Random();
Color color = new Color(ran.nextInt(256),
ran.nextInt(256), ran.nextInt(256));
return color;
}
public static void main(String[] args) throws IOException {
Object[] objs = createImage();
BufferedImage image = (BufferedImage) objs[1];
OutputStream os = new FileOutputStream("d:/1.png");
ImageIO.write(image, "png", os);
os.close();
}
}
\ No newline at end of file
package com.zrqx.core.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class WeekEveryDay {
static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
public static String getTimeInterval(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
// 判断要计算的日期是否是周日,如果是则减一天计算周六的,否则会出问题,计算到下一周去了
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
if (1 == dayWeek) {
cal.add(Calendar.DAY_OF_MONTH, -1);
}
// System.out.println("要计算日期为:" + sdf.format(cal.getTime())); // 输出要计算日期
// 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
cal.setFirstDayOfWeek(Calendar.MONDAY);
// 获得当前日期是一个星期的第几天
int day = cal.get(Calendar.DAY_OF_WEEK);
// 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
String imptimeBegin = sdf.format(cal.getTime());
// System.out.println("所在周星期一的日期:" + imptimeBegin);
cal.add(Calendar.DATE, 6);
String imptimeEnd = sdf.format(cal.getTime());
// System.out.println("所在周星期日的日期:" + imptimeEnd);
return imptimeBegin + "," + imptimeEnd;
}
public String getLastTimeInterval() {
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
int dayOfWeek = calendar1.get(Calendar.DAY_OF_WEEK) - 1;
int offset1 = 1 - dayOfWeek;
int offset2 = 7 - dayOfWeek;
calendar1.add(Calendar.DATE, offset1 - 7);
calendar2.add(Calendar.DATE, offset2 - 7);
// System.out.println(sdf.format(calendar1.getTime()));// last Monday
String lastBeginDate = sdf.format(calendar1.getTime());
// System.out.println(sdf.format(calendar2.getTime()));// last Sunday
String lastEndDate = sdf.format(calendar2.getTime());
return lastBeginDate + "," + lastEndDate;
}
public static List<Date> findDates(Date dBegin, Date dEnd)
{
List lDate = new ArrayList();
lDate.add(dBegin);
Calendar calBegin = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
calBegin.setTime(dBegin);
Calendar calEnd = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
calEnd.setTime(dEnd);
// 测试此日期是否在指定日期之后
while (dEnd.after(calBegin.getTime()))
{
// 根据日历的规则,为给定的日历字段添加或减去指定的时间量
calBegin.add(Calendar.DAY_OF_MONTH, 1);
lDate.add(calBegin.getTime());
}
return lDate;
}
public static List<Date> weekDate() {
String yz_time = getTimeInterval(new Date());//获取本周时间
String array[]=yz_time.split(",");
String start_time=array[0];//本周第一天
String end_time=array[1]; //本周最后一天
//格式化日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dBegin = null;
try {
dBegin = sdf.parse(start_time);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Date dEnd = null;
try {
dEnd = sdf.parse(end_time);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<Date> SDate = findDates(dBegin, dEnd);//获取这周所有date
/* for (Date date : lDate)
{
System.out.println(sdf.format(date));
}*/
return SDate;
}
}
package com.zrqx.core.util.download;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
public class DownloadUtil {
/**
* 默认每次读取长度
*/
private static final int length = 2*1024;
/**
* 设置响应头,并把文件写入response
* @param response 响应对象
* @param file 要下载的文件
* @param fileName 下载后文件的名称
* @param length 每次读取长度
* @throws Exception
*/
public static void start(HttpServletResponse response,File file,String fileName,int length) throws Exception {
setResponse(response,file,fileName);
readWrite(response.getOutputStream(),file,length);
}
/**
* 设置响应头,并把文件写入response
* @param response 响应对象
* @param file 要下载的文件
* @param fileName 下载后文件的名称
* @throws Exception
*/
public static void start(HttpServletResponse response,File file,String fileName) throws Exception {
start(response,file,fileName,length);
}
/**
* 设置响应头,并把文件写入response
* @param response 响应对象
* @param filePath 要下载的文件路径
* @param fileName 下载后文件的名称
* @throws Exception
*/
public static void start(HttpServletResponse response,String filePath,String fileName) throws Exception {
start(response,new File(filePath),fileName,length);
}
/**
* 设置响应头,并把文件写入response
* @param response 响应对象
* @param file 要下载的文件
* @param fileName 下载后文件的名称
* @throws Exception
*/
public static void startOpen(HttpServletResponse response,String filePath) throws Exception {
startOpen(response,new File(filePath));
}
/**
* 设置响应头,并把文件写入response
* @param response 响应对象
* @param filePath 要下载的文件路径
* @param fileName 下载后文件的名称
* @throws Exception
*/
public static void startOpen(HttpServletResponse response,File file) throws Exception {
setOpenResponse(response,file);
readWrite(response.getOutputStream(),file,length);
}
/**
* 设置响应头
* @param response 响应对象
* @param file 要下载的文件
* @param fileName 下载后文件的名称
* @throws Exception
*/
public static void setResponse(HttpServletResponse response,File file,String fileName) throws Exception {
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
}
/**
* 设置响应头
* @param response 响应对象
* @param file 要打开的文件
* @throws Exception
*/
public static void setOpenResponse(HttpServletResponse response,File file) throws Exception {
URL u = new URL("file:///" + file.getPath());
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename=" + file.getName());
}
/**
* 设置响应头
* @param response 响应对象
* @param filePath 要下载的文件路径
* @param fileName 下载后文件的名称
* @throws Exception
*/
public static void setResponse(HttpServletResponse response,String filePath,String fileName) throws Exception {
setResponse(response,new File(filePath),fileName);
}
/**
* 读写文件
* @param out 文件输出流
* @param file 要读取的文件
*/
public static void readWrite(OutputStream out, File file) {
readWrite(out, file,length);
}
/**
* 读写文件
* @param out 文件输出流
* @param file 要读取的文件
* @param length 每次读取长度
*/
public static void readWrite(OutputStream out, File file,int length) {
byte[] buffer = new byte[length];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
// 文件输入流
bis = new BufferedInputStream(fis);
// 输出流
while (-1 != bis.read(buffer)) {
out.write(buffer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != fis)
fis.close();
if (null != bis)
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.zrqx.core.util.erweima;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
* 二维码生成和读的工具类
*
*/
public class QrCodeCreateUtil {
private static String TYPE = "JPEG";
private static int SIZE = 300;
/**
* 生成包含字符串信息的二维码图片
*
* @param outputStream
* 文件输出流路径
* @param content
* 二维码携带信息
* @param qrCodeSize
* 二维码图片大小
* @param imageFormat
* 二维码的格式
* @throws WriterException
* @throws IOException
*/
public static boolean createQrCode(OutputStream outputStream, String content, int qrCodeSize, String imageFormat)
throws WriterException, IOException {
if(qrCodeSize < 130){
qrCodeSize = 130;
}
// 设置二维码纠错级别MAP
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); // 矫错级别
QRCodeWriter qrCodeWriter = new QRCodeWriter();
// 创建比特矩阵(位矩阵)的QR码编码的字符串
BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap);
// 使BufferedImage勾画QRCode (matrixWidth 是行二维码像素点)
int matrixWidth = byteMatrix.getWidth();
BufferedImage image = new BufferedImage(matrixWidth - 50, matrixWidth - 50, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, matrixWidth, matrixWidth);
// 使用比特矩阵画并保存图像
graphics.setColor(Color.BLACK);
for (int i = 0; i < matrixWidth; i++) {
for (int j = 0; j < matrixWidth; j++) {
if (byteMatrix.get(i, j)) {
graphics.fillRect(i-25, j-25, 1, 1);
}
}
}
boolean flag = ImageIO.write(image, imageFormat, outputStream);
outputStream.close();
return flag;
}
/**
* 生成包含字符串信息的二维码图片
*
* @param outputStream
* 文件输出流路径
* @param content
* 二维码携带信息
* @param qrCodeSize
* 二维码图片大小
* @throws WriterException
* @throws IOException
*/
public static boolean createQrCode(OutputStream outputStream, String content, int qrCodeSize)
throws WriterException, IOException {
return createQrCode(outputStream, content, qrCodeSize, TYPE);
}
/**
* 生成包含字符串信息的二维码图片
*
* @param outputStream
* 文件输出流路径
* @param content
* 二维码携带信息
* @param imageFormat
* 二维码的格式
* @throws WriterException
* @throws IOException
*/
public static boolean createQrCode(OutputStream outputStream, String content, String imageFormat)
throws WriterException, IOException {
return createQrCode(outputStream, content, SIZE, imageFormat);
}
/**
* 生成包含字符串信息的二维码图片
*
* @param outputStream
* 文件输出流路径
* @param content
* 二维码携带信息
* @throws WriterException
* @throws IOException
*/
public static boolean createQrCode(OutputStream outputStream, String content) throws WriterException, IOException {
return createQrCode(outputStream, content, SIZE, TYPE);
}
/**
* 生成包含字符串信息的二维码图片
*
* @param filePath
* 文件输出路径
* @param content
* 二维码携带信息
* @throws WriterException
* @throws IOException
*/
public static boolean createQrCode(String filePath, String content) throws WriterException, IOException {
return createQrCode(new FileOutputStream(new File(filePath)), content, SIZE, TYPE);
}
/**
* 生成包含字符串信息的二维码图片
*
* @param file
* 文件
* @param content
* 二维码携带信息
* @throws WriterException
* @throws IOException
*/
public static boolean createQrCode(File file, String content) throws WriterException, IOException {
return createQrCode(new FileOutputStream(file), content, SIZE, TYPE);
}
/**
* 读二维码并输出携带的信息
*/
public static String readQrCode(InputStream inputStream) throws IOException {
// 从输入流中获取字符串信息
BufferedImage image = ImageIO.read(inputStream);
// 将图像转换为二进制位图源
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
QRCodeReader reader = new QRCodeReader();
Result result = null;
try {
result = reader.decode(bitmap);
return result.getText();
} catch (ReaderException e) {
e.printStackTrace();
}
return null;
}
/**
* 测试代码
*
* @throws WriterException
*/
public static void main(String[] args) throws IOException, WriterException {
createQrCode(new FileOutputStream(new File("d:\\qrcode.jpg")), "WE11111111111111111111111111111111111111111111");
readQrCode(new FileInputStream(new File("d:\\qrcode.jpg")));
}
}
\ No newline at end of file
package com.zrqx.core.util.qiyu;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import com.zrqx.core.model.third.qiyu.Datas;
/**
* 集合类型属性 解析
* @author lpf
* @date 2018年12月12日上午11:02:32
*/
public class ListTypeImpl extends ProperyTypeAdapter{
/**
* 获取t中的f属性 转换为 Datas对象
* 排序 累加 f属性的排序 + f属性对应的对象的 属性 排序
* @param t
* @param f
* @return
* @author lpf
* @date: 2018年12月12日 上午10:54:38
*/
@Override
public <T> List<Datas> getDatas(T t, Field f) {
Datas d = properyToDatas(t, f);
Object o = d.getValue();
if (o != null && o instanceof Collection) {
Collection<?> coll = (Collection<?>) o;
List<List<Datas>> result = new ArrayList<>(coll.size());
Iterator<?> iter = coll.iterator();
// 排序累加
int index = d.getIndex();
while(iter.hasNext()) {
Object p = iter.next();
List<Datas> list = PropertyUtils.getDatas(p);
for (Datas v : list) {
v.setIndex(v.getIndex() + index);
}
// 排序累加的步长为
index += list.size();
result.add(list);
}
return result.stream().flatMap(List :: stream).collect(Collectors.toList());
} else {
List<Datas> list = new ArrayList<>();
list.add(d);
return list;
}
}
/**
* 单例模式 懒汉式加载
*/
private ListTypeImpl(){}
public static ListTypeImpl getInstance(){
return ListTypeImplHolder.LAZY_DEMO3;
}
private static class ListTypeImplHolder{
private static final ListTypeImpl LAZY_DEMO3 = new ListTypeImpl();
}
}
package com.zrqx.core.util.qiyu;
import java.lang.reflect.Field;
import java.util.List;
import com.zrqx.core.annotation.DatasBean;
import com.zrqx.core.model.third.qiyu.Datas;
/**
* 类对象解析属性
* @author lpf
* @date 2018年12月12日上午11:03:01
*/
public class ObjectTypeImpl extends ProperyTypeAdapter{
/**
* 获取t中的f属性 转换为 Datas对象
* @param t
* @param f
* @return
* @author lpf
* @date: 2018年12月12日 上午10:54:38
*/
@Override
public <T> List<Datas> getDatas(T t, Field f) {
Datas d = properyToDatas(t, f);
Object o = d.getValue();
// 解析该对象
List<Datas> list = PropertyUtils.getDatas(o);
list.forEach(v -> {
v.setIndex(d.getIndex() + v.getIndex());
});
return list;
}
/**
* 单例模式 懒汉式加载
*/
private ObjectTypeImpl(){}
public static ObjectTypeImpl getInstance(){
return ObjectTypeImplHolder.LAZY_DEMO3;
}
private static class ObjectTypeImplHolder{
private static final ObjectTypeImpl LAZY_DEMO3 = new ObjectTypeImpl();
}
}
package com.zrqx.core.util.qiyu;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zrqx.core.annotation.DatasBean;
import com.zrqx.core.enums.ProperyTypeEnum;
import com.zrqx.core.model.third.qiyu.Blocks;
import com.zrqx.core.model.third.qiyu.Datas;
import com.zrqx.core.util.BeanUtils;
public class PropertyUtils {
private final static Logger logger = LoggerFactory.getLogger(PropertyUtils.class);
/**
* 获取t中的带有DatasBean 注解的属性 转换为 Datas对象 转换为 Blocks对象
* @param t
* @return
* @author lpf
* @date: 2018年12月11日 下午8:07:43
*/
public static <T> List<Blocks> get(T t){
List<Datas> list = getDatas(t);
Map<Boolean, List<Datas>> map = list.stream().collect(Collectors.groupingBy(Datas :: getTitleFlag));
List<Blocks> result = map.keySet().stream().map((k) -> {
Blocks b = new Blocks();
if (k) {
b.setIndex(0);
} else {
b.setIndex(1);
}
b.setIs_title(k);
b.setData(map.get(k));
return b;
}).collect(Collectors.toList());
return result;
}
/**
* 获取t中的带有DatasBean 注解的属性 转换为 Datas对象
* @param t
* @return
* @author lpf
* @date: 2018年12月11日 下午8:03:22
*/
public static <T> List<Datas> getDatas(T t){
if (t == null) return null;
Class<?> clazz = t.getClass();
Stream<Field> stream = BeanUtils.getFieldsByAnnotation(clazz,
(Field f) -> f.getAnnotation(DatasBean.class) != null);
List<Datas> result = stream.map(f -> {
try {
DatasBean bean = f.getAnnotation(DatasBean.class);
ProperyTypeEnum proEnum = bean.type();
/**
* 类型调用
*/
return proEnum.getInterfaces().getDatas(t, f);
} catch (Exception e) {
e.printStackTrace();
logger.warn("获取属性值失败"+ clazz + "对象:" + t.toString() + "属性:" + f.getName());
}
return new ArrayList<Datas>();
}).flatMap(List :: stream).sorted(Comparator.comparing(Datas :: getIndex)).collect(Collectors.toList());
return result;
}
}
package com.zrqx.core.util.qiyu;
import java.lang.reflect.Field;
import org.apache.commons.lang3.StringUtils;
import com.zrqx.core.annotation.DatasBean;
import com.zrqx.core.model.third.qiyu.Datas;
public abstract class ProperyTypeAdapter implements ProperyTypeInterface{
/**
* 工具方法
* 将基本类型属性转换为Datas对象
* @param f
* @return
* @author lpf
* @date: 2018年12月12日 上午10:04:30
*/
protected <T> Datas properyToDatas(T t,Field f) {
DatasBean bean = f.getAnnotation(DatasBean.class);
Datas d = new Datas();
if (StringUtils.isNotBlank(bean.key())) {
d.setKey(bean.key());
} else {
d.setKey(f.getName());
}
d.setLabel(bean.label());
d.setIndex(bean.index());
d.setHref(bean.href());
d.setEdit(bean.edit());
d.setMap(bean.map());
d.setSave(bean.save());
d.setZone(bean.zone());
d.setSelect(bean.select());
d.setCheck(bean.check());
d.setTitleFlag(bean.isTitle());
try {
d.setValue(f.get(t));
} catch (Exception e) {
e.printStackTrace();
}
return d;
}
}
package com.zrqx.core.util.qiyu;
import java.lang.reflect.Field;
import java.util.List;
import com.zrqx.core.model.third.qiyu.Datas;
/**
* 属性类型解析接口
* @author lpf
* @date 2018年12月12日上午9:48:57
*/
public interface ProperyTypeInterface {
/**
* 获取t中的f属性 转换为 Datas对象
* @param t
* @param f
* @return
* @author lpf
* @date: 2018年12月12日 上午10:54:38
*/
<T> List<Datas> getDatas(T t, Field f);
}
package com.zrqx.core.util.qiyu;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import com.zrqx.core.model.third.qiyu.Datas;
/**
* 基础类型 属性转换 Datas
* @author lpf
* @date 2018年12月12日上午10:24:05
*/
public class SimpleTypeImpl extends ProperyTypeAdapter {
/**
* 解析属性
* 获取t对象的f属性 转换为List<Datas>
* @param t
* @param f
* @return
* @author lpf
* @date: 2018年12月12日 上午10:18:33
*/
@Override
public <T> List<Datas> getDatas(T t, Field f) {
Datas d = properyToDatas(t, f);
List<Datas> list = new ArrayList<>();
list.add(d);
return list;
}
/**
* 单例模式 懒汉式加载
*/
private SimpleTypeImpl(){}
public static SimpleTypeImpl getInstance(){
return SimpleTypeImplHolder.LAZY_DEMO3;
}
private static class SimpleTypeImplHolder{
private static final SimpleTypeImpl LAZY_DEMO3 = new SimpleTypeImpl();
}
}
package com.zrqx.core.util.zip;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import com.zrqx.core.model.file.FileInfo;
import com.zrqx.core.util.UUIDUtil;
public class ZipUtil {
/**
*
* @param zipFileName
* 目的地Zip文件
* @param sourceFileName
* 源文件(待压缩的文件或文件夹)
* @throws Exception
*/
public static void zip(String zipFileName, String sourceFileName) throws Exception {
// File zipFile = new File(zipFileName);
System.out.println("压缩中...");
// 创建zip输出流
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName)));
File sourceFile = new File(sourceFileName);
// 调用函数
compress(out, sourceFile, sourceFile.getName());
out.close();
System.out.println("压缩完成");
}
/**
*
* @param rootPath 文件要压缩到的文件夹
* @param list 要压缩的文件对象
* @return String 文件路径
* @throws Exception
*/
public static String zip(String rootPath, List<FileInfo> list) throws Exception {
// File zipFile = new File(zipFileName);
System.out.println("压缩中...");
String zipFileName = rootPath + UUIDUtil.getUUID() + ".zip";
// 创建zip输出流
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName)));
for (FileInfo file : list) {
String filePath = rootPath + file.getPath() + "/" + file.getFileName() + file.getSuffixName();
File sourceFile = new File(filePath);
compress(out, sourceFile, sourceFile.getName());
}
out.close();
System.out.println("压缩完成");
return zipFileName;
}
public static void compress(ZipOutputStream out, File sourceFile, String base) throws Exception {
// 如果路径为目录(文件夹)
if (sourceFile.isDirectory()) {
// 取出文件夹中的文件(或子文件夹)
File[] flist = sourceFile.listFiles();
if (flist == null || flist.length == 0) {// 如果文件夹为空,则只需在目的地zip文件中写入一个目录进入点
out.putNextEntry(new ZipEntry(base + "/"));
} else {// 如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩
for (int i = 0; i < flist.length; i++) {
compress(out, flist[i], base + "/" + flist[i].getName());
}
}
} else {// 如果不是目录(文件夹),即为文件,则先写入目录进入点,之后将文件写入zip文件中
out.putNextEntry(new ZipEntry(base));
FileInputStream fos = new FileInputStream(sourceFile);
BufferedInputStream bis = new BufferedInputStream(fos);
int tag;
// 将源文件写入到zip文件中
while ((tag = bis.read()) != -1) {
out.write(tag);
}
bis.close();
fos.close();
}
}
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论