我们发布啦

This commit is contained in:
张乐
2020-08-13 16:12:57 +08:00
parent a3e1c38d27
commit c0cec49f41
1885 changed files with 376936 additions and 2 deletions

View File

@@ -0,0 +1,742 @@
package com.utils;
import com.alibaba.fastjson.JSONObject;
import com.constants.Constants;
import com.exception.CrmebException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.Security;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author stivepeim
* @title: CrmebUtil
* @projectName crmeb
* @Description: 工具类
* @since 2020/4/1414:37
*/
public class CrmebUtil {
public static String encryptPassword(String pwd, String key){
try {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
Key _key = getDESSercretKey(key);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, _key);
byte[] data = pwd.getBytes(StandardCharsets.UTF_8);
byte[] result = cipher.doFinal(data);
return new sun.misc.BASE64Encoder().encode(result);
}catch (Exception e){
throw new CrmebException("密码处理异常");
}
}
/**
* 解密密码
*/
public static String decryptPassowrd(String pwd, String key)
throws Exception {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
Key aKey = getDESSercretKey(key);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, aKey);
byte[] data = new sun.misc.BASE64Decoder().decodeBuffer(pwd);
byte[] result = cipher.doFinal(data);
return new String(result, StandardCharsets.UTF_8);
}
/**
* 获得DES加密秘钥
* @param key
* @return
* @throws UnsupportedEncodingException
*/
public static SecretKey getDESSercretKey(String key) throws UnsupportedEncodingException {
byte[] result = new byte[8];
byte[] keys = null;
keys = key.getBytes(StandardCharsets.UTF_8);
for(int i = 0; i<8;i++){
if(i < keys.length){
result[i] = keys[i];
}else{
result[i] = 0x01;
}
}
return new SecretKeySpec(result, "DES");
}
/**
* 对象转map
* @param object 对象
* @author Mr.Zhang
* @since 2020-04-14
* @return Map
*/
public static Map objectToMap(Object object){
return JSONObject.parseObject(JSONObject.toJSONString(object), Map.class);
}
public static Map StringToMap(String strValue){
return JSONObject.parseObject(strValue, HashMap.class);
}
/**
* map转对象
* @param map map
* @param clz 对象
* @author Mr.Zhang
* @since 2020-04-14
* @return Map
*/
public static <T> T mapToObj(HashMap<String,Object> map, Class<T> clz){
if (map == null) return null;
return JSONObject.parseObject(JSONObject.toJSONString(map), clz);
}
/**
* map转对象
* @param map map
* @param clz 对象
* @author Mr.Zhang
* @since 2020-04-14
* @return Map
*/
public static <T> T mapStringToObj(HashMap<String,String> map, Class<T> clz){
if (map == null) return null;
return JSONObject.parseObject(JSONObject.toJSONString(map), clz);
}
/**
* 密码工具
* @param args String[] 字符串数组
*/
public static void main(String[] args) throws Exception {
System.out.println(encryptPassword("123456", "admin"));
// System.out.println(decryptPassowrd("L8qdg72wbeQ=", "admin"));
}
/**
* map合并
* @param map 对象
* @author Mr.Zhang
* @since 2020-04-14
* @return Object
*/
public static Map<String, Object> mergeMap(Map<String, Object> map, Map<String, Object> map1){
HashMap<String, Object> map2 = new HashMap<>();
map2.putAll(map);
map2.putAll(map1);
return map2;
}
/**
* 字符串分割,转化为数组
* @param str 字符串
* @author Mr.Zhang
* @since 2020-04-22
* @return List<Integer>
*/
public static List<Integer> stringToArray(String str){
return stringToArrayByRegex(str, ",");
}
/**
* 字符串分割,转化为数组
* @param str 字符串
* @param regex 分隔符有
* @author Mr.Zhang
* @since 2020-04-22
* @return List<Integer>
*/
public static List<Integer> stringToArrayByRegex(String str, String regex ){
List<Integer> list = new ArrayList<>();
if (str.contains(regex)){
String[] split = str.split(regex);
for (String value : split) {
if(!StringUtils.isBlank(value)){
list.add(Integer.parseInt(value.trim()));
}
}
}else {
list.add(Integer.parseInt(str));
}
return list;
}
/**
* 字符串分割,转化为数组
* @param str 字符串
* @author Mr.Zhang
* @since 2020-04-22
* @return List<String>
*/
public static List<String> stringToArrayStr(String str){
return stringToArrayStrRegex(str, ",");
}
/**
* 数字字符数据转int格式数据
* @param str 待转换的数字字符串
* @return int数组
*/
public static List<Integer> stringToArrayInt(String str){
List<String> strings = stringToArrayStrRegex(str, ",");
List<Integer> ids = new ArrayList<>();
for (String string : strings) {
ids.add(Integer.parseInt(string));
}
return ids;
}
/**
* 字符串分割,转化为数组
* @param str 字符串
* @param regex 分隔符有
* @author Mr.Zhang
* @since 2020-04-22
* @return List<String>
*/
public static List<String> stringToArrayStrRegex(String str, String regex ){
List<String> list = new ArrayList<>();
if (str.contains(regex)){
String[] split = str.split(regex);
for (String value : split) {
if(!StringUtils.isBlank(value)){
list.add(value);
}
}
}else {
list.add(str);
}
return list;
}
/**
* 字符串分割,转化为数组
* @param str 字符串
* @author Mr.Zhang
* @since 2020-04-22
* @return List<Object>
*/
public static List<Object> stringToArrayObject(String str){
return stringToArrayObjectRegex(str, ",");
}
/**
* 字符串分割,转化为数组
* @param str 字符串
* @param regex 分隔符有
* @author Mr.Zhang
* @since 2020-04-22
* @return List<Object>
*/
public static List<Object> stringToArrayObjectRegex(String str, String regex ){
List<Object> list = new ArrayList<>();
if (str.contains(regex)){
String[] split = str.split(regex);
for (String value : split) {
if(!StringUtils.isBlank(value)){
list.add(value);
}
}
}else {
list.add(str);
}
return list;
}
/**
* json字符串转数组
* @param str 字符串
* @author Mr.Zhang
* @since 2020-04-22
* @return List<String>
*/
public static List<String> jsonToListString(String str){
try{
return JSONObject.parseArray(str).toJavaList(String.class);
}catch (Exception e){
ArrayList<String> list = new ArrayList<>();
list.add(str);
return list;
}
}
/**
* json字符串转数组
* @param str 字符串
* @author Mr.Zhang
* @since 2020-04-22
* @return List<Integer>
*/
public static List<Integer> jsonToListInteger(String str){
try{
return JSONObject.parseArray(str).toJavaList(Integer.class);
}catch (Exception e){
ArrayList<Integer> list = new ArrayList<>();
list.add(Integer.parseInt(str));
return list;
}
}
/**
* json字符串转数组
* @param str 字符串
* @author Mr.Zhang
* @since 2020-04-22
* @return List<Integer>
*/
public static List<Object> jsonToListObject(String str){
try{
return JSONObject.parseArray(str).toJavaList(Object.class);
}catch (Exception e){
ArrayList<Object> list = new ArrayList<>();
list.add(str);
return list;
}
}
/**
* json字符串转数组
* @param str 字符串
* @author Mr.Zhang
* @since 2020-04-22
* @return List<T>
*/
public static <T> List<T> jsonToListClass(String str, Class<T> cls){
try{
return JSONObject.parseArray(str, cls);
}catch (Exception e){
return new ArrayList<>();
}
}
/**
* 去掉域名 https / http / www 信息
* @param domain 域名
* @author Mr.Zhang
* @since 2020-04-22
* @return String
*/
public static String getCleanLowerDomain(String domain){
domain = domain.toLowerCase();
domain = domain.replaceAll("http://", "");
domain = domain.replaceAll("https://", "");
domain = domain.replaceAll("www.", "");
domain = domain.replaceAll("/", "");
return domain;
}
/**
* 获取根域名
* @param domain 域名
* @author Mr.Zhang
* @since 2020-04-22
* @return String
*/
public static String getBaseLowerDomain(String domain){
if(!domain.contains(".")){
domain += ".com";
}
domain = getCleanLowerDomain(domain);
String[] split = domain.split("\\.");
int len = split.length;
if(len == 0){
return domain;
}
return split[len - 2] + "." + split[len - 1];
}
/**
* 获取客户端ip
* @param request 参数
* @author Mr.Zhang
* @since 2020-04-22
* @return String
*/
public static String getClientIp(HttpServletRequest request){
String ip = request.getHeader("X-Forwarded-For");
if(checkIsIp(ip)){
return ip;
}
ip = request.getHeader("X-Real-IP");
if(checkIsIp(ip)){
return ip;
}
ip = request.getRemoteAddr();
if(ip.equals("0:0:0:0:0:0:0:1")){
//本地 localhost访问 ipv6
ip = "127.0.0.1";
}
if(checkIsIp(ip)){
return ip;
}
return "";
}
/**
* 检测是否为ip
* @param ip 参数
* @author Mr.Zhang
* @since 2020-04-22
* @return String
*/
public static boolean checkIsIp(String ip){
if(StringUtils.isBlank(ip)){
return false;
}
if(ip.equals("unKnown")){
return false;
}
if(ip.equals("unknown")){
return false;
}
return ip.split("\\.").length == 4;
}
/**
* 获取fin_in_set拼装sql
* @param field String 字段
* @param value Integer 值
* @author Mr.Zhang
* @since 2020-04-22
* @return String
*/
public static String getFindInSetSql(String field, Integer value ){
return "find_in_set(" + value +", " + field + ")";
}
/**
* 获取fin_in_set拼装sql
* @param field String 字段
* @param list ArrayList<Integer> 值
* @author Mr.Zhang
* @since 2020-04-22
* @return String
*/
public static String getFindInSetSql(String field, ArrayList<Integer> list ){
ArrayList<String> sqlList = new ArrayList<>();
for (Integer value: list) {
sqlList.add(getFindInSetSql(field, value));
}
return "( " + StringUtils.join(sqlList, " or ") + ")";
}
/**
* 获取fin_in_set拼装sql
* @param field String 字段
* @param idStr String 多个值,逗号分割
* @author Mr.Zhang
* @since 2020-04-22
* @return String
*/
public static String getFindInSetSql(String field, String idStr ){
List<Integer> list = stringToArray(idStr);
ArrayList<String> sqlList = new ArrayList<>();
for (Integer value: list) {
sqlList.add(getFindInSetSql(field, value));
}
return "( " + StringUtils.join(sqlList, " or ") + ")";
}
/**
* 通过id获取分类名称
* @param list 分类集合
* @param categoryIdStr id字符串
* @author Mr.Zhang
* @since 2020-05-06
* @
*/
public static String getValueByIndex(HashMap<Integer, String> list, String categoryIdStr){
if(list.size() < 1 || StringUtils.isBlank(categoryIdStr)){
return "";
}
ArrayList<String> name = new ArrayList<>();
List<Integer> idList = CrmebUtil.stringToArray(categoryIdStr);
String str = "";
for (Integer id : idList) {
str = getStrValueByIndex(list, id);
if(!StringUtils.isBlank(str)){
name.add(getStrValueByIndex(list, id));
}
}
if(name.size() < 1){
return "";
}
return StringUtils.join(name, ",");
}
/**
* 通过id获取分类名称
* @param list 分类集合
* @param key id
* @author Mr.Zhang
* @since 2020-05-06
* @
*/
public static String getStrValueByIndex(HashMap<Integer, String> list, Integer key){
if(list.size() < 1){
return "";
}
return list.getOrDefault(key, "");
}
/**
* 通过id获取分类名称
* @param list 分类集合
* @param key id
* @author Mr.Zhang
* @since 2020-05-06
* @
*/
public static Integer getIntValueByIndex(HashMap<Integer, Integer> list, Integer key){
if(null == list ||list.size() < 1){
return 0;
}
return list.getOrDefault(key, 0);
}
/**
* 获取uuid
* @author Mr.Zhang
* @since 2020-05-06
* @
*/
public static String getUuid(){
return UUID.randomUUID().toString().replace("-", "");
}
/**
* 同比率计算 //同比增长率= ((当前周期 - 上一个周期) ÷ 上一个周期 ) *100%
* @param now 当前周期
* @param last 上一个周期
* @author Mr.Zhang
* @since 2020-05-06
* @
*/
public static String getRate(Integer now, Integer last){
int diff = now - last;
if(diff == 0){
return "0%";
}
return (((now - last) / last) * 100) + "%";
}
/**
* 同比率计算 //同比增长率= ((当前周期 - 上一个周期) ÷ 上一个周期 ) *100%
* @param now 当前周期
* @param last 上一个周期
* @author Mr.Zhang
* @since 2020-05-06
* @
*/
public static String getRate(BigDecimal now, BigDecimal last){
//计算差值
BigDecimal subtract = now.subtract(now);
BigDecimal zero = new BigDecimal(BigInteger.ZERO);
if(subtract.equals(zero)){
//数值一样,说明没有增长
return "0%";
}
// BigDecimal.setScale();//用于格式化小数点
// setScale(1);//表示保留以为小数,默认用四舍五入方式
// setScale(1,BigDecimal.ROUND_DOWN);//直接删除多余的小数位如2.35会变成2.3
// setScale(1,BigDecimal.ROUND_UP);//进位处理2.35变成2.4
// setScale(1,BigDecimal.ROUND_HALF_UP);//四舍五入2.35变成2.4
// setScaler(1,BigDecimal.ROUND_HALF_DOWN);//四舍五入2.35变成2.3如果是5则向下舍
return subtract.divide(last, 0, BigDecimal.ROUND_UP).multiply(new BigDecimal(100)) + "%";
}
/**
* hash 转换
* @param hash final byte[] hash参数
* @author Mr.Zhang
* @since 2020-06-03
* @return String
*/
public static String byteToHex(final byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash) {
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
/**
* hash 转换
* @param base64 String 图片流
* @author Mr.Zhang
* @since 2020-06-03
* @return String
*/
public static String getBase64Image(String base64) {
return "data:image/png;base64," + base64;
}
/**
* 去掉字符串第一位和最后一位
* @param param String 参数
* @return String
*/
public static String trimSingeQua(String param){
return param.substring(1,param.length()-1);
}
/**
* 根据长度生成随机数字
* @param start 起始数字
* @param end 结束数字
* @return 生成的随机码
*/
public static Integer randomCount(Integer start, Integer end){
return (int)(Math.random()*(end - start +1) + start);
}
/**
* 订单号生成
* @param payType String 支付类型
* @return 生成的随机码
*/
public static String getOrderNo(String payType){
return getOrderNoPrefix(payType) + DateUtil.nowDate(Constants.DATE_TIME_FORMAT_NUM) + randomCount(11111, 99999);
}
/**
* 订单号生成
* @param payType String 支付类型
* @return 生成的随机码
*/
public static String getOrderNoPrefix(String payType){
switch (payType){
case Constants.PAY_TYPE_WE_CHAT:
return Constants.ORDER_NO_PREFIX_WE_CHAT;
//其他平台
default:
return Constants.ORDER_NO_PREFIX_H5;
}
}
/**
* map排序
* @param map Map<String, Object> 支付类型
* @return 生成的随机码
*/
public static Map<String, Object> mapSort(Map<String, Object> map) {
return new TreeMap<>(map);
}
/**
* map排序然后按照url模式拼接
* @param map Map<String, Object> 支付类型
* @return 生成的随机码
*/
public static String mapToStringUrl(Map<String, Object> map){
map = CrmebUtil.mapSort(map);
StringBuilder sb = new StringBuilder(); // 多线程访问的情况下需要用StringBuffer
Set es = map.keySet(); // 所有参与传参的key按照accsii排序升序
for (Object set : es) {
String k = set.toString();
Object v = map.get(k);
sb.append(k).append("=").append(v.toString()).append("&");
}
String str = sb.toString();
return str.substring(0, str.length() - 1);
}
public static BigDecimal getBigDecimalRate(String rate) {
return new BigDecimal(rate).divide(BigDecimal.TEN.multiply(BigDecimal.TEN));
}
/**
* unicode编码转换为汉字
* @param unicodeStr 待转化的编码
* @return 返回转化后的汉子
*/
public static String UnicodeToCN(String unicodeStr) {
Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
Matcher matcher = pattern.matcher(unicodeStr);
char ch;
while (matcher.find()) {
//group
String group = matcher.group(2);
//ch:'李四'
ch = (char) Integer.parseInt(group, 16);
//group1
String group1 = matcher.group(1);
unicodeStr = unicodeStr.replace(group1, ch + "");
}
return unicodeStr.replace("\\", "").trim();
}
/**
* 汉字转化为Unicode编码
* @param CN 待转化的中文
* @return 返回转化之后的unicode编码
*/
public static String CNToUnicode(String CN) {
try {
StringBuffer out = new StringBuffer("");
//直接获取字符串的unicode二进制
byte[] bytes = CN.getBytes("unicode");
//然后将其byte转换成对应的16进制表示即可
for (int i = 0; i < bytes.length - 1; i += 2) {
out.append("\\u");
String str = Integer.toHexString(bytes[i + 1] & 0xff);
for (int j = str.length(); j < 2; j++) {
out.append("0");
}
String str1 = Integer.toHexString(bytes[i] & 0xff);
out.append(str1);
out.append(str);
}
return out.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
public static String getSign(Map<String, Object> map, String signKey){
String result = CrmebUtil.mapToStringUrl(map) + "&key=" + signKey;
return DigestUtils.md5Hex(result).toUpperCase();
}
}

View File

@@ -0,0 +1,521 @@
package com.utils;
import com.constants.Constants;
import com.exception.CrmebException;
import com.utils.vo.dateLimitUtilVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/** excel操作类
* @author Mr.zhang
* @Description 日期时间类
* @since 2020-04-17
**/
public final class DateUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(DateUtil.class);
private DateUtil() {
throw new IllegalStateException("Utility class");
}
/**
* 获取当前日期,指定格式
* 描述:<描述函数实现的功能>.
*
* @return
*/
public static String nowDate() {
return nowDate(Constants.DATE_FORMAT_NUM);
}
/**
* 获取当前年,指定格式
* 描述:<描述函数实现的功能>.
*
* @return
*/
public static String nowYear() {
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.YEAR) + "";
}
/**
* 获取上一年,指定格式
* 描述:<描述函数实现的功能>.
*
* @return
*/
public static String lastYear() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, -1);
return cal.get(Calendar.YEAR) + "";
}
/**
* 获取当前日期,指定格式
* 描述:<描述函数实现的功能>.
*
* @return
*/
public static Date nowDateTime() {
return strToDate(nowDateTimeStr(), Constants.DATE_FORMAT);
}
/**
* 获取当前日期,指定格式
* 描述:<描述函数实现的功能>.
*
* @return
*/
public static String nowDateTimeStr() {
return nowDate(Constants.DATE_FORMAT);
}
/**
* 获取当前日期,指定格式
* 描述:<描述函数实现的功能>.
*
* @return
*/
public static String nowDate(String DATE_FORMAT) {
SimpleDateFormat dft = new SimpleDateFormat(DATE_FORMAT);
return dft.format(new Date());
}
/**
* 获取当前日期,指定格式
* 描述:<描述函数实现的功能>.
*
* @return
*/
public static String nowDateTime(String DATE_FORMAT) {
SimpleDateFormat dft = new SimpleDateFormat(DATE_FORMAT);
return dft.format(new Date());
}
/**
* 获取当前日期,指定格式
* 描述:<描述函数实现的功能>.
*
* @return
*/
public static Integer getNowTime() {
long t = (System.currentTimeMillis()/1000L);
return Integer.parseInt(String.valueOf(t));
}
/**
* 获取当前日期,指定格式
* 描述:<描述函数实现的功能>.
*
* @return
*/
public static Long getTime() {
return (System.currentTimeMillis()/1000L);
}
/**
* 获取当前日期,指定格式
* 描述:<描述函数实现的功能>.
*
* @return
*/
public static Date nowDateTimeReturnDate(String DATE_FORMAT) {
SimpleDateFormat dft = new SimpleDateFormat(DATE_FORMAT);
return strToDate(dft.format(new Date()), DATE_FORMAT);
}
/**
* convert a date to string in a specifies fromat.
*
* @param date
* @param DATE_FORMAT
* @return
*/
public static String dateToStr(Date date, String DATE_FORMAT) {
if (date == null) {
return null;
}
SimpleDateFormat myFormat = new SimpleDateFormat(DATE_FORMAT);
return myFormat.format(date);
}
/**
* parse a String to Date in a specifies fromat.
*
* @param dateStr
* @param DATE_FORMAT
* @return
* @throws ParseException
*/
public static Date strToDate(String dateStr, String DATE_FORMAT) {
SimpleDateFormat myFormat = new SimpleDateFormat(DATE_FORMAT);
try {
return myFormat.parse(dateStr);
} catch (ParseException e) {
return null;
}
}
/**
* date add Second
*
* @param date
* @param num
* @return
*/
public static Date addSecond(Date date, int num) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.SECOND, num);
return calendar.getTime();
}
/**
* date add Second return String
*
* @param date
* @param num
* @return
*/
public static String addSecond(Date date, int num, String DATE_FORMAT) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.SECOND, num);
return dateToStr(calendar.getTime(), DATE_FORMAT);
}
/**
* 指定日期加上天数后的日期
*
* @param num 为增加的天数
* @param newDate 创建时间
* @return
*/
public static final String addDay(String newDate, int num, String pattern) {
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date currdate = format.parse(newDate);
Calendar ca = Calendar.getInstance();
ca.setTime(currdate);
ca.add(Calendar.DATE, num);
return format.format(ca.getTime());
} catch (ParseException e) {
LOGGER.error("转化时间出错,", e);
return null;
}
}
/**
* 指定日期加上天数后的日期
*
* @param num 为增加的天数
* @param newDate 创建时间
* @return
*/
public static final String addDay(Date newDate, int num, String pattern) {
SimpleDateFormat format = new SimpleDateFormat(pattern);
Calendar ca = Calendar.getInstance();
ca.setTime(newDate);
ca.add(Calendar.DATE, num);
return format.format(ca.getTime());
}
/**
* convert long to date
*
* @param dateLong
* @return
*/
public static Date longToDate(long dateLong) {
return new Date(dateLong);
}
/**
* convert long to date string
*
* @param dateLong
* @param DATE_FORMAT
* @return
*/
public static String longToDate(long dateLong, String DATE_FORMAT) {
return dateToStr(new Date(dateLong), DATE_FORMAT);
}
/**
* compare two date String with a pattern
*
* @param date1
* @param date2
* @param pattern
* @return
*/
public static int compareDate(String date1, String date2, String pattern) {
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(pattern);
try {
Date dt1 = DATE_FORMAT.parse(date1);
Date dt2 = DATE_FORMAT.parse(date2);
if (dt1.getTime() > dt2.getTime()) {
return 1;
} else if (dt1.getTime() < dt2.getTime()) {
return -1;
} else {
return 0;
}
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
/**
* 检查日期格式是否合法
* @param date
* @param style
* @return
*/
public static boolean checkDateFormat(String date, String style) {
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(style);
try {
// 设置lenient为false.
// 否则SimpleDateFormat会比较宽松地验证日期比如2007/02/29会被接受并转换成2007/03/01
DATE_FORMAT.setLenient(false);
DATE_FORMAT.parse(date);
return true;
} catch (ParseException e) {
return false;
}
}
public static long getTwoDateDays(Date beforeDay, Date afterDay) {
SimpleDateFormat sm = new SimpleDateFormat(Constants.DATE_FORMAT_NUM);
long days = -1;
try {
days = (sm.parse(sm.format(afterDay)).getTime() - sm.parse(sm.format(beforeDay)).getTime()) / (1000 * 3600 * 24);
} catch (Exception e) {
e.printStackTrace();
}
return days;
}
//获取时间戳11位
public static int getSecondTimestamp(Date date){
if (null == date) {
return 0;
}
String timestamp = String.valueOf(date.getTime()/1000);
return Integer.parseInt(timestamp);
}
//获取时间戳11位
public static int getSecondTimestamp(String date){
if (null == date) {
return 0;
}
Date date1 = strToDate(date, Constants.DATE_FORMAT);
if(date1 == null){
return 0;
}
String timestamp = String.valueOf(date1.getTime()/1000);
return Integer.parseInt(timestamp);
}
//获取时间戳11位
public static int getSecondTimestamp(){
Date date = strToDate(nowDateTime(Constants.DATE_FORMAT), Constants.DATE_FORMAT);
if (null == date) {
return 0;
}
String timestamp = String.valueOf(date.getTime()/1000);
return Integer.parseInt(timestamp);
}
/** 获得昨天日期:yyyy-MM-dd HH:mm:ss */
public static String getYesterdayStr() {
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, -1);
SimpleDateFormat startSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return startSdf.format(c.getTime());
}
/** 获得本周第一天:yyyy-MM-dd HH:mm:ss */
public static String getWeekStartDay() {
Calendar c = Calendar.getInstance();
c.add(Calendar.WEEK_OF_MONTH, 0);
c.set(Calendar.DAY_OF_WEEK, 2);
SimpleDateFormat startSdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
return startSdf.format(c.getTime());
}
/** 获得本周最后一天:yyyy-MM-dd HH:mm:ss */
public static String getWeekEndDay() {
return addDay(getWeekStartDay(), 7, Constants.DATE_FORMAT);
}
/** 获得上周第一天:yyyy-MM-dd HH:mm:ss */
public static String getLastWeekStartDay() {
return addDay(getWeekStartDay(), -7, Constants.DATE_FORMAT);
}
/** 获得上周最后一天:yyyy-MM-dd HH:mm:ss */
public static String getLastWeekEndDay() {
return addDay(getLastWeekStartDay(), 7, Constants.DATE_FORMAT);
}
/** 获得本月最后一天:yyyy-MM-dd HH:mm:ss */
public static String getMonthEndDay() {
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
SimpleDateFormat endSdf = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
return endSdf.format(c.getTime());
}
/** 获得上月第一天:yyyy-MM-dd HH:mm:ss */
public static String getLastMonthStartDay() {
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, -1);
c.set(Calendar.DAY_OF_MONTH, 1);
SimpleDateFormat startSdf = new SimpleDateFormat("yyyy-MM-01 00:00:00");
return startSdf.format(c.getTime());
}
/** 获得上月最后一天:yyyy-MM-dd HH:mm:ss */
public static String getLastMonthEndDay() {
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, -1);
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
SimpleDateFormat endSdf = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
return endSdf.format(c.getTime());
}
/** 获得上年第一天:yyyy-MM-dd HH:mm:ss */
public static String getLastYearStartDay() {
Calendar c = Calendar.getInstance();
c.add(Calendar.YEAR, -1);
SimpleDateFormat startSdf = new SimpleDateFormat("yyyy-01-01 00:00:00");
return startSdf.format(c.getTime());
}
/** 获得上年最后一天:yyyy-MM-dd HH:mm:ss */
public static String getLastYearEndDay() {
Calendar c = Calendar.getInstance();
c.add(Calendar.YEAR, -1);
SimpleDateFormat endSdf = new SimpleDateFormat("yyyy-12-31 23:59:59");
return endSdf.format(c.getTime());
}
/**
* 计算时间范围
* @param data string 类型
* @author Mr.Zhang
* @since 2020-05-06
* @return dateLimitUtilVo
*/
public static dateLimitUtilVo getDateLimit(String data){
//时间计算
String startTime = null;
String endTime = DateUtil.nowDateTime(Constants.DATE_FORMAT);
String day = DateUtil.nowDateTime(Constants.DATE_FORMAT_START);
String end = DateUtil.nowDateTime(Constants.DATE_FORMAT_END);
if(!StringUtils.isBlank(data)){
switch (data){
case Constants.SEARCH_DATE_DAY:
startTime = day;
break;
case Constants.SEARCH_DATE_YESTERDAY:
startTime = DateUtil.addDay(day, -1, Constants.DATE_FORMAT_START);
endTime = DateUtil.addDay(end, -1, Constants.DATE_FORMAT_END);
break;
case Constants.SEARCH_DATE_LATELY_7:
startTime = DateUtil.addDay(day, -7, Constants.DATE_FORMAT_START);
break;
case Constants.SEARCH_DATE_WEEK:
startTime = getWeekStartDay();
endTime = getWeekEndDay();
break;
case Constants.SEARCH_DATE_PRE_WEEK:
startTime = getLastWeekStartDay();
endTime = getLastWeekEndDay();
break;
case Constants.SEARCH_DATE_LATELY_30:
startTime = DateUtil.addDay(day, -30, Constants.DATE_FORMAT_START);
break;
case Constants.SEARCH_DATE_MONTH:
startTime = DateUtil.nowDateTime(Constants.DATE_FORMAT_MONTH_START);
endTime = getMonthEndDay();
break;
case Constants.SEARCH_DATE_PRE_MONTH:
startTime = getLastMonthStartDay();
endTime = getLastMonthEndDay();
break;
case Constants.SEARCH_DATE_YEAR:
startTime = DateUtil.nowDateTime(Constants.DATE_FORMAT_YEAR_START);
endTime = DateUtil.nowDateTime(Constants.DATE_FORMAT_YEAR_END);
break;
case Constants.SEARCH_DATE_PRE_YEAR:
startTime = getLastYearStartDay();
endTime = getLastYearEndDay();
break;
default:
List<String> list = CrmebUtil.stringToArrayStr(data);
if(list.size() == 1){
throw new CrmebException("选择时间参数格式错误,请在 " +
Constants.SEARCH_DATE_DAY + "|" +
Constants.SEARCH_DATE_YESTERDAY + "|" +
Constants.SEARCH_DATE_LATELY_7 + "|" +
Constants.SEARCH_DATE_LATELY_30 + "|" +
Constants.SEARCH_DATE_MONTH + "|" +
Constants.SEARCH_DATE_YEAR + "|自定义时间范围格式yyyy-MM-dd HH:mm:ss两个时间范围用逗号分割");
}
startTime = list.get(0);
endTime = list.get(1);
break;
}
}
return new dateLimitUtilVo(startTime, endTime);
}
/**
* 获取某一时间段内的时间集合
* @param data string 类型
* @author Mr.Zhang
* @since 2020-05-06
* @return List<Date>
*/
public static List<String> getListDate(String data) {
//获取30天的开始结束日期
dateLimitUtilVo dateLimit = DateUtil.getDateLimit(data);
//定义日期集合
List<String> date = new ArrayList<>();
//开始日期
Date startDate = DateUtil.strToDate(dateLimit.getStartTime(), Constants.DATE_FORMAT);
//结束日期
Date endDate = DateUtil.strToDate(dateLimit.getEndTime(), Constants.DATE_FORMAT);
while (endDate.after(startDate)){
date.add(DateUtil.dateToStr(startDate, Constants.DATE_FORMAT_DATE)); // 放入集合
startDate = DateUtil.strToDate(DateUtil.addDay(startDate, 1, Constants.DATE_FORMAT), Constants.DATE_FORMAT); //循环一次 加一天
}
return date;
}
}

View File

@@ -0,0 +1,354 @@
package com.utils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.constants.Constants;
import com.zbkj.crmeb.export.vo.ExcelColumn;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/** excel操作类
* @author Mr.zhang
* @since 2020-04-17
**/
public class ExcelUtil {
private final static Logger log = LoggerFactory.getLogger(ExcelUtil.class);
private final static String EXCEL2003 = "xls";
private final static String EXCEL2007 = "xlsx";
private static String sheetName;
public static String getSheetName() {
return sheetName;
}
public static void setSheetName(String sheetName) {
ExcelUtil.sheetName = sheetName;
}
public static String getFileName() {
return fileName;
}
public static void setFileName(String fileName) {
ExcelUtil.fileName = fileName;
}
private static String fileName;
public static <T> List<T> readExcel(String path, Class<T> cls, MultipartFile file){
String fileName = file.getOriginalFilename();
if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
log.error("上传文件格式不正确");
}
List<T> dataList = new ArrayList<>();
Workbook workbook = null;
try {
InputStream is = file.getInputStream();
if (fileName.endsWith(EXCEL2007)) {
// FileInputStream is = new FileInputStream(new File(path));
workbook = new XSSFWorkbook(is);
}
if (fileName.endsWith(EXCEL2003)) {
// FileInputStream is = new FileInputStream(new File(path));
workbook = new HSSFWorkbook(is);
}
if (workbook != null) {
//类映射 注解 value-->bean columns
Map<String, List<Field>> classMap = new HashMap<>();
List<Field> fields = Stream.of(cls.getDeclaredFields()).collect(Collectors.toList());
fields.forEach(
field -> {
ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
if (annotation != null) {
String value = annotation.value();
if (StringUtils.isBlank(value)) {
return;//return起到的作用和continue是相同的 语法
}
if (!classMap.containsKey(value)) {
classMap.put(value, new ArrayList<>());
}
field.setAccessible(true);
classMap.get(value).add(field);
}
}
);
//索引-->columns
Map<Integer, List<Field>> reflectionMap = new HashMap<>(16);
//默认读取第一个sheet
Sheet sheet = workbook.getSheetAt(0);
boolean firstRow = true;
for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
//首行 提取注解
if (firstRow) {
for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
Cell cell = row.getCell(j);
String cellValue = getCellValue(cell);
if (classMap.containsKey(cellValue)) {
reflectionMap.put(j, classMap.get(cellValue));
}
}
firstRow = false;
} else {
//忽略空白行
if (row == null) {
continue;
}
try {
T t = cls.newInstance();
//判断是否为空白行
boolean allBlank = true;
for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
if (reflectionMap.containsKey(j)) {
Cell cell = row.getCell(j);
String cellValue = getCellValue(cell);
if (StringUtils.isNotBlank(cellValue)) {
allBlank = false;
}
List<Field> fieldList = reflectionMap.get(j);
fieldList.forEach(
x -> {
try {
handleField(t, cellValue, x);
} catch (Exception e) {
log.error(String.format("reflect field:%s value:%s exception!", x.getName(), cellValue), e);
}
}
);
}
}
if (!allBlank) {
dataList.add(t);
} else {
log.warn(String.format("row:%s is blank ignore!", i));
}
} catch (Exception e) {
log.error(String.format("parse row:%s exception!", i), e);
}
}
}
}
} catch (Exception e) {
log.error(String.format("parse excel exception!"), e);
} finally {
if (workbook != null) {
try {
workbook.close();
} catch (Exception e) {
log.error(String.format("parse excel exception!"), e);
}
}
}
return dataList;
}
private static <T> void handleField(T t, String value, Field field) throws Exception {
Class<?> type = field.getType();
if (type == null || type == void.class || StringUtils.isBlank(value)) {
return;
}
if (type == Object.class) {
field.set(t, value);
//数字类型
} else if (type.getSuperclass() == null || type.getSuperclass() == Number.class) {
if (type == int.class || type == Integer.class) {
field.set(t, NumberUtils.toInt(value));
} else if (type == long.class || type == Long.class) {
field.set(t, NumberUtils.toLong(value));
} else if (type == byte.class || type == Byte.class) {
field.set(t, NumberUtils.toByte(value));
} else if (type == short.class || type == Short.class) {
field.set(t, NumberUtils.toShort(value));
} else if (type == double.class || type == Double.class) {
field.set(t, NumberUtils.toDouble(value));
} else if (type == float.class || type == Float.class) {
field.set(t, NumberUtils.toFloat(value));
} else if (type == char.class || type == Character.class) {
field.set(t, CharUtils.toChar(value));
} else if (type == boolean.class) {
field.set(t, BooleanUtils.toBoolean(value));
} else if (type == BigDecimal.class) {
field.set(t, new BigDecimal(value));
}
} else if (type == Boolean.class) {
field.set(t, BooleanUtils.toBoolean(value));
} else if (type == Date.class) {
//
field.set(t, value);
} else if (type == String.class) {
field.set(t, value);
} else {
Constructor<?> constructor = type.getConstructor(String.class);
field.set(t, constructor.newInstance(value));
}
}
private static String getCellValue(Cell cell) {
if (cell == null) {
return "";
}
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
// if (DateUtil.checkDateFormat(cell.getNumericCellValue() + "", Constants.DATE_TIME_FORMAT_NUM)) {
// return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
// } else {
// return new BigDecimal(cell.getNumericCellValue()).toString();
// }
return cell.getNumericCellValue() + "";
} else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
return StringUtils.trimToEmpty(cell.getStringCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
return StringUtils.trimToEmpty(cell.getCellFormula());
} else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
return "";
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
return "ERROR";
} else {
return cell.toString().trim();
}
}
public static <T> void writeExcel(HttpServletResponse response, List<T> dataList, Class<T> cls){
Field[] fields = cls.getDeclaredFields();
List<Field> fieldList = Arrays.stream(fields)
.filter(field -> {
ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
if (annotation != null && annotation.col() > 0) {
field.setAccessible(true);
return true;
}
return false;
}).sorted(Comparator.comparing(field -> {
int col = 0;
ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
if (annotation != null) {
col = annotation.col();
}
return col;
})).collect(Collectors.toList());
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet(getSheetName());
AtomicInteger ai = new AtomicInteger();
{
Row row = sheet.createRow(ai.getAndIncrement());
AtomicInteger aj = new AtomicInteger();
//写入头部
fieldList.forEach(field -> {
ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
String columnName = "";
if (annotation != null) {
columnName = annotation.value();
}
Cell cell = row.createCell(aj.getAndIncrement());
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
Font font = wb.createFont();
font.setBoldweight(Font.BOLDWEIGHT_NORMAL);
cellStyle.setFont(font);
cell.setCellStyle(cellStyle);
cell.setCellValue(columnName);
});
}
if (CollectionUtils.isNotEmpty(dataList)) {
dataList.forEach(t -> {
Row row1 = sheet.createRow(ai.getAndIncrement());
AtomicInteger aj = new AtomicInteger();
fieldList.forEach(field -> {
Class<?> type = field.getType();
Object value = "";
try {
value = field.get(t);
} catch (Exception e) {
e.printStackTrace();
}
Cell cell = row1.createCell(aj.getAndIncrement());
if (value != null) {
if (type == Date.class) {
cell.setCellValue(value.toString());
} else {
cell.setCellValue(value.toString());
}
cell.setCellValue(value.toString());
}
});
});
}
//冻结窗格
wb.getSheet(getSheetName()).createFreezePane(0, 1, 0, 1);
//浏览器下载excel
buildExcelDocument(getFileName() + "_" + DateUtil.nowDate(Constants.DATE_TIME_FORMAT_NUM) +".xlsx", wb, response);
//生成excel文件
// buildExcelFile(".\\default.xlsx",wb);
}
/**
* 浏览器下载excel
* @param fileName
* @param wb
* @param response
*/
private static void buildExcelDocument(String fileName, Workbook wb,HttpServletResponse response){
try {
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "utf-8"));
response.flushBuffer();
wb.write(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 生成excel文件
* @param path 生成excel路径
* @param wb
*/
private static void buildExcelFile(String path, Workbook wb){
File file = new File(path);
if (file.exists()) {
file.delete();
}
try {
wb.write(new FileOutputStream(file));
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,140 @@
package com.utils;
import com.constants.Constants;
import com.exception.CrmebException;
import com.utils.vo.ImageMergeUtilVo;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.awt.*;
import java.io.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
@Data
@Component
public class ImageMergeUtil {
public static BufferedImage bufferedImage; //背景图片
public static String model = "merge";
public static String ext = "jpg";
/**
* 合并生成新的图片文件
* @param list List<ImageMergeUtilVo> 图片集合
* @author Mr.Zhang
* @since 2020-05-06
*/
public static String drawWordFile(List<ImageMergeUtilVo> list){
buildImage(list);
if(bufferedImage == null){
return null;
}
try {
UploadUtil.setModelPath(model);
UploadUtil.setExtStr(ext);
UploadUtil.setType(Constants.UPLOAD_TYPE_IMAGE);
//文件名
String newFileName = UploadUtil.fileName(ext);
// 创建目标文件的名称规则请看destPath方法
String destPath = UploadUtil.getDestPath(newFileName);
// 创建文件
File file = UploadUtil.createFile(destPath);
ImageIO.write(bufferedImage, ext, file);
return destPath;
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
private static void drawImage(ImageMergeUtilVo imageMergeUtilVo){
String fileName = getFileSource(imageMergeUtilVo.getPath());
if(StringUtils.isBlank(fileName)){
return;
}
try{
File file = new File(fileName);
BufferedImage read = ImageIO.read(file);
if(bufferedImage == null || bufferedImage.equals("")){
imageMergeUtilVo.setX(0);
imageMergeUtilVo.setY(0);
//创建新的画布,宽高以第一个图为准
bufferedImage = new BufferedImage(read.getWidth(), read.getHeight(), BufferedImage.TYPE_INT_BGR);
}
Graphics graphics = bufferedImage.getGraphics();
//在画布上绘制背景图
graphics.drawImage(read, imageMergeUtilVo.getX(), imageMergeUtilVo.getX(), read.getWidth(), read.getHeight(), null);
file.delete();
}catch (Exception e){
//合成图片xx失败
throw new CrmebException("合成图片 + " + fileName + "失败");
}
}
/**
* 合并生成新的图片流
* @param list List<ImageMergeUtilVo> 图片集合
* @author Mr.Zhang
* @since 2020-05-06
*/
private static void buildImage(List<ImageMergeUtilVo> list){
if(list.size() < 2){
throw new CrmebException("至少需要2张图片才可以做合并");
}
for (ImageMergeUtilVo imageMergeUtilVo : list) {
drawImage(imageMergeUtilVo);
}
}
/**
* 根据图片路径输出File流
* @param url String 文件地址
* @author Mr.Zhang
* @since 2020-05-06
*/
private static String getFileSource(String url){
if(!url.contains("http")){
return url;
}
try {
URL urlInfo = new URL(url);
// 打开连接
URLConnection con = urlInfo.openConnection();
// 输入流
InputStream is = con.getInputStream();
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
String fileName = UploadUtil.fileName(ext);
// 输出的文件流
OutputStream os = new FileOutputStream(fileName);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
return fileName;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}

View File

@@ -0,0 +1,62 @@
package com.utils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
/**
* @description:
* @author: Administrator
* @date: 2019-03-18 10:40
*/
@Component
public class QRCodeUtil {
public static String crateQRCode(String content, int width, int height) throws IOException {
String resultImage = "";
if (!StringUtils.isEmpty(content)) {
ServletOutputStream stream = null;
ByteArrayOutputStream os = new ByteArrayOutputStream();
@SuppressWarnings("rawtypes")
HashMap<EncodeHintType, Comparable> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 指定字符编码为“utf-8”
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 指定二维码的纠错等级为中级
hints.put(EncodeHintType.MARGIN, 2); // 设置图片的边距
try {
QRCodeWriter writer = new QRCodeWriter();
BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
ImageIO.write(bufferedImage, "png", os);
/**
* 原生转码前面没有 data:image/png;base64 这些字段,返回给前端是无法被解析,可以让前端加,也可以在下面加上
*/
return CrmebUtil.getBase64Image(Base64.encodeBase64String(os.toByteArray()));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
stream.flush();
stream.close();
}
}
}
return null;
}
}

View File

@@ -0,0 +1,292 @@
package com.utils;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;
/**
* redis工具类
* @author Mr.Zhang
* @since 2020-04-13
*/
@Component
public class RedisUtil {
@Autowired
private RedisTemplate redisTemplate;
/**
* 写入缓存
* @param key string key
* @param value string value
* @author Mr.Zhang
* @since 2020-04-13
* @return bool
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 写入缓存带有效期
* @param key string key
* @param value string value
* @param expireTime Long 过期时间
* @param timeUnit TimeUnit 时间格式
* @author Mr.Zhang
* @since 2020-04-13
* @return bool
*/
public boolean set(final String key, Object value, Long expireTime, TimeUnit timeUnit) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, timeUnit);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 批量删除对应的value
* @param keys string key
* @author Mr.Zhang
* @since 2020-04-13
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量删除key
* @param pattern string key
* @author Mr.Zhang
* @since 2020-04-13
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0) {
redisTemplate.delete(keys);
}
}
/**
* 删除对应的value
* @param key string key
* @author Mr.Zhang
* @since 2020-04-13
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
* @param key string key
* @author Mr.Zhang
* @since 2020-04-13
* @return bool
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
* @param key string key
* @author Mr.Zhang
* @since 2020-04-13
* @return Object
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 哈希 添加
*
* @param key
* @param hashKey
* @param value
*/
/**
* 哈希添加
* @param key string key
* @param hashKey Object hashKey
* @param value Object value
* @author Mr.Zhang
* @since 2020-04-13
*/
public void hmSet(String key, Object hashKey, Object value) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
hash.put(key, hashKey, value);
}
/**
* 哈希删除
* @param key string key
* @param hashKey Object hashKey
* @author Mr.Zhang
* @since 2020-04-13
*/
public void hmDelete(String key, Object hashKey) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
hash.delete(key, hashKey);
}
/**
* 哈希获取数据
* @param key string key
* @param hashKey Object hashKey
* @author Mr.Zhang
* @return Object
* @since 2020-04-13
*/
public Object hmGet(String key, Object hashKey) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.get(key, hashKey);
}
/**
* 列表添加左边添加
* @param k string key
* @param v Object v
* @author Mr.Zhang
* @since 2020-04-13
*/
public void lPush(String k, Object v) {
ListOperations<String, Object> list = redisTemplate.opsForList();
list.leftPush(k, v);
}
/**
* 从右边拿出来一个
* @param k string key
* @param t Long 超时秒数
* @author Mr.Zhang
* @since 2020-04-13
*/
public Object getRightPop(String k, Long t){
return redisTemplate.opsForList().rightPop(k, t, TimeUnit.SECONDS);
}
/**
* 列表获取数量
* @param k string key
* @author Mr.Zhang
* @since 2020-04-13
* @return Long
*/
public Long getListSize(String k) {
return redisTemplate.opsForList().size(k);
}
/**
* 列表获取
* @param k string key
* @param l long l
* @param l1 long l1
* @author Mr.Zhang
* @since 2020-04-13
* @return List<Object>
*/
public List<Object> lRange(String k, long l, long l1) {
ListOperations<String, Object> list = redisTemplate.opsForList();
return list.range(k, l, l1);
}
/**
* 集合添加
* @param key string key
* @param value Object value
* @author Mr.Zhang
* @since 2020-04-13
*/
public void add(String key, Object value) {
SetOperations<String, Object> set = redisTemplate.opsForSet();
set.add(key, value);
}
/**
* 集合获取
* @param key string key
* @author Mr.Zhang
* @since 2020-04-13
* @return Set<Object>
*/
public Set<Object> setMembers(String key) {
SetOperations<String, Object> set = redisTemplate.opsForSet();
return set.members(key);
}
/**
* 有序集合添加
*
* @param key
* @param value
* @param scoure
*/
/**
* 有序集合添加 排行榜使用
* @param key string key
* @param value Object value
* @param score double scoure
* @author Mr.Zhang
* @since 2020-04-13
*/
public void zAdd(String key, Object value, double score) {
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
zset.add(key, value, score);
}
/**
* 有序集合获取 排行榜使用
* @param key string key
* @param score double scoure
* @author Mr.Zhang
* @since 2020-04-13
* @return Set<Object>
*/
public Set<Object> rangeByScore(String key, double score, double score1) {
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
return zset.rangeByScore(key, score, score1);
}
}

View File

@@ -0,0 +1,93 @@
package com.utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
public class RequestUtil extends HttpServlet{
public static HttpServletRequest getRequest() {
if(RequestContextHolder.getRequestAttributes() != null){
return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
}
return null;
}
public static HashMap<String, Object> getRequestParamAndHeader(){
try{
HttpServletRequest request = getRequest();
if(request == null){
return null;
}
//request信息
HashMap<String, Object> data = new HashMap<>();
HashMap<String, Object> requestParams = new HashMap<>();
Enumeration<String> paraNames = request.getParameterNames();
if(paraNames != null){
for(Enumeration<String> enumeration =paraNames;enumeration.hasMoreElements();){
String key= enumeration.nextElement();
requestParams.put(key, request.getParameter(key));
}
}
HashMap<String, Object> requestFilter = new HashMap<>();
Enumeration<String> attributeNames = request.getAttributeNames();
if(attributeNames != null){
for ( Enumeration<String> attributeNames1 = attributeNames; attributeNames1.hasMoreElements();) {
String key= attributeNames1.nextElement();
if(key.contains("request_")){
requestFilter.put(key, request.getAttribute(key));
}
}
}
data.put("url", request.getRequestURL());
data.put("uri", request.getRequestURI());
data.put("method", request.getMethod());
data.put("request", requestParams);
data.put("request_filter", requestFilter);
//header 信息
Enumeration<String> headerNames = request.getHeaderNames();
HashMap<String, Object> headerParams = new HashMap<>();
if(headerNames != null){
for(Enumeration<String> enumeration = headerNames;enumeration.hasMoreElements();){
String key= enumeration.nextElement();
String value=request.getHeader(key);
headerParams.put(key, value);
}
}
data.put("header", headerParams);
return data;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
public static String getDomain(){
HttpServletRequest request = getRequest();
if(request == null){
return null;
}
return request.getServerName() + ":" + request.getServerPort();
}
public static String getUri(HttpServletRequest request){
String uri = request.getRequestURI();
List<String> list = CrmebUtil.stringToArrayStrRegex(uri, "/");
list.removeIf(StringUtils::isNumeric);
return StringUtils.join(list, "/");
}
}

View File

@@ -0,0 +1,317 @@
package com.utils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* httpClient 工具类
* @author Mr.Zhang
* @since 2020-04-13
*/
@Component
public class RestTemplateUtil {
@Autowired
private RestTemplate restTemplate;
/**
* 发送GET请求
* @param url
* @param param
* @return
*/
public String getData(String url, Map<String, String> param) {
// 请勿轻易改变此提交方式,大部分的情况下,提交方式都是表单提交
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
return restTemplate.getForEntity(url, String.class, param).getBody();
}
/**
* 发送GET请求
* @param url
* @return
*/
public String getLink(String url) {
return restTemplate.getForEntity(url, String.class).getBody();
}
/**
* 发送GET请求
* @param url
* @return
*/
public JSONObject getData(String url) {
HttpHeaders headers = new HttpHeaders();
headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, Object>> requestEntity =
new HttpEntity<>( headers);
return restTemplate.exchange( url, HttpMethod.GET, requestEntity, JSONObject.class).getBody();
}
/**
* 发送GET请求 支持header
* @param url
* @return
*/
public JSONObject getData(String url, HashMap<String, String> hashMap) {
HttpHeaders headers = new HttpHeaders();
headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
for (Map.Entry<String, String> entry : hashMap.entrySet()) {
headers.add(entry.getKey(), entry.getValue());
}
HttpEntity<Map<String, Object>> requestEntity =
new HttpEntity<>( headers);
return restTemplate.exchange( url, HttpMethod.GET, requestEntity, JSONObject.class).getBody();
}
/**
* 发送POST-JSON请求
*
* @param url
* @param param
* @return
*/
public String postJsonData(String url, JSONObject param) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
HttpEntity<JSONObject> requestEntity = new HttpEntity<JSONObject>(param, headers);
return restTemplate.postForEntity(url, param, String.class).getBody();
}
/**
* 发送POST 表单请求
*
* @param url
* @return
*/
public String postFormData(String url, MultiValueMap<String, String> map) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, String>> requests = new HttpEntity<MultiValueMap<String, String>>(map, headers);
String body = restTemplate.postForEntity(url, requests, String.class).getBody();
return body;
}
/**
* 发送POST-JSON请求
*
* @param url
* @param param
* @return
*/
public JSONObject postJsonDataAndReturnJson(String url, JSONObject param) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
HttpEntity<JSONObject> requestEntity = new HttpEntity<JSONObject>(param, headers);
JSONObject body = restTemplate.postForEntity(url, requestEntity, JSONObject.class).getBody();
return body;
}
/**
* 发送POST-JSON请求
*
* @param url
* @return
*/
public JSONObject post(String url) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
HttpEntity<String> requestEntity = new HttpEntity<>( headers);
JSONObject body = restTemplate.postForEntity(url, requestEntity, JSONObject.class).getBody();
return body;
}
/**
* 发送POST-JSON请求
*
* @param url
* @return
*/
public String postXml(String url, String xml){
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/xml; charset=UTF-8");
headers.setContentType(type);
HttpEntity<String> requestEntity = new HttpEntity<>(xml, headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
try{
return new String(Objects.requireNonNull(responseEntity.getBody()).getBytes("ISO8859-1"), StandardCharsets.UTF_8);
}catch (Exception e){
return "";
}
}
/**
* 发送POST 表单请求
*
* @param url
* @param params
* @return
*
* 表单提交,返回数据分为两部分,一个代表成功,一个是返回的数据内容
*/
public String postFormData(String url, LinkedMultiValueMap<String, Object> params ) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
new HttpEntity<>(params, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(
url,
HttpMethod.POST,
requestEntity,
String.class);
String body = responseEntity.getBody();
return body;
}
public String postMapData(String url, Map<String, Object> params ) {
//cs
HttpHeaders headers = new HttpHeaders();
headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
HttpEntity<Map<String, Object>> requestEntity =
new HttpEntity<>(params, headers);
String body1 = restTemplate.postForEntity( url, requestEntity, String.class).getBody();
System.out.println(body1);
return body1;
}
public String postMapData(String url, Map<String, Object> params, Map<String, String> header) {
//cs
HttpHeaders headers = new HttpHeaders();
headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
for (Map.Entry<String, String> entry : header.entrySet()) {
headers.add(entry.getKey(), entry.getValue());
}
HttpEntity<Map<String, Object>> requestEntity =
new HttpEntity<>(params, headers);
String body1 = restTemplate.postForEntity( url, requestEntity, String.class).getBody();
System.out.println(body1);
return body1;
}
public String postStringData(String url,String data ) {
//cs
HttpHeaders headers = new HttpHeaders();
headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
HttpEntity<String> requestEntity =
new HttpEntity<>(data, headers);
String body1 = restTemplate.postForEntity(url, requestEntity, String.class).getBody();
System.out.println(body1);
return body1;
}
public byte[] postJsonDataAndReturnBuffer(String url, JSONObject param) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
HttpEntity<JSONObject> requestEntity = new HttpEntity<JSONObject>(param, headers);
return restTemplate.postForEntity(url, param, byte[].class).getBody();
}
public byte[] getBuffer(String url) {
return restTemplate.getForEntity(url, byte[].class).getBody();
}
}

View File

@@ -0,0 +1,38 @@
package com.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if(SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = applicationContext;
}
}
//获取applicationContext
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
//通过name获取 Bean.
public static Object getBean(String name){
return getApplicationContext().getBean(name);
}
//通过class获取Bean.
public static <T> T getBean(Class<T> clazz){
return getApplicationContext().getBean(clazz);
}
//通过name,以及Clazz返回指定的Bean
public static <T> T getBean(String name,Class<T> clazz){
return getApplicationContext().getBean(name, clazz);
}
}

View File

@@ -0,0 +1,90 @@
package com.utils;
/**
* Created on 2019/9/7.
*
* @author MaXiaolong
*/
import java.util.*;
public final class ThreadLocalUtil {
private ThreadLocalUtil() {
throw new IllegalStateException("Utility class");
}
private static final ThreadLocal<Map<String, Object>> threadLocal = ThreadLocal.withInitial(() -> new HashMap(4));
public static Map<String, Object> getThreadLocal(){
return threadLocal.get();
}
public static <T> T get(String key) {
Map map = (Map)threadLocal.get();
return (T)map.get(key);
}
public static <T> T get(String key,T defaultValue) {
Map map = (Map)threadLocal.get();
return (T)map.get(key) == null ? defaultValue : (T)map.get(key);
}
public static void set(String key, Object value) {
Map map = (Map)threadLocal.get();
map.put(key, value);
}
public static void set(Map<String, Object> keyValueMap) {
Map map = (Map)threadLocal.get();
map.putAll(keyValueMap);
}
public static void remove() {
threadLocal.remove();
}
public static <T> Map<String,T> fetchVarsByPrefix(String prefix) {
Map<String,T> vars = new HashMap<>();
if( prefix == null ){
return vars;
}
Map map = (Map)threadLocal.get();
Set<Map.Entry> set = map.entrySet();
for( Map.Entry entry : set ){
Object key = entry.getKey();
if( key instanceof String ){
if( ((String) key).startsWith(prefix) ){
vars.put((String)key,(T)entry.getValue());
}
}
}
return vars;
}
public static <T> T remove(String key) {
Map map = (Map)threadLocal.get();
return (T)map.remove(key);
}
public static void clear(String prefix) {
if( prefix == null ){
return;
}
Map map = (Map)threadLocal.get();
Set<Map.Entry> set = map.entrySet();
List<String> removeKeys = new ArrayList<>();
for( Map.Entry entry : set ){
Object key = entry.getKey();
if( key instanceof String ){
if( ((String) key).startsWith(prefix) ){
removeKeys.add((String)key);
}
}
}
for( String key : removeKeys ){
map.remove(key);
}
}
}

