Commit fd9fb2a6 authored by dqjdda's avatar dqjdda
Browse files

Merge branch '2.3dev'

parents 7895e547 1839ef8d
...@@ -14,7 +14,7 @@ public class ElAdminConstant { ...@@ -14,7 +14,7 @@ public class ElAdminConstant {
/** /**
* 用于IP定位转换 * 用于IP定位转换
*/ */
public static final String REGION = "内网IP|内网IP"; static final String REGION = "内网IP|内网IP";
/** /**
* 常用接口 * 常用接口
......
...@@ -6,6 +6,7 @@ import javax.crypto.SecretKey; ...@@ -6,6 +6,7 @@ import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory; import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec; import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.StandardCharsets;
/** /**
* 加密 * 加密
...@@ -18,32 +19,29 @@ public class EncryptUtils { ...@@ -18,32 +19,29 @@ public class EncryptUtils {
/** /**
* 对称加密 * 对称加密
* @param source
* @return
* @throws Exception
*/ */
public static String desEncrypt(String source) throws Exception { public static String desEncrypt(String source) throws Exception {
if (source == null || source.length() == 0){ if (source == null || source.length() == 0){
return null; return null;
} }
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(strKey.getBytes("UTF-8")); DESKeySpec desKeySpec = new DESKeySpec(strKey.getBytes(StandardCharsets.UTF_8));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec); SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(strParam.getBytes("UTF-8")); IvParameterSpec iv = new IvParameterSpec(strParam.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv); cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
return byte2hex( return byte2hex(
cipher.doFinal(source.getBytes("UTF-8"))).toUpperCase(); cipher.doFinal(source.getBytes(StandardCharsets.UTF_8))).toUpperCase();
} }
public static String byte2hex(byte[] inStr) { private static String byte2hex(byte[] inStr) {
String stmp; String stmp;
StringBuffer out = new StringBuffer(inStr.length * 2); StringBuilder out = new StringBuilder(inStr.length * 2);
for (int n = 0; n < inStr.length; n++) { for (byte b : inStr) {
stmp = Integer.toHexString(inStr[n] & 0xFF); stmp = Integer.toHexString(b & 0xFF);
if (stmp.length() == 1) { if (stmp.length() == 1) {
// 如果是0至F的单位字符串,则添加0 // 如果是0至F的单位字符串,则添加0
out.append("0" + stmp); out.append("0").append(stmp);
} else { } else {
out.append(stmp); out.append(stmp);
} }
...@@ -51,8 +49,7 @@ public class EncryptUtils { ...@@ -51,8 +49,7 @@ public class EncryptUtils {
return out.toString(); return out.toString();
} }
private static byte[] hex2byte(byte[] b) {
public static byte[] hex2byte(byte[] b) {
if ((b.length % 2) != 0){ if ((b.length % 2) != 0){
throw new IllegalArgumentException("长度不是偶数"); throw new IllegalArgumentException("长度不是偶数");
} }
...@@ -66,9 +63,6 @@ public class EncryptUtils { ...@@ -66,9 +63,6 @@ public class EncryptUtils {
/** /**
* 对称解密 * 对称解密
* @param source
* @return
* @throws Exception
*/ */
public static String desDecrypt(String source) throws Exception { public static String desDecrypt(String source) throws Exception {
if (source == null || source.length() == 0){ if (source == null || source.length() == 0){
...@@ -76,10 +70,10 @@ public class EncryptUtils { ...@@ -76,10 +70,10 @@ public class EncryptUtils {
} }
byte[] src = hex2byte(source.getBytes()); byte[] src = hex2byte(source.getBytes());
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(strKey.getBytes("UTF-8")); DESKeySpec desKeySpec = new DESKeySpec(strKey.getBytes(StandardCharsets.UTF_8));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec); SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(strParam.getBytes("UTF-8")); IvParameterSpec iv = new IvParameterSpec(strParam.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv); cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] retByte = cipher.doFinal(src); byte[] retByte = cipher.doFinal(src);
return new String(retByte); return new String(retByte);
...@@ -87,8 +81,6 @@ public class EncryptUtils { ...@@ -87,8 +81,6 @@ public class EncryptUtils {
/** /**
* 密码加密 * 密码加密
* @param password
* @return
*/ */
public static String encryptPassword(String password){ public static String encryptPassword(String password){
return DigestUtils.md5DigestAsHex(password.getBytes()); return DigestUtils.md5DigestAsHex(password.getBytes());
......
...@@ -11,6 +11,7 @@ import javax.activation.MimetypesFileTypeMap; ...@@ -11,6 +11,7 @@ import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletOutputStream; import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.*; import java.io.*;
import java.security.MessageDigest;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
...@@ -44,8 +45,6 @@ public class FileUtil extends cn.hutool.core.io.FileUtil { ...@@ -44,8 +45,6 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
/** /**
* MultipartFile转File * MultipartFile转File
* @param multipartFile
* @return
*/ */
public static File toFile(MultipartFile multipartFile){ public static File toFile(MultipartFile multipartFile){
// 获取文件名 // 获取文件名
...@@ -65,21 +64,7 @@ public class FileUtil extends cn.hutool.core.io.FileUtil { ...@@ -65,21 +64,7 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
} }
/** /**
* 删除 * 获取文件扩展名,不带 .
* @param files
*/
public static void deleteFile(File... files) {
for (File file : files) {
if (file.exists()) {
file.delete();
}
}
}
/**
* 获取文件扩展名
* @param filename
* @return
*/ */
public static String getExtensionName(String filename) { public static String getExtensionName(String filename) {
if ((filename != null) && (filename.length() > 0)) { if ((filename != null) && (filename.length() > 0)) {
...@@ -93,8 +78,6 @@ public class FileUtil extends cn.hutool.core.io.FileUtil { ...@@ -93,8 +78,6 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
/** /**
* Java文件操作 获取不带扩展名的文件名 * Java文件操作 获取不带扩展名的文件名
* @param filename
* @return
*/ */
public static String getFileNameNoEx(String filename) { public static String getFileNameNoEx(String filename) {
if ((filename != null) && (filename.length() > 0)) { if ((filename != null) && (filename.length() > 0)) {
...@@ -108,11 +91,9 @@ public class FileUtil extends cn.hutool.core.io.FileUtil { ...@@ -108,11 +91,9 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
/** /**
* 文件大小转换 * 文件大小转换
* @param size
* @return
*/ */
public static String getSize(long size){ public static String getSize(long size){
String resultSize = ""; String resultSize;
if (size / GB >= 1) { if (size / GB >= 1) {
//如果当前Byte的值大于等于1GB //如果当前Byte的值大于等于1GB
resultSize = DF.format(size / (float) GB) + "GB "; resultSize = DF.format(size / (float) GB) + "GB ";
...@@ -130,18 +111,14 @@ public class FileUtil extends cn.hutool.core.io.FileUtil { ...@@ -130,18 +111,14 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
/** /**
* inputStream 转 File * inputStream 转 File
* @param ins
* @param name
* @return
* @throws Exception
*/ */
public static File inputStreamToFile(InputStream ins, String name) throws Exception{ static File inputStreamToFile(InputStream ins, String name) throws Exception{
File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name); File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);
if (file.exists()) { if (file.exists()) {
return file; return file;
} }
OutputStream os = new FileOutputStream(file); OutputStream os = new FileOutputStream(file);
int bytesRead = 0; int bytesRead;
byte[] buffer = new byte[8192]; byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) { while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead); os.write(buffer, 0, bytesRead);
...@@ -153,10 +130,6 @@ public class FileUtil extends cn.hutool.core.io.FileUtil { ...@@ -153,10 +130,6 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
/** /**
* 将文件名解析成文件的上传路径 * 将文件名解析成文件的上传路径
*
* @param file
* @param filePath
* @return 上传到服务器的文件名
*/ */
public static File upload(MultipartFile file, String filePath) { public static File upload(MultipartFile file, String filePath) {
Date date = new Date(); Date date = new Date();
...@@ -170,10 +143,10 @@ public class FileUtil extends cn.hutool.core.io.FileUtil { ...@@ -170,10 +143,10 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
File dest = new File(path); File dest = new File(path);
// 检测是否存在目录 // 检测是否存在目录
if (!dest.getParentFile().exists()) { if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();// 新建文件夹 dest.getParentFile().mkdirs();
} }
String d = dest.getPath(); // 文件写入
file.transferTo(dest);// 文件写入 file.transferTo(dest);
return dest; return dest;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
...@@ -183,20 +156,16 @@ public class FileUtil extends cn.hutool.core.io.FileUtil { ...@@ -183,20 +156,16 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
public static String fileToBase64(File file) throws Exception { public static String fileToBase64(File file) throws Exception {
FileInputStream inputFile = new FileInputStream(file); FileInputStream inputFile = new FileInputStream(file);
String base64 =null; String base64;
byte[] buffer = new byte[(int)file.length()]; byte[] buffer = new byte[(int)file.length()];
inputFile.read(buffer); inputFile.read(buffer);
inputFile.close(); inputFile.close();
base64=new Base64().encode(buffer); base64=Base64.encode(buffer);
String encoded = base64.replaceAll("[\\s*\t\n\r]", ""); return base64.replaceAll("[\\s*\t\n\r]", "");
return encoded;
} }
/** /**
* 导出excel * 导出excel
* @param list
* @return
* @throws Exception
*/ */
public static void downloadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException { public static void downloadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException {
String tempPath =System.getProperty("java.io.tmpdir") + IdUtil.fastSimpleUUID() + ".xlsx"; String tempPath =System.getProperty("java.io.tmpdir") + IdUtil.fastSimpleUUID() + ".xlsx";
...@@ -217,28 +186,91 @@ public class FileUtil extends cn.hutool.core.io.FileUtil { ...@@ -217,28 +186,91 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
} }
public static String getFileType(String type) { public static String getFileType(String type) {
String documents = "txt doc pdf ppt pps xlsx xls"; String documents = "txt doc pdf ppt pps xlsx xls docx";
String music = "mp3 wav wma mpa ram ra aac aif m4a"; String music = "mp3 wav wma mpa ram ra aac aif m4a";
String video = "avi mpg mpe mpeg asf wmv mov qt rm mp4 flv m4v webm ogv ogg"; String video = "avi mpg mpe mpeg asf wmv mov qt rm mp4 flv m4v webm ogv ogg";
String image = "bmp dib pcp dif wmf gif jpg tif eps psd cdr iff tga pcd mpt png jpeg"; String image = "bmp dib pcp dif wmf gif jpg tif eps psd cdr iff tga pcd mpt png jpeg";
if(image.indexOf(type) != -1){ if(image.contains(type)){
return "图片"; return "图片";
} else if(documents.indexOf(type) != -1){ } else if(documents.contains(type)){
return "文档"; return "文档";
} else if(music.indexOf(type) != -1){ } else if(music.contains(type)){
return "音乐"; return "音乐";
} else if(video.indexOf(type) != -1){ } else if(video.contains(type)){
return "视频"; return "视频";
} else return "其他"; } else {
return "其他";
}
} }
public static String getFileTypeByMimeType(String type) { public static String getFileTypeByMimeType(String type) {
String mimeType = new MimetypesFileTypeMap().getContentType("." + type); String mimeType = new MimetypesFileTypeMap().getContentType("." + type);
return mimeType.split("\\/")[0]; return mimeType.split("/")[0];
} }
public static void checkSize(long maxSize, long size) { public static void checkSize(long maxSize, long size) {
if(size > (maxSize * 1024 * 1024)){ if(size > (maxSize * 1024 * 1024)){
throw new BadRequestException("文件超出规定大小"); throw new BadRequestException("文件超出规定大小");
} }
} }
/**
* 判断两个文件是否相同
*/
public static boolean check(File file1, File file2) {
String img1Md5 = getMd5(file1);
String img2Md5 = getMd5(file2);
return img1Md5.equals(img2Md5);
}
/**
* 判断两个文件是否相同
*/
public static boolean check(String file1Md5, String file2Md5) {
return file1Md5.equals(file2Md5);
}
private static byte[] getByte(File file) {
// 得到文件长度
byte[] b = new byte[(int) file.length()];
try {
InputStream in = new FileInputStream(file);
try {
in.read(b);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
return b;
}
private static String getMd5(byte[] bytes) {
// 16进制字符
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
try {
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(bytes);
byte[] md = mdTemp.digest();
int j = md.length;
char[] str = new char[j * 2];
int k = 0;
// 移位 输出字符串
for (byte byte0 : md) {
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String getMd5(File file) {
return getMd5(getByte(file));
}
} }
...@@ -12,10 +12,6 @@ public class PageUtil extends cn.hutool.core.util.PageUtil { ...@@ -12,10 +12,6 @@ public class PageUtil extends cn.hutool.core.util.PageUtil {
/** /**
* List 分页 * List 分页
* @param page
* @param size
* @param list
* @return
*/ */
public static List toPage(int page, int size , List list) { public static List toPage(int page, int size , List list) {
int fromIndex = page * size; int fromIndex = page * size;
...@@ -32,10 +28,8 @@ public class PageUtil extends cn.hutool.core.util.PageUtil { ...@@ -32,10 +28,8 @@ public class PageUtil extends cn.hutool.core.util.PageUtil {
/** /**
* Page 数据处理,预防redis反序列化报错 * Page 数据处理,预防redis反序列化报错
* @param page
* @return
*/ */
public static Map toPage(Page page) { public static Map<String,Object> toPage(Page page) {
Map<String,Object> map = new LinkedHashMap<>(2); Map<String,Object> map = new LinkedHashMap<>(2);
map.put("content",page.getContent()); map.put("content",page.getContent());
map.put("totalElements",page.getTotalElements()); map.put("totalElements",page.getTotalElements());
...@@ -43,11 +37,9 @@ public class PageUtil extends cn.hutool.core.util.PageUtil { ...@@ -43,11 +37,9 @@ public class PageUtil extends cn.hutool.core.util.PageUtil {
} }
/** /**
* @param object * 自定义分页
* @param totalElements
* @return
*/ */
public static Map toPage(Object object, Object totalElements) { public static Map<String,Object> toPage(Object object, Object totalElements) {
Map<String,Object> map = new LinkedHashMap<>(2); Map<String,Object> map = new LinkedHashMap<>(2);
map.put("content",object); map.put("content",object);
map.put("totalElements",totalElements); map.put("totalElements",totalElements);
......
...@@ -15,18 +15,12 @@ import java.util.*; ...@@ -15,18 +15,12 @@ import java.util.*;
@Slf4j @Slf4j
public class QueryHelp { public class QueryHelp {
/**
* @描述 : 转换为Predicate
* @作者 : Dong ZhaoYang
* @日期 : 2017/8/7
* @时间 : 17:25
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <R, Q> Predicate getPredicate(Root<R> root, Q query, CriteriaBuilder cb) { public static <R, Q> Predicate getPredicate(Root<R> root, Q query, CriteriaBuilder cb) {
List<Predicate> list = new ArrayList<>(); List<Predicate> list = new ArrayList<>();
if(query == null){ if(query == null){
return cb.and(list.toArray(new Predicate[list.size()])); return cb.and(list.toArray(new Predicate[0]));
} }
try { try {
List<Field> fields = getAllFields(query.getClass(), new ArrayList<>()); List<Field> fields = getAllFields(query.getClass(), new ArrayList<>());
...@@ -62,19 +56,20 @@ public class QueryHelp { ...@@ -62,19 +56,20 @@ public class QueryHelp {
for (String name : joinNames) { for (String name : joinNames) {
switch (q.join()) { switch (q.join()) {
case LEFT: case LEFT:
if(ObjectUtil.isNotEmpty(join)){ if(ObjectUtil.isNotNull(join)){
join = join.join(name, JoinType.LEFT); join = join.join(name, JoinType.LEFT);
} else { } else {
join = root.join(name, JoinType.LEFT); join = root.join(name, JoinType.LEFT);
} }
break; break;
case RIGHT: case RIGHT:
if(ObjectUtil.isNotEmpty(join)){ if(ObjectUtil.isNotNull(join)){
join = join.join(name, JoinType.RIGHT); join = join.join(name, JoinType.RIGHT);
} else { } else {
join = root.join(name, JoinType.RIGHT); join = root.join(name, JoinType.RIGHT);
} }
break; break;
default: break;
} }
} }
} }
...@@ -111,6 +106,7 @@ public class QueryHelp { ...@@ -111,6 +106,7 @@ public class QueryHelp {
list.add(getExpression(attributeName,join,root).in((Collection<Long>) val)); list.add(getExpression(attributeName,join,root).in((Collection<Long>) val));
} }
break; break;
default: break;
} }
} }
field.setAccessible(accessible); field.setAccessible(accessible);
...@@ -118,7 +114,8 @@ public class QueryHelp { ...@@ -118,7 +114,8 @@ public class QueryHelp {
} catch (Exception e) { } catch (Exception e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
} }
return cb.and(list.toArray(new Predicate[list.size()])); int size = list.size();
return cb.and(list.toArray(new Predicate[size]));
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
...@@ -130,21 +127,19 @@ public class QueryHelp { ...@@ -130,21 +127,19 @@ public class QueryHelp {
} }
} }
@SuppressWarnings("unchecked") private static boolean isBlank(final CharSequence cs) {
public static boolean isBlank(final CharSequence cs) {
int strLen; int strLen;
if (cs == null || (strLen = cs.length()) == 0) { if (cs == null || (strLen = cs.length()) == 0) {
return true; return true;
} }
for (int i = 0; i < strLen; i++) { for (int i = 0; i < strLen; i++) {
if (Character.isWhitespace(cs.charAt(i)) == false) { if (!Character.isWhitespace(cs.charAt(i))) {
return false; return false;
} }
} }
return true; return true;
} }
@SuppressWarnings("unchecked")
private static List<Field> getAllFields(Class clazz, List<Field> fields) { private static List<Field> getAllFields(Class clazz, List<Field> fields) {
if (clazz != null) { if (clazz != null) {
fields.addAll(Arrays.asList(clazz.getDeclaredFields())); fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
......
...@@ -3,6 +3,7 @@ package me.zhengjie.utils; ...@@ -3,6 +3,7 @@ package me.zhengjie.utils;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
/** /**
* 获取 HttpServletRequest * 获取 HttpServletRequest
...@@ -12,6 +13,6 @@ import javax.servlet.http.HttpServletRequest; ...@@ -12,6 +13,6 @@ import javax.servlet.http.HttpServletRequest;
public class RequestHolder { public class RequestHolder {
public static HttpServletRequest getHttpServletRequest() { public static HttpServletRequest getHttpServletRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
} }
} }
...@@ -13,7 +13,7 @@ import org.springframework.security.core.userdetails.UserDetails; ...@@ -13,7 +13,7 @@ import org.springframework.security.core.userdetails.UserDetails;
public class SecurityUtils { public class SecurityUtils {
public static UserDetails getUserDetails() { public static UserDetails getUserDetails() {
UserDetails userDetails = null; UserDetails userDetails;
try { try {
userDetails = (UserDetails) org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication().getPrincipal(); userDetails = (UserDetails) org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication().getPrincipal();
} catch (Exception e) { } catch (Exception e) {
...@@ -28,8 +28,7 @@ public class SecurityUtils { ...@@ -28,8 +28,7 @@ public class SecurityUtils {
*/ */
public static String getUsername(){ public static String getUsername(){
Object obj = getUserDetails(); Object obj = getUserDetails();
JSONObject json = new JSONObject(obj); return new JSONObject(obj).get("username", String.class);
return json.get("username", String.class);
} }
/** /**
...@@ -38,7 +37,6 @@ public class SecurityUtils { ...@@ -38,7 +37,6 @@ public class SecurityUtils {
*/ */
public static Long getUserId(){ public static Long getUserId(){
Object obj = getUserDetails(); Object obj = getUserDetails();
JSONObject json = new JSONObject(obj); return new JSONObject(obj).get("id", Long.class);
return json.get("id", Long.class);
} }
} }
...@@ -7,7 +7,7 @@ import org.springframework.context.ApplicationContext; ...@@ -7,7 +7,7 @@ import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationContextAware;
/** /**
* @author * @author Jie
* @date 2019-01-07 * @date 2019-01-07
*/ */
@Slf4j @Slf4j
...@@ -15,17 +15,10 @@ public class SpringContextHolder implements ApplicationContextAware, DisposableB ...@@ -15,17 +15,10 @@ public class SpringContextHolder implements ApplicationContextAware, DisposableB
private static ApplicationContext applicationContext = null; private static ApplicationContext applicationContext = null;
/**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
assertContextInjected();
return applicationContext;
}
/** /**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/ */
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) { public static <T> T getBean(String name) {
assertContextInjected(); assertContextInjected();
return (T) applicationContext.getBean(name); return (T) applicationContext.getBean(name);
...@@ -52,14 +45,14 @@ public class SpringContextHolder implements ApplicationContextAware, DisposableB ...@@ -52,14 +45,14 @@ public class SpringContextHolder implements ApplicationContextAware, DisposableB
/** /**
* 清除SpringContextHolder中的ApplicationContext为Null. * 清除SpringContextHolder中的ApplicationContext为Null.
*/ */
public static void clearHolder() { private static void clearHolder() {
log.debug("清除SpringContextHolder中的ApplicationContext:" log.debug("清除SpringContextHolder中的ApplicationContext:"
+ applicationContext); + applicationContext);
applicationContext = null; applicationContext = null;
} }
@Override @Override
public void destroy() throws Exception { public void destroy(){
SpringContextHolder.clearHolder(); SpringContextHolder.clearHolder();
} }
......
package me.zhengjie.utils; package me.zhengjie.utils;
import cn.hutool.core.io.resource.ClassPathResource; import cn.hutool.core.io.resource.ClassPathResource;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import org.lionsoul.ip2region.DataBlock; import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig; import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher; import org.lionsoul.ip2region.DbSearcher;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.io.File; import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
...@@ -18,25 +20,6 @@ import java.util.Date; ...@@ -18,25 +20,6 @@ import java.util.Date;
public class StringUtils extends org.apache.commons.lang3.StringUtils { public class StringUtils extends org.apache.commons.lang3.StringUtils {
private static final char SEPARATOR = '_'; private static final char SEPARATOR = '_';
private static final String CHARSET_NAME = "UTF-8";
/**
* 是否包含字符串
*
* @param str 验证字符串
* @param strs 字符串组
* @return 包含返回true
*/
public static boolean inString(String str, String... strs) {
if (str != null) {
for (String s : strs) {
if (str.equals(trim(s))) {
return true;
}
}
}
return false;
}
/** /**
* 驼峰命名法工具 * 驼峰命名法工具
...@@ -92,7 +75,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { ...@@ -92,7 +75,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
* toCapitalizeCamelCase("hello_world") == "HelloWorld" * toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world" * toUnderScoreCase("helloWorld") = "hello_world"
*/ */
public static String toUnderScoreCase(String s) { static String toUnderScoreCase(String s) {
if (s == null) { if (s == null) {
return null; return null;
} }
...@@ -125,53 +108,45 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { ...@@ -125,53 +108,45 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
/** /**
* 获取ip地址 * 获取ip地址
* @param request
* @return
*/ */
public static String getIP(HttpServletRequest request) { public static String getIp(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for"); String ip = request.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP"); ip = request.getHeader("Proxy-Client-IP");
} }
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP"); ip = request.getHeader("WL-Proxy-Client-IP");
} }
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr(); ip = request.getRemoteAddr();
} }
String[] ips = ip.split(","); if (ip.contains(",")) {
return "0:0:0:0:0:0:0:1".equals(ips[0])?"127.0.0.1":ips[0]; ip = ip.split(",")[0];
}
if ("127.0.0.1".equals(ip)) {
// 获取本机真正的ip地址
try {
ip = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
return ip;
} }
/** /**
* 根据ip获取详细地址 * 根据ip获取详细地址
* @param ip
* @return
*/ */
public static String getCityInfo(String ip) { public static String getCityInfo(String ip) {
try { try {
String path = "ip2region/ip2region.db"; String path = "ip2region/ip2region.db";
String name = "ip2region.db"; String name = "ip2region.db";
int algorithm = DbSearcher.BTREE_ALGORITHM;
DbConfig config = new DbConfig(); DbConfig config = new DbConfig();
File file = FileUtil.inputStreamToFile(new ClassPathResource(path).getStream(), name); File file = FileUtil.inputStreamToFile(new ClassPathResource(path).getStream(), name);
DbSearcher searcher = new DbSearcher(config, file.getPath()); DbSearcher searcher = new DbSearcher(config, file.getPath());
Method method = null; Method method;
switch (algorithm) { method = searcher.getClass().getMethod("btreeSearch", String.class);
case DbSearcher.BTREE_ALGORITHM: DataBlock dataBlock;
method = searcher.getClass().getMethod("btreeSearch", String.class);
break;
case DbSearcher.BINARY_ALGORITHM:
method = searcher.getClass().getMethod("binarySearch", String.class);
break;
case DbSearcher.MEMORY_ALGORITYM:
method = searcher.getClass().getMethod("memorySearch", String.class);
break;
default:
method = searcher.getClass().getMethod("memorySearch", String.class);
break;
}
DataBlock dataBlock = null;
dataBlock = (DataBlock) method.invoke(searcher, ip); dataBlock = (DataBlock) method.invoke(searcher, ip);
String address = dataBlock.getRegion().replace("0|",""); String address = dataBlock.getRegion().replace("0|","");
if(address.charAt(address.length()-1) == '|'){ if(address.charAt(address.length()-1) == '|'){
...@@ -184,6 +159,12 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { ...@@ -184,6 +159,12 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
return ""; return "";
} }
public static String getBrowser(HttpServletRequest request){
UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
Browser browser = userAgent.getBrowser();
return browser.getName();
}
/** /**
* 获得当天是周几 * 获得当天是周几
*/ */
......
...@@ -2,30 +2,23 @@ package me.zhengjie.utils; ...@@ -2,30 +2,23 @@ package me.zhengjie.utils;
import me.zhengjie.exception.BadRequestException; import me.zhengjie.exception.BadRequestException;
import org.hibernate.exception.ConstraintViolationException; import org.hibernate.exception.ConstraintViolationException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
/** /**
* 异常工具 * 异常工具 2019-01-06
* @author Zheng Jie * @author Zheng Jie
* @date 2019-01-06
*/ */
public class ThrowableUtil { public class ThrowableUtil {
/** /**
* 获取堆栈信息 * 获取堆栈信息
* @param throwable
* @return
*/ */
public static String getStackTrace(Throwable throwable){ public static String getStackTrace(Throwable throwable){
StringWriter sw = new StringWriter(); StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw); try (PrintWriter pw = new PrintWriter(sw)) {
try {
throwable.printStackTrace(pw); throwable.printStackTrace(pw);
return sw.toString(); return sw.toString();
} finally {
pw.close();
} }
} }
...@@ -34,9 +27,10 @@ public class ThrowableUtil { ...@@ -34,9 +27,10 @@ public class ThrowableUtil {
while ((t != null) && !(t instanceof ConstraintViolationException)) { while ((t != null) && !(t instanceof ConstraintViolationException)) {
t = t.getCause(); t = t.getCause();
} }
if (t instanceof ConstraintViolationException) { if (t != null) {
throw new BadRequestException(msg); throw new BadRequestException(msg);
} }
assert false;
throw new BadRequestException("删除失败:" + t.getMessage()); throw new BadRequestException("删除失败:" + t.getMessage());
} }
} }
package me.zhengjie.utils; package me.zhengjie.utils;
import cn.hutool.json.JSONArray; import cn.hutool.json.JSONArray;
import lombok.var;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
...@@ -26,7 +24,7 @@ public class TranslatorUtil { ...@@ -26,7 +24,7 @@ public class TranslatorUtil {
BufferedReader in = new BufferedReader( BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream())); new InputStreamReader(con.getInputStream()));
String inputLine; String inputLine;
StringBuffer response = new StringBuffer(); StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) { while ((inputLine = in.readLine()) != null) {
response.append(inputLine); response.append(inputLine);
...@@ -38,15 +36,12 @@ public class TranslatorUtil { ...@@ -38,15 +36,12 @@ public class TranslatorUtil {
} }
} }
private static String parseResult(String inputJson) throws Exception { private static String parseResult(String inputJson){
JSONArray jsonArray = new JSONArray(inputJson); JSONArray jsonArray2 = (JSONArray) new JSONArray(inputJson).get(0);
JSONArray jsonArray2 = (JSONArray) jsonArray.get(0); StringBuilder result = new StringBuilder();
String result =""; for (Object o : jsonArray2) {
result.append(((JSONArray) o).get(0).toString());
for(var i = 0; i < jsonArray2.size(); i ++){
result += ((JSONArray) jsonArray2.get(i)).get(0).toString();
} }
return result; return result.toString();
} }
} }
package me.zhengjie.utils; package me.zhengjie.utils;
import cn.hutool.core.util.ObjectUtil;
import me.zhengjie.exception.BadRequestException; import me.zhengjie.exception.BadRequestException;
import java.util.Optional;
/** /**
* 验证工具 * 验证工具
...@@ -12,27 +12,22 @@ public class ValidationUtil{ ...@@ -12,27 +12,22 @@ public class ValidationUtil{
/** /**
* 验证空 * 验证空
* @param optional
*/ */
public static void isNull(Optional optional, String entity,String parameter , Object value){ public static void isNull(Object obj, String entity, String parameter , Object value){
if(!optional.isPresent()){ if(ObjectUtil.isNull(obj)){
String msg = entity String msg = entity + " 不存在: "+ parameter +" is "+ value;
+ " 不存在 "
+"{ "+ parameter +":"+ value.toString() +" }";
throw new BadRequestException(msg); throw new BadRequestException(msg);
} }
} }
/** /**
* 验证是否为邮箱 * 验证是否为邮箱
* @param string
* @return
*/ */
public static boolean isEmail(String string) { public static boolean isEmail(String string) {
if (string == null){ if (string == null){
return false; return false;
} }
String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"; String regEx1 = "^([a-z0-9A-Z]+[-|.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
return string.matches(regEx1); return string.matches(regEx1);
} }
} }
...@@ -11,12 +11,6 @@ import static org.junit.Assert.*; ...@@ -11,12 +11,6 @@ import static org.junit.Assert.*;
public class StringUtilsTest { public class StringUtilsTest {
@Test
public void testInString() {
assertTrue(inString("?", "?"));
assertFalse(inString("?", new String[]{}));
}
@Test @Test
public void testToCamelCase() { public void testToCamelCase() {
assertNull(toCamelCase(null)); assertNull(toCamelCase(null));
...@@ -44,6 +38,6 @@ public class StringUtilsTest { ...@@ -44,6 +38,6 @@ public class StringUtilsTest {
@Test @Test
public void testGetIP() { public void testGetIP() {
assertEquals("127.0.0.1", getIP(new MockHttpServletRequest())); assertEquals("127.0.0.1", getIp(new MockHttpServletRequest()));
} }
} }
\ No newline at end of file
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>eladmin</artifactId> <artifactId>eladmin</artifactId>
<groupId>me.zhengjie</groupId> <groupId>me.zhengjie</groupId>
<version>2.2</version> <version>2.3</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
...@@ -20,7 +20,7 @@ ...@@ -20,7 +20,7 @@
<dependency> <dependency>
<groupId>me.zhengjie</groupId> <groupId>me.zhengjie</groupId>
<artifactId>eladmin-common</artifactId> <artifactId>eladmin-common</artifactId>
<version>2.2</version> <version>2.3</version>
</dependency> </dependency>
<!--模板引擎--> <!--模板引擎-->
......
...@@ -16,26 +16,26 @@ public class GenConfig { ...@@ -16,26 +16,26 @@ public class GenConfig {
@Id @Id
private Long id; private Long id;
/** 包路径 **/ // 包路径
private String pack; private String pack;
/** 模块名 **/ // 模块名
@Column(name = "module_name") @Column(name = "module_name")
private String moduleName; private String moduleName;
/** 前端文件路径 **/ // 前端文件路径
private String path; private String path;
/** 前端文件路径 **/ // 前端文件路径
@Column(name = "api_path") @Column(name = "api_path")
private String apiPath; private String apiPath;
/** 作者 **/ // 作者
private String author; private String author;
/** 表前缀 **/ // 表前缀
private String prefix; private String prefix;
/** 是否覆盖 **/ // 是否覆盖
private Boolean cover; private Boolean cover;
} }
...@@ -14,27 +14,27 @@ import lombok.NoArgsConstructor; ...@@ -14,27 +14,27 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor @NoArgsConstructor
public class ColumnInfo { public class ColumnInfo {
/** 数据库字段名称 **/ // 数据库字段名称
private Object columnName; private Object columnName;
/** 允许空值 **/ // 允许空值
private Object isNullable; private Object isNullable;
/** 数据库字段类型 **/ // 数据库字段类型
private Object columnType; private Object columnType;
/** 数据库字段注释 **/ // 数据库字段注释
private Object columnComment; private Object columnComment;
/** 数据库字段键类型 **/ // 数据库字段键类型
private Object columnKey; private Object columnKey;
/** 额外的参数 **/ // 额外的参数
private Object extra; private Object extra;
/** 查询 1:模糊 2:精确 **/ // 查询 1:模糊 2:精确
private String columnQuery; private String columnQuery;
/** 是否在列表显示 **/ // 是否在列表显示
private String columnShow; private String columnShow;
} }
...@@ -14,10 +14,10 @@ import lombok.NoArgsConstructor; ...@@ -14,10 +14,10 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor @NoArgsConstructor
public class TableInfo { public class TableInfo {
/** 表名称 **/ // 表名称
private Object tableName; private Object tableName;
/** 创建日期 **/ // 创建日期
private Object createTime; private Object createTime;
// 数据库引擎 // 数据库引擎
......
package me.zhengjie.rest; package me.zhengjie.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.domain.GenConfig; import me.zhengjie.domain.GenConfig;
import me.zhengjie.service.GenConfigService; import me.zhengjie.service.GenConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
...@@ -13,23 +14,25 @@ import org.springframework.web.bind.annotation.*; ...@@ -13,23 +14,25 @@ import org.springframework.web.bind.annotation.*;
* @date 2019-01-14 * @date 2019-01-14
*/ */
@RestController @RestController
@RequestMapping("api") @RequestMapping("/api/genConfig")
@Api(tags = "系统:代码生成器配置管理")
public class GenConfigController { public class GenConfigController {
@Autowired private final GenConfigService genConfigService;
private GenConfigService genConfigService;
/** public GenConfigController(GenConfigService genConfigService) {
* 查询生成器配置 this.genConfigService = genConfigService;
* @return }
*/
@GetMapping(value = "/genConfig") @ApiOperation("查询")
@GetMapping
public ResponseEntity get(){ public ResponseEntity get(){
return new ResponseEntity(genConfigService.find(), HttpStatus.OK); return new ResponseEntity<>(genConfigService.find(), HttpStatus.OK);
} }
@PutMapping(value = "/genConfig") @ApiOperation("修改")
@PutMapping
public ResponseEntity emailConfig(@Validated @RequestBody GenConfig genConfig){ public ResponseEntity emailConfig(@Validated @RequestBody GenConfig genConfig){
return new ResponseEntity(genConfigService.update(genConfig),HttpStatus.OK); return new ResponseEntity<>(genConfigService.update(genConfig),HttpStatus.OK);
} }
} }
package me.zhengjie.rest; package me.zhengjie.rest;
import cn.hutool.core.util.PageUtil; import cn.hutool.core.util.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.domain.vo.ColumnInfo; import me.zhengjie.domain.vo.ColumnInfo;
import me.zhengjie.exception.BadRequestException; import me.zhengjie.exception.BadRequestException;
import me.zhengjie.service.GenConfigService; import me.zhengjie.service.GenConfigService;
import me.zhengjie.service.GeneratorService; import me.zhengjie.service.GeneratorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
...@@ -17,49 +18,39 @@ import java.util.List; ...@@ -17,49 +18,39 @@ import java.util.List;
* @date 2019-01-02 * @date 2019-01-02
*/ */
@RestController @RestController
@RequestMapping("api") @RequestMapping("/api/generator")
@Api(tags = "系统:代码生成管理")
public class GeneratorController { public class GeneratorController {
@Autowired private final GeneratorService generatorService;
private GeneratorService generatorService;
@Autowired private final GenConfigService genConfigService;
private GenConfigService genConfigService;
@Value("${generator.enabled}") @Value("${generator.enabled}")
private Boolean generatorEnabled; private Boolean generatorEnabled;
/** public GeneratorController(GeneratorService generatorService, GenConfigService genConfigService) {
* 查询数据库元数据 this.generatorService = generatorService;
* @param name this.genConfigService = genConfigService;
* @param page }
* @param size
* @return @ApiOperation("查询数据库元数据")
*/ @GetMapping(value = "/tables")
@GetMapping(value = "/generator/tables")
public ResponseEntity getTables(@RequestParam(defaultValue = "") String name, public ResponseEntity getTables(@RequestParam(defaultValue = "") String name,
@RequestParam(defaultValue = "0")Integer page, @RequestParam(defaultValue = "0")Integer page,
@RequestParam(defaultValue = "10")Integer size){ @RequestParam(defaultValue = "10")Integer size){
int[] startEnd = PageUtil.transToStartEnd(page+1, size); int[] startEnd = PageUtil.transToStartEnd(page+1, size);
return new ResponseEntity(generatorService.getTables(name,startEnd), HttpStatus.OK); return new ResponseEntity<>(generatorService.getTables(name,startEnd), HttpStatus.OK);
} }
/** @ApiOperation("查询表内元数据")
* 查询表内元数据 @GetMapping(value = "/columns")
* @param tableName
* @return
*/
@GetMapping(value = "/generator/columns")
public ResponseEntity getTables(@RequestParam String tableName){ public ResponseEntity getTables(@RequestParam String tableName){
return new ResponseEntity(generatorService.getColumns(tableName), HttpStatus.OK); return new ResponseEntity<>(generatorService.getColumns(tableName), HttpStatus.OK);
} }
/** @ApiOperation("生成代码")
* 生成代码 @PostMapping
* @param columnInfos
* @return
*/
@PostMapping(value = "/generator")
public ResponseEntity generator(@RequestBody List<ColumnInfo> columnInfos, @RequestParam String tableName){ public ResponseEntity generator(@RequestBody List<ColumnInfo> columnInfos, @RequestParam String tableName){
if(!generatorEnabled){ if(!generatorEnabled){
throw new BadRequestException("此环境不允许生成代码!"); throw new BadRequestException("此环境不允许生成代码!");
......
package me.zhengjie.service; package me.zhengjie.service;
import me.zhengjie.domain.GenConfig; import me.zhengjie.domain.GenConfig;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
/** /**
* @author Zheng Jie * @author Zheng Jie
* @date 2019-01-14 * @date 2019-01-14
*/ */
@CacheConfig(cacheNames = "genConfig")
public interface GenConfigService { public interface GenConfigService {
/**
* find
* @return
*/
@Cacheable(key = "'1'")
GenConfig find(); GenConfig find();
/**
* update
* @param genConfig
* @return
*/
@CacheEvict(allEntries = true)
GenConfig update(GenConfig genConfig); GenConfig update(GenConfig genConfig);
} }
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment