Commit fd9fb2a6 authored by dqjdda's avatar dqjdda
Browse files

Merge branch '2.3dev'

parents 7895e547 1839ef8d
......@@ -14,7 +14,7 @@ public class ElAdminConstant {
/**
* 用于IP定位转换
*/
public static final String REGION = "内网IP|内网IP";
static final String REGION = "内网IP|内网IP";
/**
* 常用接口
......
......@@ -6,6 +6,7 @@ import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.StandardCharsets;
/**
* 加密
......@@ -18,32 +19,29 @@ public class EncryptUtils {
/**
* 对称加密
* @param source
* @return
* @throws Exception
*/
public static String desEncrypt(String source) throws Exception {
if (source == null || source.length() == 0){
return null;
}
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");
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);
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;
StringBuffer out = new StringBuffer(inStr.length * 2);
for (int n = 0; n < inStr.length; n++) {
stmp = Integer.toHexString(inStr[n] & 0xFF);
StringBuilder out = new StringBuilder(inStr.length * 2);
for (byte b : inStr) {
stmp = Integer.toHexString(b & 0xFF);
if (stmp.length() == 1) {
// 如果是0至F的单位字符串,则添加0
out.append("0" + stmp);
out.append("0").append(stmp);
} else {
out.append(stmp);
}
......@@ -51,8 +49,7 @@ public class EncryptUtils {
return out.toString();
}
public static byte[] hex2byte(byte[] b) {
private static byte[] hex2byte(byte[] b) {
if ((b.length % 2) != 0){
throw new IllegalArgumentException("长度不是偶数");
}
......@@ -66,9 +63,6 @@ public class EncryptUtils {
/**
* 对称解密
* @param source
* @return
* @throws Exception
*/
public static String desDecrypt(String source) throws Exception {
if (source == null || source.length() == 0){
......@@ -76,10 +70,10 @@ public class EncryptUtils {
}
byte[] src = hex2byte(source.getBytes());
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");
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);
byte[] retByte = cipher.doFinal(src);
return new String(retByte);
......@@ -87,8 +81,6 @@ public class EncryptUtils {
/**
* 密码加密
* @param password
* @return
*/
public static String encryptPassword(String password){
return DigestUtils.md5DigestAsHex(password.getBytes());
......
......@@ -11,6 +11,7 @@ import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
......@@ -44,8 +45,6 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
/**
* MultipartFile转File
* @param multipartFile
* @return
*/
public static File toFile(MultipartFile multipartFile){
// 获取文件名
......@@ -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) {
if ((filename != null) && (filename.length() > 0)) {
......@@ -93,8 +78,6 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
/**
* Java文件操作 获取不带扩展名的文件名
* @param filename
* @return
*/
public static String getFileNameNoEx(String filename) {
if ((filename != null) && (filename.length() > 0)) {
......@@ -108,11 +91,9 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
/**
* 文件大小转换
* @param size
* @return
*/
public static String getSize(long size){
String resultSize = "";
String resultSize;
if (size / GB >= 1) {
//如果当前Byte的值大于等于1GB
resultSize = DF.format(size / (float) GB) + "GB ";
......@@ -130,18 +111,14 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
/**
* 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);
if (file.exists()) {
return file;
}
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
int bytesRead;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
......@@ -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) {
Date date = new Date();
......@@ -170,10 +143,10 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
File dest = new File(path);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();// 新建文件夹
dest.getParentFile().mkdirs();
}
String d = dest.getPath();
file.transferTo(dest);// 文件写入
// 文件写入
file.transferTo(dest);
return dest;
} catch (Exception e) {
e.printStackTrace();
......@@ -183,20 +156,16 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
public static String fileToBase64(File file) throws Exception {
FileInputStream inputFile = new FileInputStream(file);
String base64 =null;
String base64;
byte[] buffer = new byte[(int)file.length()];
inputFile.read(buffer);
inputFile.close();
base64=new Base64().encode(buffer);
String encoded = base64.replaceAll("[\\s*\t\n\r]", "");
return encoded;
base64=Base64.encode(buffer);
return base64.replaceAll("[\\s*\t\n\r]", "");
}
/**
* 导出excel
* @param list
* @return
* @throws Exception
*/
public static void downloadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException {
String tempPath =System.getProperty("java.io.tmpdir") + IdUtil.fastSimpleUUID() + ".xlsx";
......@@ -217,28 +186,91 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
}
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 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";
if(image.indexOf(type) != -1){
if(image.contains(type)){
return "图片";
} else if(documents.indexOf(type) != -1){
} else if(documents.contains(type)){
return "文档";
} else if(music.indexOf(type) != -1){
} else if(music.contains(type)){
return "音乐";
} else if(video.indexOf(type) != -1){
} else if(video.contains(type)){
return "视频";
} else return "其他";
} else {
return "其他";
}
}
public static String getFileTypeByMimeType(String type) {
String mimeType = new MimetypesFileTypeMap().getContentType("." + type);
return mimeType.split("\\/")[0];
return mimeType.split("/")[0];
}
public static void checkSize(long maxSize, long size) {
if(size > (maxSize * 1024 * 1024)){
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 {
/**
* List 分页
* @param page
* @param size
* @param list
* @return
*/
public static List toPage(int page, int size , List list) {
int fromIndex = page * size;
......@@ -32,10 +28,8 @@ public class PageUtil extends cn.hutool.core.util.PageUtil {
/**
* 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.put("content",page.getContent());
map.put("totalElements",page.getTotalElements());
......@@ -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.put("content",object);
map.put("totalElements",totalElements);
......
......@@ -15,18 +15,12 @@ import java.util.*;
@Slf4j
public class QueryHelp {
/**
* @描述 : 转换为Predicate
* @作者 : Dong ZhaoYang
* @日期 : 2017/8/7
* @时间 : 17:25
*/
@SuppressWarnings("unchecked")
public static <R, Q> Predicate getPredicate(Root<R> root, Q query, CriteriaBuilder cb) {
List<Predicate> list = new ArrayList<>();
if(query == null){
return cb.and(list.toArray(new Predicate[list.size()]));
return cb.and(list.toArray(new Predicate[0]));
}
try {
List<Field> fields = getAllFields(query.getClass(), new ArrayList<>());
......@@ -62,19 +56,20 @@ public class QueryHelp {
for (String name : joinNames) {
switch (q.join()) {
case LEFT:
if(ObjectUtil.isNotEmpty(join)){
if(ObjectUtil.isNotNull(join)){
join = join.join(name, JoinType.LEFT);
} else {
join = root.join(name, JoinType.LEFT);
}
break;
case RIGHT:
if(ObjectUtil.isNotEmpty(join)){
if(ObjectUtil.isNotNull(join)){
join = join.join(name, JoinType.RIGHT);
} else {
join = root.join(name, JoinType.RIGHT);
}
break;
default: break;
}
}
}
......@@ -111,6 +106,7 @@ public class QueryHelp {
list.add(getExpression(attributeName,join,root).in((Collection<Long>) val));
}
break;
default: break;
}
}
field.setAccessible(accessible);
......@@ -118,7 +114,8 @@ public class QueryHelp {
} catch (Exception 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")
......@@ -130,21 +127,19 @@ public class QueryHelp {
}
}
@SuppressWarnings("unchecked")
public static boolean isBlank(final CharSequence cs) {
private static boolean isBlank(final CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (Character.isWhitespace(cs.charAt(i)) == false) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
@SuppressWarnings("unchecked")
private static List<Field> getAllFields(Class clazz, List<Field> fields) {
if (clazz != null) {
fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
......
......@@ -3,6 +3,7 @@ package me.zhengjie.utils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
/**
* 获取 HttpServletRequest
......@@ -12,6 +13,6 @@ import javax.servlet.http.HttpServletRequest;
public class RequestHolder {
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;
public class SecurityUtils {
public static UserDetails getUserDetails() {
UserDetails userDetails = null;
UserDetails userDetails;
try {
userDetails = (UserDetails) org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication().getPrincipal();
} catch (Exception e) {
......@@ -28,8 +28,7 @@ public class SecurityUtils {
*/
public static String getUsername(){
Object obj = getUserDetails();
JSONObject json = new JSONObject(obj);
return json.get("username", String.class);
return new JSONObject(obj).get("username", String.class);
}
/**
......@@ -38,7 +37,6 @@ public class SecurityUtils {
*/
public static Long getUserId(){
Object obj = getUserDetails();
JSONObject json = new JSONObject(obj);
return json.get("id", Long.class);
return new JSONObject(obj).get("id", Long.class);
}
}
......@@ -7,7 +7,7 @@ import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* @author
* @author Jie
* @date 2019-01-07
*/
@Slf4j
......@@ -15,17 +15,10 @@ public class SpringContextHolder implements ApplicationContextAware, DisposableB
private static ApplicationContext applicationContext = null;
/**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
assertContextInjected();
return applicationContext;
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
assertContextInjected();
return (T) applicationContext.getBean(name);
......@@ -52,14 +45,14 @@ public class SpringContextHolder implements ApplicationContextAware, DisposableB
/**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
public static void clearHolder() {
private static void clearHolder() {
log.debug("清除SpringContextHolder中的ApplicationContext:"
+ applicationContext);
applicationContext = null;
}
@Override
public void destroy() throws Exception {
public void destroy(){
SpringContextHolder.clearHolder();
}
......
package me.zhengjie.utils;
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.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.Date;
......@@ -18,25 +20,6 @@ import java.util.Date;
public class StringUtils extends org.apache.commons.lang3.StringUtils {
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 {
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
*/
public static String toUnderScoreCase(String s) {
static String toUnderScoreCase(String s) {
if (s == null) {
return null;
}
......@@ -125,53 +108,45 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
/**
* 获取ip地址
* @param request
* @return
*/
public static String getIP(HttpServletRequest request) {
public static String getIp(HttpServletRequest request) {
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");
}
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");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
String[] ips = ip.split(",");
return "0:0:0:0:0:0:0:1".equals(ips[0])?"127.0.0.1":ips[0];
if (ip.contains(",")) {
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获取详细地址
* @param ip
* @return
*/
public static String getCityInfo(String ip) {
try {
String path = "ip2region/ip2region.db";
String name = "ip2region.db";
int algorithm = DbSearcher.BTREE_ALGORITHM;
DbConfig config = new DbConfig();
File file = FileUtil.inputStreamToFile(new ClassPathResource(path).getStream(), name);
DbSearcher searcher = new DbSearcher(config, file.getPath());
Method method = null;
switch (algorithm) {
case DbSearcher.BTREE_ALGORITHM:
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;
Method method;
method = searcher.getClass().getMethod("btreeSearch", String.class);
DataBlock dataBlock;
dataBlock = (DataBlock) method.invoke(searcher, ip);
String address = dataBlock.getRegion().replace("0|","");
if(address.charAt(address.length()-1) == '|'){
......@@ -184,6 +159,12 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
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;
import me.zhengjie.exception.BadRequestException;
import org.hibernate.exception.ConstraintViolationException;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* 异常工具
* 异常工具 2019-01-06
* @author Zheng Jie
* @date 2019-01-06
*/
public class ThrowableUtil {
/**
* 获取堆栈信息
* @param throwable
* @return
*/
public static String getStackTrace(Throwable throwable){
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
try {
try (PrintWriter pw = new PrintWriter(sw)) {
throwable.printStackTrace(pw);
return sw.toString();
} finally {
pw.close();
}
}
......@@ -34,9 +27,10 @@ public class ThrowableUtil {
while ((t != null) && !(t instanceof ConstraintViolationException)) {
t = t.getCause();
}
if (t instanceof ConstraintViolationException) {
if (t != null) {
throw new BadRequestException(msg);
}
assert false;
throw new BadRequestException("删除失败:" + t.getMessage());
}
}
package me.zhengjie.utils;
import cn.hutool.json.JSONArray;
import lombok.var;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
......@@ -26,7 +24,7 @@ public class TranslatorUtil {
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
......@@ -38,15 +36,12 @@ public class TranslatorUtil {
}
}
private static String parseResult(String inputJson) throws Exception {
JSONArray jsonArray = new JSONArray(inputJson);
JSONArray jsonArray2 = (JSONArray) jsonArray.get(0);
String result ="";
for(var i = 0; i < jsonArray2.size(); i ++){
result += ((JSONArray) jsonArray2.get(i)).get(0).toString();
private static String parseResult(String inputJson){
JSONArray jsonArray2 = (JSONArray) new JSONArray(inputJson).get(0);
StringBuilder result = new StringBuilder();
for (Object o : jsonArray2) {
result.append(((JSONArray) o).get(0).toString());
}
return result;
return result.toString();
}
}
package me.zhengjie.utils;
import cn.hutool.core.util.ObjectUtil;
import me.zhengjie.exception.BadRequestException;
import java.util.Optional;
/**
* 验证工具
......@@ -12,27 +12,22 @@ public class ValidationUtil{
/**
* 验证空
* @param optional
*/
public static void isNull(Optional optional, String entity,String parameter , Object value){
if(!optional.isPresent()){
String msg = entity
+ " 不存在 "
+"{ "+ parameter +":"+ value.toString() +" }";
public static void isNull(Object obj, String entity, String parameter , Object value){
if(ObjectUtil.isNull(obj)){
String msg = entity + " 不存在: "+ parameter +" is "+ value;
throw new BadRequestException(msg);
}
}
/**
* 验证是否为邮箱
* @param string
* @return
*/
public static boolean isEmail(String string) {
if (string == null){
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);
}
}
......@@ -11,12 +11,6 @@ import static org.junit.Assert.*;
public class StringUtilsTest {
@Test
public void testInString() {
assertTrue(inString("?", "?"));
assertFalse(inString("?", new String[]{}));
}
@Test
public void testToCamelCase() {
assertNull(toCamelCase(null));
......@@ -44,6 +38,6 @@ public class StringUtilsTest {
@Test
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 @@
<parent>
<artifactId>eladmin</artifactId>
<groupId>me.zhengjie</groupId>
<version>2.2</version>
<version>2.3</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......@@ -20,7 +20,7 @@
<dependency>
<groupId>me.zhengjie</groupId>
<artifactId>eladmin-common</artifactId>
<version>2.2</version>
<version>2.3</version>
</dependency>
<!--模板引擎-->
......
......@@ -16,26 +16,26 @@ public class GenConfig {
@Id
private Long id;
/** 包路径 **/
// 包路径
private String pack;
/** 模块名 **/
// 模块名
@Column(name = "module_name")
private String moduleName;
/** 前端文件路径 **/
// 前端文件路径
private String path;
/** 前端文件路径 **/
// 前端文件路径
@Column(name = "api_path")
private String apiPath;
/** 作者 **/
// 作者
private String author;
/** 表前缀 **/
// 表前缀
private String prefix;
/** 是否覆盖 **/
// 是否覆盖
private Boolean cover;
}
......@@ -14,27 +14,27 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor
public class ColumnInfo {
/** 数据库字段名称 **/
// 数据库字段名称
private Object columnName;
/** 允许空值 **/
// 允许空值
private Object isNullable;
/** 数据库字段类型 **/
// 数据库字段类型
private Object columnType;
/** 数据库字段注释 **/
// 数据库字段注释
private Object columnComment;
/** 数据库字段键类型 **/
// 数据库字段键类型
private Object columnKey;
/** 额外的参数 **/
// 额外的参数
private Object extra;
/** 查询 1:模糊 2:精确 **/
// 查询 1:模糊 2:精确
private String columnQuery;
/** 是否在列表显示 **/
// 是否在列表显示
private String columnShow;
}
......@@ -14,10 +14,10 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor
public class TableInfo {
/** 表名称 **/
// 表名称
private Object tableName;
/** 创建日期 **/
// 创建日期
private Object createTime;
// 数据库引擎
......
package me.zhengjie.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.domain.GenConfig;
import me.zhengjie.service.GenConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
......@@ -13,23 +14,25 @@ import org.springframework.web.bind.annotation.*;
* @date 2019-01-14
*/
@RestController
@RequestMapping("api")
@RequestMapping("/api/genConfig")
@Api(tags = "系统:代码生成器配置管理")
public class GenConfigController {
@Autowired
private GenConfigService genConfigService;
private final GenConfigService genConfigService;
/**
* 查询生成器配置
* @return
*/
@GetMapping(value = "/genConfig")
public GenConfigController(GenConfigService genConfigService) {
this.genConfigService = genConfigService;
}
@ApiOperation("查询")
@GetMapping
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){
return new ResponseEntity(genConfigService.update(genConfig),HttpStatus.OK);
return new ResponseEntity<>(genConfigService.update(genConfig),HttpStatus.OK);
}
}
package me.zhengjie.rest;
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.exception.BadRequestException;
import me.zhengjie.service.GenConfigService;
import me.zhengjie.service.GeneratorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
......@@ -17,49 +18,39 @@ import java.util.List;
* @date 2019-01-02
*/
@RestController
@RequestMapping("api")
@RequestMapping("/api/generator")
@Api(tags = "系统:代码生成管理")
public class GeneratorController {
@Autowired
private GeneratorService generatorService;
private final GeneratorService generatorService;
@Autowired
private GenConfigService genConfigService;
private final GenConfigService genConfigService;
@Value("${generator.enabled}")
private Boolean generatorEnabled;
/**
* 查询数据库元数据
* @param name
* @param page
* @param size
* @return
*/
@GetMapping(value = "/generator/tables")
public GeneratorController(GeneratorService generatorService, GenConfigService genConfigService) {
this.generatorService = generatorService;
this.genConfigService = genConfigService;
}
@ApiOperation("查询数据库元数据")
@GetMapping(value = "/tables")
public ResponseEntity getTables(@RequestParam(defaultValue = "") String name,
@RequestParam(defaultValue = "0")Integer page,
@RequestParam(defaultValue = "10")Integer size){
@RequestParam(defaultValue = "0")Integer page,
@RequestParam(defaultValue = "10")Integer 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);
}
/**
* 查询表内元数据
* @param tableName
* @return
*/
@GetMapping(value = "/generator/columns")
@ApiOperation("查询表内元数据")
@GetMapping(value = "/columns")
public ResponseEntity getTables(@RequestParam String tableName){
return new ResponseEntity(generatorService.getColumns(tableName), HttpStatus.OK);
return new ResponseEntity<>(generatorService.getColumns(tableName), HttpStatus.OK);
}
/**
* 生成代码
* @param columnInfos
* @return
*/
@PostMapping(value = "/generator")
@ApiOperation("生成代码")
@PostMapping
public ResponseEntity generator(@RequestBody List<ColumnInfo> columnInfos, @RequestParam String tableName){
if(!generatorEnabled){
throw new BadRequestException("此环境不允许生成代码!");
......
package me.zhengjie.service;
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
* @date 2019-01-14
*/
@CacheConfig(cacheNames = "genConfig")
public interface GenConfigService {
/**
* find
* @return
*/
@Cacheable(key = "'1'")
GenConfig find();
/**
* update
* @param genConfig
* @return
*/
@CacheEvict(allEntries = true)
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