View File

@@ -0,0 +1,314 @@
package com.utils;
import cn.hutool.core.util.RandomUtil;
import com.constants.Constants;
import com.exception.CrmebException;
import com.zbkj.crmeb.upload.vo.FileResultVo;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* 上传工具类
* @author Mr.Zhang
* @since 2020-05-08
*/
public class UploadUtil {
private static UploadUtil uploadUtil = new UploadUtil();
//服务器存储地址
// private static String rootPath = "/www/wwwroot/upload";
private static String rootPath = "";
//类型
// private static String imagePath = "/image";
private static String type = "/image";
//模块
// private static String modelPath = "/store";
private static String modelPath = "/public";
//扩展名
private static String extStr = "png,jpg";
//文件大小上限
private static int size = 2;
//是否压缩图片
private static boolean isCompress = false;
public static String getRootPath() {
return rootPath;
}
public static void setRootPath(String rootPath) {
UploadUtil.rootPath = (rootPath + "/").replace(" ", "").replace("//", "/");
}
public static String getType() {
return type;
}
public static void setType(String type) {
UploadUtil.type = type + "/";
}
public static String getModelPath() {
return modelPath;
}
public static void setModelPath(String modelPath) {
UploadUtil.modelPath = modelPath + "/";
}
public static String getExtStr() {
return extStr;
}
public static void setExtStr(String extStr) {
UploadUtil.extStr = extStr;
}
public static int getSize() {
return size;
}
public static void setSize(int size) {
UploadUtil.size = size;
}
public static boolean isIsCompress() {
return isCompress;
}
public static void setIsCompress(boolean isCompress) {
UploadUtil.isCompress = isCompress;
}
/**
* 获取单例
* @author Mr.Zhang
* @since 2020-05-08
*/
public static UploadUtil getInstance() {
if (uploadUtil == null) {
uploadUtil = new UploadUtil();
}
return uploadUtil;
}
/**
* 根据文件的绝对路径创建一个文件对象.
* @return 返回创建的这个文件对象
* @author Mr.Zhang
* @since 2020-05-08
*/
public static File createFile(String filePath) throws IOException {
// 获取文件的完整目录
String fileDir = FilenameUtils.getFullPath(filePath);
// 判断目录是否存在,不存在就创建一个目录
File file = new File(fileDir);
if (!file.isDirectory()) {
//创建失败返回null
if (!file.mkdirs()) {
throw new CrmebException("文件目录创建失败...");
}
}
// 判断这个文件是否存在,不存在就创建
file = new File(filePath);
if (!file.exists()) {
if (!file.createNewFile()) {
throw new CrmebException("目标文件创建失败...");
}
}
return file;
}
/**
* 判断文件扩展名是否合法
* @param extName 文件的后缀名
* @author Mr.Zhang
* @since 2020-05-08
*/
private static void isContains(String extName) {
if (StringUtils.isNotEmpty(getExtStr())) {
// 切割文件扩展名
List<String> extensionList = CrmebUtil.stringToArrayStr(getExtStr());
if (extensionList.size() > 0) {
//判断
if (!extensionList.contains(extName)) {
throw new CrmebException("上传文件的类型只能是:" + getExtStr());
}
} else {
throw new CrmebException("上传文件的类型只能是:" + getExtStr());
}
}
}
// /**
// * 图片压缩
// * @param serverPath 图片的绝对路径
// * @param childFile 子文件夹
// * @param extName 文件的后缀
// * @author Mr.Zhang
// * @since 2020-05-08
// */
// private static String thumbnails(String serverPath, String childFile, String extName) throws IOException {
// // 压缩后的相对路径文件名
// String toFilePath = getDestPath(extName);
//
// // scale图片缩放比例
// // outputQuality图片压缩比例
// // toFile图片位置
// // outputFormat文件输出后缀名
// // Thumbnails 如果用来压缩 png 格式的文件,会越压越大,
// // 得把png格式的图片转换为jpg格式
// if ("png".equalsIgnoreCase(extName)) {
// // 由于outputFormat会自动在路径后加上后缀名所以移除以前的后缀名
// String removeExtensionFilePath = FilenameUtils.removeExtension(toFilePath);
// Thumbnails.of(serverPath).scale(1f)
// .outputQuality(0.5f)
// .outputFormat("jpg")
// .toFile(getServerPath(removeExtensionFilePath));
// toFilePath = removeExtensionFilePath + ".jpg";
// } else {
// Thumbnails.of(serverPath).scale(1f).outputQuality(0.5f)
// .toFile(getServerPath(toFilePath));
// }
//
// // 删除被压缩的文件
// FileUtils.forceDelete(new File(serverPath));
//
// return toFilePath;
// }
/**
* 生成文件文件名
* @param fileName 文件名
* @author Mr.Zhang
* @since 2020-05-08
*/
public static String getDestPath(String fileName) {
//规则: 子目录/年/月/日.后缀名
return getServerPath() + fileName;
}
public static String fileName(String extName){
return CrmebUtil.getUuid() + RandomUtil.randomString(10) + "." + extName;
}
/**
* 生成文件在的实际的路径
* @author Mr.Zhang
* @since 2020-05-08
*/
private static String getServerPath() {
// 文件分隔符转化为当前系统的格式
return FilenameUtils.separatorsToSystem( getRootPath() + getWebPath());
}
/**
* web目录可访问的路径
* @author Mr.Zhang
* @since 2020-05-08
*/
private static String getWebPath() {
// 文件分隔符转化为当前系统的格式
return getType() + getModelPath() + DateUtil.nowDate(Constants.DATE_FORMAT_DATE).replace("-", "/") + "/";
}
/**
* 检测文件大小上限
* @author Mr.Zhang
* @since 2020-05-08
*/
private static void checkSize(Long size) {
// 文件分隔符转化为当前系统的格式
float fileSize = (float)size / 1024 / 1024;
String fs = String.format("%.2f", fileSize);
if( fileSize > getSize()){
throw new CrmebException("最大允许上传" + getSize() + " MB的文件, 当前文件大小为 " + fs + " MB");
}
}
/**
* 上传文件
* @param multipartFile 上传的文件对象,必传
* @author Mr.Zhang
* @since 2020-05-08
*/
private static FileResultVo saveFile(MultipartFile multipartFile) throws IOException {
if (null == multipartFile || multipartFile.isEmpty()) {
throw new CrmebException("上传的文件对象不存在...");
}
// 文件名
String fileName = multipartFile.getOriginalFilename();
// 文件后缀名
String extName = FilenameUtils.getExtension(fileName);
if (StringUtils.isEmpty(extName)) {
throw new RuntimeException("文件类型未定义不能上传...");
}
//文件大小验证
checkSize(multipartFile.getSize());
// 判断文件的后缀名是否符合规则
isContains(extName);
//文件名
String newFileName = fileName(extName);
// 创建目标文件的名称规则请看destPath方法
String destPath = getDestPath(newFileName);
// 创建文件
File file = createFile(destPath);
// 保存文件
multipartFile.transferTo(file);
// 拼装返回的数据
FileResultVo result = new FileResultVo();
//如果是图片,就进行图片处理
if (BooleanUtils.isTrue(isIsCompress())) {
// // 图片处理
// String toFilePath = thumbnails(serverPath, childFile, extName);
// // 得到处理后的图片文件对象
// File file = new File(getServerPath());
// // 压缩后的文件后缀名
// String extExtName = FilenameUtils.getExtension(toFilePath);
// // 源文件=源文件名.压缩后的后缀名
// String extFileName = FilenameUtils.getBaseName(fileName) + "." + FilenameUtils.getExtension(toFilePath);
// result.setFileSize(file.length());
// result.setServerPath(toFilePath);
// result.setFileName(extFileName);
// result.setExtName(extExtName);
} else {
result.setFileSize(multipartFile.getSize());
result.setFileName(fileName);
result.setExtName(extName);
result.setServerPath(destPath);
result.setUrl(getWebPath() + newFileName);
result.setType(multipartFile.getContentType());
}
return result;
}
/**
* 上传
* @param multipartFile 上传的文件对象,必传
* @since 2020-05-08
* @author Mr.Zhang
*/
public static FileResultVo file(MultipartFile multipartFile) throws IOException {
return saveFile(multipartFile);
}
}

View File

@@ -0,0 +1,94 @@
package com.utils;
import com.alibaba.fastjson.JSONObject;
import com.exception.CrmebException;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* http通用工具类
*
*/
public class UploadWeChatMediaUtil {
/**
* 把文件上传到指定url上去
* @param url 上传地址
* @param file 待上传文件
*/
public static JSONObject uploadFile(String url, InputStream file, String fileName) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000).build();
httppost.setConfig(requestConfig);
/**
* 这一步最关键:
*调用addBinaryBody("media",input2byte(file),ContentType.DEFAULT_BINARY, fileName),
* fileName可以为任意值但不能为null如果为null则上传失败。
* input2byte(file)把inputstream转为byte[]
* 如果直接调用addPart用FileBody做参数则MultifilePart不好转换
* 如果直接调用addPart用InpustreamBody做参数则因为没有fileName会造成上传失败
*/
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addBinaryBody("media", input2byte(file), ContentType.DEFAULT_BINARY,
fileName).build();
httppost.setEntity(reqEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseEntityStr = EntityUtils.toString(response.getEntity());
return JSONObject.parseObject(responseEntityStr);
}
EntityUtils.consume(resEntity);
}catch (Exception e){
e.printStackTrace();
throw new CrmebException(e.getMessage());
}finally {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
throw new CrmebException(e.getMessage());
} finally {
try {
httpclient.close();
} catch (IOException e) {
throw new CrmebException(e.getMessage());
}
}
return null;
}
private static byte[] input2byte(InputStream inStream)
throws IOException {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = inStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
return swapStream.toByteArray();
}
}

View File

@@ -0,0 +1,69 @@
package com.utils;
import java.util.HashMap;
import java.util.Map;
/**
* url 工具类
*/
public class UrlUtil {
public static class UrlEntity {
/**
* 基础url
*/
public String baseUrl;
/**
* url参数
*/
public Map<String, String> params;
}
/**
* 解析url
*
* @param url
* @return
*/
public static UrlEntity parse(String url) {
UrlEntity entity = new UrlEntity();
if (url == null) {
return entity;
}
url = url.trim();
if (url.equals("")) {
return entity;
}
String[] urlParts = url.split("\\?");
entity.baseUrl = urlParts[0];
//没有参数
if (urlParts.length == 1) {
return entity;
}
//有参数
String[] params = urlParts[1].split("&");
entity.params = new HashMap<>();
for (String param : params) {
String[] keyValue = param.split("=");
entity.params.put(keyValue[0], keyValue[1]);
}
return entity;
}
public static String getParamsByKey(String url,String key){
UrlEntity entity = parse(url);
return entity.params.get(key);
}
/**
* 测试
*
* @param args
*/
public static void main(String[] args) {
UrlEntity entity = parse(null);
entity = parse("http://www.123.com?id=1&name=小明");
System.out.println(entity.baseUrl + "\n" + entity.params);
System.out.println(entity.params.get("id"));
}
}

View File

@@ -0,0 +1,203 @@
package com.utils;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.Random;
import javax.imageio.ImageIO;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.druid.util.Base64;
import org.springframework.stereotype.Component;
/**
* 验证码生成工具类
* @author Mr.Zhang
* @since 2020-04-16
*/
@Component
public class ValidateCodeUtil {
private static Validate validate = null; //验证码类用于最后返回此对象包含验证码图片base64和真值
private static Random random = new Random(); //随机类,用于生成随机参数
private static String randString = "0123456789abcdefghijkmnpqrtyABCDEFGHIJLMNQRTY";//随机生成字符串的取值范围
private static int width = 80; //图片宽度
private static int height = 34; //图片高度
private static int stringNum = 4; //字符的数量
private static int lineSize = 40; //干扰线数量
/**
* 将构造函数私有化 禁止new创建
* @author Mr.Zhang
* @since 2020-04-16
*/
private ValidateCodeUtil() {
super();
}
/**
* 获取随机字符
* @author Mr.Zhang
* @since 2020-04-16
* @return String
*/
private static String getRandomChar(int index) {
//获取指定位置index的字符并转换成字符串表示形式
return String.valueOf(randString.charAt(index));
}
/**
* 获取随机指定区间的随机数
* @param min (指定最小数)
* @param max (指定最大数)
* @author Mr.Zhang
* @since 2020-04-16
* @return String
*/
private static int getRandomNum(int min,int max) {
return RandomUtil.randomInt(min, max);
}
/**
* 获得字体
*/
private static Font getFont() {
return new Font("Fixedsys", Font.CENTER_BASELINE, 25); //名称、样式、磅值
}
/**
* 获得颜色
* @param frontColor 覆盖颜色
* @param backColor 背景色
* @author Mr.Zhang
* @since 2020-04-16
* @return Color
*/
private static Color getRandColor(int frontColor, int backColor) {
if(frontColor > 255)
frontColor = 255;
if(backColor > 255)
backColor = 255;
int red = frontColor + random.nextInt(backColor - frontColor - 16);
int green = frontColor + random.nextInt(backColor - frontColor -14);
int blue = frontColor + random.nextInt(backColor - frontColor -18);
return new Color(red, green, blue);
}
/**
* 绘制字符串,返回绘制的字符串
* @param graphics 获得BufferedImage对象的Graphics对象
* @param randomString 随机字符串
* @param i 坐标倍数
* @author Mr.Zhang
* @since 2020-04-16
* @return string
*/
private static String drawString(Graphics graphics, String randomString, int i) {
Graphics2D g2d = (Graphics2D) graphics;
g2d.setFont(getFont()); //设置字体
g2d.setColor(new Color(random.nextFloat(), random.nextFloat(), random.nextFloat()));//设置颜色
String randChar = String.valueOf(getRandomChar(random.nextInt(randString.length())));
randomString += randChar; //组装
int rot = getRandomNum(5,10);
g2d.translate(random.nextInt(3), random.nextInt(3));
g2d.rotate(rot * Math.PI / 180);
g2d.drawString(randChar, 13*i, 20);
g2d.rotate(-rot * Math.PI / 180);
return randomString;
}
/**
* 绘制干扰线
* @param graphics 获得BufferedImage对象的Graphics对象
* @author Mr.Zhang
* @since 2020-04-16
*/
private static void drawLine(Graphics graphics) {
//起点(x,y) 偏移量x1、y1
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(13);
int yl = random.nextInt(15);
graphics.setColor(new Color(random.nextFloat(), random.nextFloat(), random.nextFloat()));
graphics.drawLine(x, y, x + xl, y + yl);
}
/**
* 生成Base64图片验证码
* @author Mr.Zhang
* @since 2020-04-16
* @return String
*/
public static Validate getRandomCode() {
validate = validate==null?new Validate():validate;
// BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
Graphics Graphics = image.getGraphics();// 获得BufferedImage对象的Graphics对象
Graphics.fillRect(0, 0, width, height);//填充矩形
Graphics.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));//设置字体
Graphics.setColor(getRandColor(110, 133));//设置颜色
//绘制干扰线
for(int i = 0; i <= lineSize; i++) {
drawLine(Graphics);
}
//绘制字符
String randomString = "";
for(int i = 1; i <= stringNum; i++) {
randomString = drawString(Graphics, randomString, i);
validate.setValue(randomString);
}
Graphics.dispose();//释放绘图资源
ByteArrayOutputStream bs = null;
try {
bs = new ByteArrayOutputStream();
ImageIO.write(image, "png", bs);//将绘制得图片输出到流
String imgSrc = Base64.byteArrayToBase64(bs.toByteArray());
validate.setBase64Str(imgSrc);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bs.close();
} catch (IOException e) {
e.printStackTrace();
}finally{
bs = null;
}
}
return validate;
}
/**
* 验证码类
* @author Mr.Zhang
* @since 2020-04-16
*/
public static class Validate implements Serializable{
private static final long serialVersionUID = 1L;
private String Base64Str; //Base64 值
private String value; //验证码值
public String getBase64Str() {
return Base64Str;
}
public void setBase64Str(String base64Str) {
Base64Str = base64Str;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}

View File

@@ -0,0 +1,188 @@
package com.utils;
import com.constants.RegularConstants;
import com.exception.CrmebException;
import com.zbkj.crmeb.system.model.SystemConfig;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
import java.util.regex.Pattern;
/** 表单验证类
* @author Mr.zhang
* @Description 表单验证类
* @since 2020-05-11
**/
public class ValidateFormUtil {
/**
* 检测类型
* @param systemConfig SystemConfig 需要验证的类
* @author Mr.Zhang
* @since 2020-05-11
*/
public static void checkType(SystemConfig systemConfig, String rule){
if(StringUtils.isBlank(rule)){
return;
}
//required:true,min:0,max:100,number:true
List<String> list = CrmebUtil.stringToArrayStr(rule);
for (String value : list) {
List<String> val = CrmebUtil.stringToArrayStrRegex(value, ":");
////必填
if(val.get(0).equals("required") && val.get(1).equals("true")){
isRequire(systemConfig.getValue(), systemConfig.getTitle());
continue;
}
//数字
if(val.get(0).equals("number") && val.get(1).equals("true")){
isNumber(systemConfig.getValue(), systemConfig.getTitle());
continue;
}
//最大值
if(val.get(0).equals("max")){
isNumber(systemConfig.getValue(), systemConfig.getTitle());
continue;
}
//最小值
if(val.get(0).equals("min")){
isNumber(systemConfig.getValue(), systemConfig.getTitle());
continue;
}
//邮箱
if(val.get(0).equals("email") && val.get(1).equals("true")){
isEmail(systemConfig.getValue(), systemConfig.getTitle());
continue;
}
//手机
if(val.get(0).equals("phone") && val.get(1).equals("true")){
isPhone(systemConfig.getValue(), systemConfig.getTitle());
}
}
}
/**
* 邮箱
* @param value String 值
* @param info String 字段名
* @author Mr.Zhang
* @since 2020-05-11
*/
public static void isEmail(String value, String info) {
regularException(value, info, RegularConstants.EMAIL, "邮箱");
}
/**
* 手机
* @param value String 值
* @param info String 字段名
* @author Mr.Zhang
* @since 2020-05-11
*/
public static void isPhone(String value, String info) {
regularException(value, info, RegularConstants.PHONE, "手机");
}
/**
* 验证必填
* @param value String 值
* @param info String 字段名
* @author Mr.Zhang
* @since 2020-05-11
*/
public static void isRequire(String value, String info){
if(StringUtils.isBlank(value) ){
throw new CrmebException("请填写/选择" + info);
}
}
/**
* 数字验证
* @param value String 值
* @param info String 字段名
* @author Mr.Zhang
* @since 2020-05-11
*/
public static void isNumber(String value, String info){
regularException(value, info, RegularConstants.NUMBER, "数字");
}
/**
* 数字范围
* @param value String 值
* @param info String 字段名
* @author Mr.Zhang
* @since 2020-05-11
*/
public static void range(String value, String info, Integer max, Integer min){
isNumber(value, info);
max(value, info, max);
min(value, info, min);
}
/**
* 最大数值
* @param value String 值
* @param info String 字段名
* @author Mr.Zhang
* @since 2020-05-11
*/
public static void max(String value, String info, Integer max){
isNumber(value, info);
int number = Integer.parseInt(value);
if(number > max ){
throw new CrmebException(info + "不在取值范围内,最大不能大于" + max);
}
}
/**
* 最小数值
* @param value String 值
* @param info String 字段名
* @author Mr.Zhang
* @since 2020-05-11
*/
public static void min(String value, String info, Integer min){
isNumber(value, info);
int number = Integer.parseInt(value);
if(number > min ){
throw new CrmebException(info + "不在取值范围内,最小不能小于" + min);
}
}
/**
* 正则表达式验证
* @param value String 值
* @param info String 字段名
* @param regular String 正则表达式
* @author Mr.Zhang
* @since 2020-05-11
*/
public static void regularException(String value, String info, String regular, String title){
if(!regular(value, info, regular)){
//正则验证
throw new CrmebException(info + " 格式必须为 " + title);
}
}
/**
* 正则表达式验证
* @param value String 值
* @param info String 字段名
* @param regular String 正则表达式
* @author Mr.Zhang
* @since 2020-05-11
*/
public static boolean regular(String value, String info, String regular){
isRequire(value, info);
Pattern pattern = Pattern.compile(regular);
return pattern.matcher(value).matches();
}
}

View File

@@ -0,0 +1,87 @@
package com.utils;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.naming.NoNameCoder;
import com.thoughtworks.xstream.io.xml.Xpp3Driver;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class XmlUtil {
public static Map<String,String> xmlToMap(HttpServletRequest request)
{
Map<String,String> map = new HashMap<>();
SAXReader reader = new SAXReader();
InputStream in = null;
try {
in = request.getInputStream();
Document doc = reader.read(in);
Element root = doc.getRootElement();
List<Element> list = root.elements();
for (Element element : list) {
map.put(element.getName(), element.getText());
}
} catch (IOException | DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
assert in != null;
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return map;
}
/**
* 将发送消息封装成对应的xml格式
*/
public static HashMap<String,Object> xmlToMap(String strxml)throws Exception{
strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
HashMap<String,Object> map = new HashMap<>();
SAXReader reader = new SAXReader();
InputStream inputStream = new ByteArrayInputStream(strxml.getBytes(StandardCharsets.UTF_8));
if(StringUtils.isBlank(strxml)) {
return null;
}
Document document = reader.read(inputStream);
Element root = document.getRootElement();
List<Element> list = root.elements();
for (Element e : list){
map.put(e.getName(),e.getText());
}
inputStream.close();
return map;
}
/**
* 将发送消息封装成对应的xml格式
*/
public static String objectToXml(Object object) {
XStream xstream = new XStream(new Xpp3Driver(new NoNameCoder())); //不需要转义
xstream.alias("xml", object.getClass());
return xstream.toXML(object);
}
}

View File

@@ -0,0 +1,28 @@
package com.utils.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
/**
* 图片合成详情
* @author Mr.Zhang
* @since 2020-04-18
*/
@Data
public class ImageMergeUtilVo {
@ApiModelProperty(value = "图片地址", required = true)
@NotBlank(message = "图片地址必须填写")
private String path; //地址
@ApiModelProperty(value = "x轴", required = true)
@Min(value = 0, message = "x轴至少为0")
private int x; //x轴
@ApiModelProperty(value = "y轴", required = true)
@Min(value = 0, message = "y轴至少为0")
private int y; //y轴
}

View File

@@ -0,0 +1,23 @@
package com.utils.vo;
import lombok.Data;
/**
* @author stivepeim
* @title: dateLimitVoUtil
* @projectName crmeb
* @Description: 工具类
* @since 2020/4/1414:37
*/
@Data
public class dateLimitUtilVo {
public dateLimitUtilVo() {}
public dateLimitUtilVo(String startTime, String endTime) {
this.startTime = startTime;
this.endTime = endTime;
}
private String startTime; //开始时间
private String endTime; //结束时间
}