| | |
| | | |
| | | <modules> |
| | | <module>zy-asrs-common</module> |
| | | <module>zy-asrs-framework</module> |
| | | <module>zy-asrs-wcs</module> |
| | | <module>zy-asrs-wms</module> |
| | | </modules> |
New file |
| | |
| | | HELP.md |
| | | target/ |
| | | !.mvn/wrapper/maven-wrapper.jar |
| | | !**/src/main/**/target/ |
| | | !**/src/test/**/target/ |
| | | |
| | | ### STS ### |
| | | .apt_generated |
| | | .classpath |
| | | .factorypath |
| | | .project |
| | | .settings |
| | | .springBeans |
| | | .sts4-cache |
| | | |
| | | ### IntelliJ IDEA ### |
| | | .idea |
| | | *.iws |
| | | *.iml |
| | | *.ipr |
| | | |
| | | ### NetBeans ### |
| | | /nbproject/private/ |
| | | /nbbuild/ |
| | | /dist/ |
| | | /nbdist/ |
| | | /.nb-gradle/ |
| | | build/ |
| | | !**/src/main/**/build/ |
| | | !**/src/test/**/build/ |
| | | |
| | | ### VS Code ### |
| | | .vscode/ |
New file |
| | |
| | | <?xml version="1.0" encoding="UTF-8"?> |
| | | <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
| | | xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> |
| | | <modelVersion>4.0.0</modelVersion> |
| | | |
| | | <artifactId>asrs-framework</artifactId> |
| | | <version>1.0.0</version> |
| | | |
| | | <name>framework</name> |
| | | |
| | | <parent> |
| | | <groupId>com.zy</groupId> |
| | | <artifactId>asrs</artifactId> |
| | | <version>1.0.0</version> |
| | | </parent> |
| | | |
| | | <properties> |
| | | <jdk.version>1.8</jdk.version> |
| | | <spring-framework.version>5.3.9</spring-framework.version> |
| | | </properties> |
| | | |
| | | <dependencies> |
| | | <dependency> |
| | | <groupId>org.springframework</groupId> |
| | | <artifactId>spring-context</artifactId> |
| | | <version>${spring-framework.version}</version> |
| | | </dependency> |
| | | <dependency> |
| | | <groupId>mysql</groupId> |
| | | <artifactId>mysql-connector-java</artifactId> |
| | | <version>5.1.46</version> |
| | | </dependency> |
| | | <dependency> |
| | | <groupId>com.microsoft.sqlserver</groupId> |
| | | <artifactId>mssql-jdbc</artifactId> |
| | | <version>8.2.2.jre8</version> |
| | | </dependency> |
| | | </dependencies> |
| | | |
| | | <build> |
| | | <plugins> |
| | | <plugin> |
| | | <groupId>org.apache.maven.plugins</groupId> |
| | | <artifactId>maven-resources-plugin</artifactId> |
| | | <configuration> |
| | | <encoding>UTF-8</encoding> |
| | | </configuration> |
| | | </plugin> |
| | | </plugins> |
| | | </build> |
| | | |
| | | </project> |
New file |
| | |
| | | package com.zy.asrs.framework.annotations; |
| | | |
| | | import java.lang.annotation.ElementType; |
| | | import java.lang.annotation.Retention; |
| | | import java.lang.annotation.RetentionPolicy; |
| | | import java.lang.annotation.Target; |
| | | |
| | | /** |
| | | * 应用端认证标签 |
| | | */ |
| | | @Target({ElementType.TYPE,ElementType.METHOD}) |
| | | @Retention(RetentionPolicy.RUNTIME) |
| | | public @interface AppAuth { |
| | | |
| | | Auth value() default Auth.CHECK; |
| | | |
| | | // 备注 |
| | | String memo() default ""; |
| | | |
| | | public enum Auth{ |
| | | //权限检测 |
| | | CHECK, |
| | | //不检测权限 |
| | | NONE |
| | | } |
| | | |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.annotations; |
| | | |
| | | import java.lang.annotation.ElementType; |
| | | import java.lang.annotation.Retention; |
| | | import java.lang.annotation.RetentionPolicy; |
| | | import java.lang.annotation.Target; |
| | | |
| | | @Target({ElementType.TYPE,ElementType.FIELD}) |
| | | @Retention(RetentionPolicy.RUNTIME) |
| | | public @interface CoolTranslate { |
| | | |
| | | // 意思 |
| | | String value() default ""; |
| | | |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.annotations; |
| | | |
| | | import java.lang.annotation.ElementType; |
| | | import java.lang.annotation.Retention; |
| | | import java.lang.annotation.RetentionPolicy; |
| | | import java.lang.annotation.Target; |
| | | |
| | | /** |
| | | * 管理端认证标签 |
| | | */ |
| | | @Target({ElementType.TYPE,ElementType.METHOD}) |
| | | @Retention(RetentionPolicy.RUNTIME) |
| | | public @interface ManagerAuth { |
| | | |
| | | Auth value() default Auth.CHECK; |
| | | |
| | | // 备注 |
| | | String memo() default ""; |
| | | |
| | | public enum Auth{ |
| | | //权限检测 |
| | | CHECK, |
| | | //不检测权限 |
| | | NONE |
| | | } |
| | | |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.common; |
| | | |
| | | import javax.crypto.Cipher; |
| | | import javax.crypto.spec.SecretKeySpec; |
| | | |
| | | |
| | | /** |
| | | * aes128-base64 |
| | | * @author Vincent |
| | | */ |
| | | public class AesUtils { |
| | | |
| | | private final static String DEFAULT_CHARSET = "utf-8"; |
| | | private final static int DEFAULT_KEY_LENGTH = 16; |
| | | |
| | | /** |
| | | * aes128 - base64 加密 |
| | | * @param data 需要加密的明文 |
| | | * @param key 盐 |
| | | * @return 密文 |
| | | */ |
| | | public static String encrypt(String data, String key) { |
| | | try { |
| | | if (null == key || "".equals(key) || key.length() != DEFAULT_KEY_LENGTH) { |
| | | return null; |
| | | } |
| | | byte[] raw = key.getBytes(DEFAULT_CHARSET); |
| | | SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); |
| | | Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式" |
| | | cipher.init(Cipher.ENCRYPT_MODE, skeySpec); |
| | | byte[] encrypted = cipher.doFinal(data.getBytes(DEFAULT_CHARSET)); |
| | | return RadixTools.bytesToHexStr(encrypted); |
| | | } catch (Exception ex) { |
| | | return null; |
| | | } |
| | | |
| | | } |
| | | |
| | | /** |
| | | * aes128 - base64 解密 |
| | | * @param data 需要解密的密文 |
| | | * @param key 盐 |
| | | * @return 明文 |
| | | */ |
| | | public static String decrypt(String data, String key) { |
| | | try { |
| | | if (null == key || "".equals(key) || key.length() != DEFAULT_KEY_LENGTH) { |
| | | return null; |
| | | } |
| | | byte[] raw = key.getBytes(DEFAULT_CHARSET); |
| | | SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); |
| | | Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); |
| | | cipher.init(Cipher.DECRYPT_MODE, skeySpec); |
| | | byte[] original = cipher.doFinal(RadixTools.hexStringToBytes(data)); |
| | | return new String(original,DEFAULT_CHARSET); |
| | | } catch (Exception ex) { |
| | | return null; |
| | | } |
| | | } |
| | | |
| | | public static void main(String[] args) { |
| | | //test |
| | | String key = "123456"; |
| | | // String jsonData = "json={\"status\":200,\"msg\":\"success\",\"data\":\"dsadsa\"}×tamp=" + String.valueOf(System.currentTimeMillis()+5000000L); |
| | | //// String jsonData = "status=200&msg=xltys1995==sadsadsad×tamp=" + String.valueOf(System.currentTimeMillis()+5000000L); |
| | | // System.out.println(System.currentTimeMillis() + 5000000L); |
| | | // String encrypt = encrypt(key, jsonData); |
| | | // System.out.println(encrypt); |
| | | // String key = "QeCB1d74ab24482b"; |
| | | // String s = decrypt("bd064484343cde2d325693c0611c157d04294ae2cea03854d10a2f0aa01377cfc69cf6c700ae665c8f4c539d030bb2af" |
| | | // , key); |
| | | // System.out.printf(s); |
| | | |
| | | |
| | | String data = "15988786205×tamp=" + (System.currentTimeMillis() + 5000000L); |
| | | // String jsonData = "status=200&msg=xltys1995==sadsadsad×tamp=" + String.valueOf(System.currentTimeMillis()+5000000L); |
| | | System.out.println(System.currentTimeMillis() + 5000000L); |
| | | String encrypt = encrypt(data,key); |
| | | System.out.println(encrypt); |
| | | } |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.common; |
| | | |
| | | import java.math.BigDecimal; |
| | | import java.math.RoundingMode; |
| | | |
| | | /** |
| | | * 四则运算 |
| | | * Created by vincent on 2019-04-15 |
| | | */ |
| | | public class Arith { |
| | | |
| | | /** |
| | | * 加法 |
| | | * @param dot 保留小数点 |
| | | * @param numbers 数字类型 |
| | | */ |
| | | public static double add(int dot, Number... numbers) { |
| | | return getAirth(dot, ArithType.ADD.getValue(), numbers); |
| | | } |
| | | |
| | | /** |
| | | * 减法 |
| | | * @param dot 保留小数点 |
| | | * @param numbers 第一个是被减数 |
| | | */ |
| | | public static double subtract(int dot, Number... numbers) { |
| | | return getAirth(dot, ArithType.SUBTRACT.getValue(), numbers); |
| | | } |
| | | |
| | | /** |
| | | * 乘法 |
| | | * @param dot 保留小数点 |
| | | * @param numbers 乘法的因子 |
| | | */ |
| | | public static double multiplys(int dot, Number... numbers) { |
| | | return getAirth(dot, ArithType.MULTIPLY.getValue(), numbers); |
| | | } |
| | | |
| | | /** |
| | | * 除法 |
| | | * @param dot 保留小数点 |
| | | * @param numbers 除数,第一个是除数 |
| | | */ |
| | | public static double divides(int dot, Number... numbers) { |
| | | return getAirth(dot, ArithType.DIVIDE.getValue(), numbers); |
| | | } |
| | | |
| | | /** |
| | | * 获取百分比 |
| | | * @param numbers 除数,第一个是除数 |
| | | * @return 百分数 * 100 |
| | | */ |
| | | public static int percentage(Number... numbers){ |
| | | return (int) (divides(2,numbers) * 100); |
| | | } |
| | | |
| | | /** |
| | | * 余数 |
| | | * @param numbers |
| | | * @return |
| | | */ |
| | | public static double remainder(Number... numbers){ |
| | | return new BigDecimal(numbers[0].toString()).remainder(new BigDecimal(String.valueOf(numbers[1]))).doubleValue(); |
| | | } |
| | | |
| | | /** |
| | | * 综合的运算 |
| | | * @param dot 保留精度 |
| | | * @param arithType 运算的类型 |
| | | * @param numbers 需要运算的数字 |
| | | */ |
| | | private static double getAirth(int dot, int arithType, Number... numbers) { |
| | | if (numbers == null || numbers.length == 0) { |
| | | return 0.0; |
| | | } |
| | | BigDecimal bigDecimal = new BigDecimal(numbers[0].toString()); |
| | | for (int i = 1; i < numbers.length; i++) { |
| | | switch (arithType) { |
| | | case 0: |
| | | bigDecimal = bigDecimal.add(new BigDecimal(String.valueOf(numbers[i]))); |
| | | |
| | | break; |
| | | case 1: |
| | | bigDecimal = bigDecimal.divide(new BigDecimal(String.valueOf(numbers[i])), dot, RoundingMode.HALF_UP); |
| | | break; |
| | | case 2: |
| | | bigDecimal = bigDecimal.subtract(new BigDecimal(String.valueOf(numbers[i]))); |
| | | break; |
| | | case 3: |
| | | bigDecimal = bigDecimal.multiply(new BigDecimal(String.valueOf(numbers[i]))); |
| | | break; |
| | | default: |
| | | return 0.00; |
| | | } |
| | | } |
| | | return bigDecimal.setScale(dot, RoundingMode.HALF_UP).doubleValue(); |
| | | } |
| | | |
| | | |
| | | /** |
| | | * 运算的类型 |
| | | */ |
| | | private enum ArithType { |
| | | ADD("add", 0), |
| | | DIVIDE("divide", 1), |
| | | SUBTRACT("subtract", 2), |
| | | MULTIPLY("multiply", 3); |
| | | @SuppressWarnings("unused") |
| | | private String key; |
| | | private int value; |
| | | ArithType(String key, int value) { |
| | | this.key = key; |
| | | this.value = value; |
| | | } |
| | | public int getValue() { |
| | | return value; |
| | | } |
| | | } |
| | | |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.common; |
| | | |
| | | public interface BaseRes { |
| | | |
| | | String OK = "200-操作成功"; |
| | | String EMPTY = "201-暂无数据"; |
| | | String LIMIT = "202-无权限"; |
| | | String PARAM = "401-参数为空"; |
| | | String DENIED = "403-请重新登录"; |
| | | String REPEAT = "407-已存在"; |
| | | String NO_ACTIVATION = "409-请先激活系统"; |
| | | String ERROR = "500-服务器错误"; |
| | | |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.common; |
| | | |
| | | import com.zy.asrs.framework.exception.ApplicationException; |
| | | |
| | | import java.util.Map; |
| | | import java.util.concurrent.ConcurrentHashMap; |
| | | import java.util.function.Supplier; |
| | | |
| | | /** |
| | | * 缓存 |
| | | * |
| | | */ |
| | | public class Cache { |
| | | |
| | | private Map<String,Object> caches=new ConcurrentHashMap<>(); |
| | | |
| | | @SuppressWarnings("unchecked") |
| | | public <T>T get(Class<T> prototype) { |
| | | return (T) get(prototype.getName()); |
| | | } |
| | | |
| | | public Object get(String key) { |
| | | return get(key,true); |
| | | } |
| | | |
| | | @SuppressWarnings("unchecked") |
| | | public <T>T get(String key,Supplier<T> func){ |
| | | if(!hasKey(key)) { |
| | | put(key,func.get()); |
| | | } |
| | | return (T)get(key); |
| | | } |
| | | |
| | | public Object get(String key,boolean exist) { |
| | | if(exist) { |
| | | if(!hasKey(key)) { |
| | | throw new ApplicationException(this+"-找不到缓存对象:"+key); |
| | | } |
| | | } |
| | | return caches.get(key); |
| | | } |
| | | |
| | | public Cache put(Object value) { |
| | | String key=value.getClass().getName(); |
| | | put(key,value); |
| | | return this; |
| | | } |
| | | |
| | | public Cache put(String key,Object value) { |
| | | put(key, value,true); |
| | | return this; |
| | | } |
| | | |
| | | public Cache put(String key,Object value,boolean exist) { |
| | | if(exist) { |
| | | if(hasKey(key)) { |
| | | throw new ApplicationException(this+"-缓存"+key+"已存在"); |
| | | } |
| | | } |
| | | caches.put(key, value); |
| | | return this; |
| | | } |
| | | |
| | | public boolean hasKey(Class<?> prototype) { |
| | | return hasKey(prototype.getName()); |
| | | } |
| | | |
| | | public boolean hasKey(String key) { |
| | | return caches.containsKey(key); |
| | | } |
| | | |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.common; |
| | | |
| | | import com.zy.asrs.framework.annotations.CoolTranslate; |
| | | |
| | | import java.lang.reflect.*; |
| | | import java.nio.charset.StandardCharsets; |
| | | import java.security.MessageDigest; |
| | | import java.util.HashMap; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * Created by vincent on 2019-06-09 |
| | | */ |
| | | public class Cools { |
| | | |
| | | public static boolean isEmpty(Object... objects) { |
| | | for (Object obj : objects){ |
| | | if (isEmpty(obj)){ |
| | | return true; |
| | | } |
| | | } |
| | | return false; |
| | | } |
| | | |
| | | @SuppressWarnings("rawtypes") |
| | | public static boolean isEmpty(Object o) { |
| | | if (o == null) { |
| | | return true; |
| | | } |
| | | if (o instanceof String) { |
| | | if (o.toString().trim().equals("")) { |
| | | return true; |
| | | } |
| | | } else if (o instanceof List) { |
| | | if (((List) o).size() == 0) { |
| | | return true; |
| | | } |
| | | } else if (o instanceof Map) { |
| | | if (((Map) o).size() == 0) { |
| | | return true; |
| | | } |
| | | } else if (o instanceof Set) { |
| | | if (((Set) o).size() == 0) { |
| | | return true; |
| | | } |
| | | } else if (o instanceof Object[]) { |
| | | if (((Object[]) o).length == 0) { |
| | | return true; |
| | | } |
| | | } else if (o instanceof int[]) { |
| | | if (((int[]) o).length == 0) { |
| | | return true; |
| | | } |
| | | } else if (o instanceof long[]) { |
| | | if (((long[]) o).length == 0) { |
| | | return true; |
| | | } |
| | | } |
| | | return false; |
| | | } |
| | | |
| | | public static int sqlLimitIndex(Integer pageIndex, Integer pageSize){ |
| | | return (pageIndex - 1) * pageSize; |
| | | } |
| | | |
| | | public static String enToken(String username, String password){ |
| | | return AesUtils.encrypt(username, zerofill(password, 16)); |
| | | } |
| | | |
| | | public static String deTokn(String token, String password){ |
| | | return AesUtils.decrypt(token, zerofill(password, 16)); |
| | | } |
| | | |
| | | public static String zerofill(String msg, Integer count){ |
| | | if (msg.length() == count){ |
| | | return msg; |
| | | } else if (msg.length() > count){ |
| | | return msg.substring(0, 16); |
| | | } else { |
| | | StringBuilder msgBuilder = new StringBuilder(msg); |
| | | for (int i = 0; i<count-msg.length(); i++){ |
| | | msgBuilder.append("0"); |
| | | } |
| | | return msgBuilder.toString(); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 截取字符串(默认end=true) |
| | | * @param str 被截字符串 |
| | | * @param end true:最后一个字符 / false:第一个字符 |
| | | */ |
| | | public static String deleteChar(String str, boolean end){ |
| | | if (isEmpty(str)){ |
| | | return ""; |
| | | } |
| | | if (end){ |
| | | return str.substring(0, str.length()-1); |
| | | } else { |
| | | return str.substring(1); |
| | | } |
| | | } |
| | | |
| | | public static String deleteChar(String str){ |
| | | return deleteChar(str, true); |
| | | } |
| | | |
| | | |
| | | /** |
| | | * map 转 对象 |
| | | */ |
| | | public static <T> T conver(Map<? extends String, ?> map, Class<T> cls){ |
| | | T instance = null; |
| | | try { |
| | | Constructor<T> constructor = cls.getDeclaredConstructor(); |
| | | boolean constructorAccessible = constructor.isAccessible(); |
| | | constructor.setAccessible(true); |
| | | instance = constructor.newInstance(); |
| | | constructor.setAccessible(constructorAccessible); |
| | | } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) { |
| | | e.printStackTrace(); |
| | | } |
| | | Class<?> prototype = cls; |
| | | do { |
| | | for (Field field : prototype.getDeclaredFields()){ |
| | | if (Modifier.isFinal(field.getModifiers()) |
| | | || Modifier.isStatic(field.getModifiers()) |
| | | || Modifier.isTransient(field.getModifiers())){ |
| | | continue; |
| | | } |
| | | String fieldName = field.getName(); |
| | | Object val = null; |
| | | if (map.containsKey(fieldName)){ |
| | | val = map.get(fieldName); |
| | | } |
| | | if (val != null){ |
| | | boolean fieldAccessible = field.isAccessible(); |
| | | field.setAccessible(true); |
| | | Class<?> type = field.getType(); |
| | | try { |
| | | Constructor<?> constructor = type.getDeclaredConstructor(String.class); |
| | | boolean constructorAccessible = constructor.isAccessible(); |
| | | constructor.setAccessible(true); |
| | | field.set(instance, constructor.newInstance(String.valueOf(val))); |
| | | constructor.setAccessible(constructorAccessible); |
| | | } catch (IllegalAccessException |
| | | | InstantiationException |
| | | | InvocationTargetException |
| | | | NoSuchMethodException e) { |
| | | System.err.println("convert error ===> Class["+prototype+"],Field:["+fieldName+"],Type:["+type+"],Value:["+val+"]"); |
| | | } |
| | | field.setAccessible(fieldAccessible); |
| | | } |
| | | } |
| | | prototype = prototype.getSuperclass(); |
| | | } while (!Object.class.equals(prototype)); |
| | | return instance; |
| | | } |
| | | |
| | | /** |
| | | * 对象 转 map |
| | | */ |
| | | public static Map<String, Object> conver(Object obj){ |
| | | Class<?> cls = obj.getClass(); |
| | | Field[] fields = getAllFields(cls); |
| | | Map<String, Object> map = new HashMap<>(); |
| | | for (Field field : fields) { |
| | | if (Modifier.isFinal(field.getModifiers()) |
| | | || Modifier.isStatic(field.getModifiers()) |
| | | || Modifier.isTransient(field.getModifiers())){ |
| | | continue; |
| | | } |
| | | String key = field.getName(); |
| | | boolean flag = field.isAccessible(); |
| | | field.setAccessible(true); |
| | | Object val = null; |
| | | try { |
| | | val = field.get(obj); |
| | | } catch (IllegalAccessException e) { |
| | | e.printStackTrace(); |
| | | } |
| | | field.setAccessible(flag); |
| | | if (val != null){ |
| | | map.put(key, val); |
| | | } |
| | | } |
| | | return map; |
| | | } |
| | | |
| | | /** |
| | | * 获取指定Class(及其SuperClass)的成员变量 |
| | | */ |
| | | public static Field[] getAllFields(Class<?> cls){ |
| | | return getAllFields(cls, null); |
| | | } |
| | | |
| | | /** |
| | | * 递归合并基类Field |
| | | */ |
| | | private static Field[] getAllFields(Class<?> cls, Field[] params){ |
| | | Field[] fields = (params == null) ? cls.getDeclaredFields() : params; |
| | | Class<?> superCls = cls.getSuperclass(); |
| | | if (superCls == null || superCls == Object.class){ |
| | | return fields; |
| | | } |
| | | Field[] superClsFields = superCls.getDeclaredFields(); |
| | | fields = addAll(fields, superClsFields); |
| | | return getAllFields(superCls, fields); |
| | | } |
| | | |
| | | /** |
| | | * 根据fieldName获取Field对象 |
| | | */ |
| | | public static Field getField(Class<?> cls, String fieldName) { |
| | | Field[] allFields = getAllFields(cls); |
| | | for (Field field : allFields) { |
| | | if (field.getName().equals(fieldName)) { |
| | | return field; |
| | | } |
| | | } |
| | | return null; |
| | | } |
| | | |
| | | /** |
| | | * 获取对象中某个Field的值 |
| | | */ |
| | | public static Object getFieldValue(Object obj, Field field) { |
| | | if (null == field) { |
| | | return null; |
| | | } else { |
| | | if (obj instanceof Class) { |
| | | obj = null; |
| | | } |
| | | if (!field.isAccessible()) { |
| | | field.setAccessible(true); |
| | | } |
| | | try { |
| | | return field.get(obj); |
| | | } catch (IllegalAccessException e) { |
| | | throw new RuntimeException(e); |
| | | } |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 数组叠加 |
| | | */ |
| | | @SuppressWarnings("unchecked") |
| | | public static <T> T[] addAll(T[] array1, T... array2) { |
| | | if (array1 == null) { |
| | | return clone(array2); |
| | | } else if (array2 == null) { |
| | | return clone(array1); |
| | | } else { |
| | | Class<?> cls = array1.getClass().getComponentType(); |
| | | T[] joinedArray = (T[]) Array.newInstance(cls, array1.length + array2.length); |
| | | System.arraycopy(array1, 0, joinedArray, 0, array1.length); |
| | | |
| | | try { |
| | | System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); |
| | | return joinedArray; |
| | | } catch (ArrayStoreException e) { |
| | | Class<?> type2 = array2.getClass().getComponentType(); |
| | | if (!cls.isAssignableFrom(type2)) { |
| | | throw new RuntimeException("Cannot store " + type2.getName() + " in an array of " + cls.getName(), e); |
| | | } else { |
| | | throw e; |
| | | } |
| | | } |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 克隆 |
| | | */ |
| | | private static <T> T[] clone(T[] array) { |
| | | return array == null ? null : array.clone(); |
| | | } |
| | | |
| | | /** |
| | | * map操作 |
| | | */ |
| | | public static CoolMap add(String key,Object value){ |
| | | CoolMap map = new CoolMap(); |
| | | map.put(key, value); |
| | | return map; |
| | | } |
| | | |
| | | public static class CoolMap extends HashMap<String, Object>{ |
| | | |
| | | public CoolMap add(String key,Object value){ |
| | | this.put(key, value); |
| | | return this; |
| | | } |
| | | |
| | | public CoolMap $(String key,Object value){ |
| | | this.put(key, value); |
| | | return this; |
| | | } |
| | | |
| | | } |
| | | |
| | | public static String md5(String string){ |
| | | try{ |
| | | MessageDigest md5 = MessageDigest.getInstance("MD5"); |
| | | byte[] bytes = md5.digest(string.getBytes(StandardCharsets.UTF_8)); |
| | | char[] chars = new char[bytes.length * 2]; |
| | | for (int i = 0; i < bytes.length; i++) { |
| | | int b = bytes[i]; |
| | | chars[i * 2] = hexDigits[(b & 0xF0) >> 4]; |
| | | chars[i * 2 + 1] = hexDigits[b & 0x0F]; |
| | | } |
| | | return new String(chars).toLowerCase(); |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | throw new RuntimeException("md5加密失败,str=".concat(string)); |
| | | } |
| | | } |
| | | |
| | | private static char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; |
| | | |
| | | public static Map<String, Object> translate(Object obj){ |
| | | Class<?> cls = obj.getClass(); |
| | | Field[] fields = getAllFields(cls); |
| | | Map<String, Object> map = new HashMap<>(); |
| | | for (Field field : fields) { |
| | | String key = field.getName(); |
| | | if (field.isAnnotationPresent(CoolTranslate.class)){ |
| | | CoolTranslate annotation = field.getAnnotation(CoolTranslate.class); |
| | | if (!isEmpty(annotation.value())) { |
| | | key = annotation.value(); |
| | | } |
| | | } |
| | | boolean flag = field.isAccessible(); |
| | | field.setAccessible(true); |
| | | Object val = null; |
| | | try { |
| | | val = field.get(obj); |
| | | } catch (IllegalAccessException e) { |
| | | e.printStackTrace(); |
| | | } |
| | | field.setAccessible(flag); |
| | | if (val != null){ |
| | | map.put(key, val); |
| | | } |
| | | } |
| | | return map; |
| | | } |
| | | |
| | | public static boolean eq(String str, String str0) { |
| | | if (Cools.isEmpty(str) && Cools.isEmpty(str0)) { |
| | | return true; |
| | | } |
| | | if (Cools.isEmpty(str) && !Cools.isEmpty(str0)) { |
| | | return false; |
| | | } |
| | | if (Cools.isEmpty(str0) && !Cools.isEmpty(str)) { |
| | | return false; |
| | | } |
| | | if (str.equals(str0)) { |
| | | return true; |
| | | } |
| | | return false; |
| | | } |
| | | |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.common; |
| | | |
| | | import java.text.ParseException; |
| | | import java.text.SimpleDateFormat; |
| | | import java.util.Calendar; |
| | | import java.util.Date; |
| | | import java.util.Objects; |
| | | import java.util.concurrent.TimeUnit; |
| | | |
| | | /** |
| | | * 时间工具类 |
| | | * Created by vincent on 2019-04-15 |
| | | */ |
| | | public class DateUtils { |
| | | |
| | | public final static String yyyyMMdd_C="yyyy年MM月dd日"; |
| | | public final static String yyyyMM_F="yyyy-MM"; |
| | | public final static String yyyyMMdd_F="yyyy-MM-dd"; |
| | | public final static String yyyyMMddHHmmss_F="yyyy-MM-dd HH:mm:ss"; |
| | | public final static String yyyyMMddHHmmsssss_F="yyyy-MM-dd HH:mm:ss,SSS"; |
| | | public final static String yyyy="yyyy"; |
| | | public final static String yyyyMM="yyyyMM"; |
| | | public final static String yyyyMMdd="yyyyMMdd"; |
| | | public final static String yyyyMMddHH="yyyyMMddHH"; |
| | | public final static String yyyyMMddHHmmss="yyyyMMddHHmmss"; |
| | | public final static String YYMMDDHHMMSS="YYMMDDHHMMSS"; |
| | | public final static String yyyyMMddHHmmsssss="yyyyMMddHHmmssSSS"; |
| | | |
| | | /** |
| | | * date ==>> string |
| | | */ |
| | | public static String convert(Date date, String pattern){ |
| | | return new SimpleDateFormat(pattern).format(date); |
| | | } |
| | | |
| | | public static String convert(Date date){ |
| | | return convert(date, yyyyMMddHHmmss_F); |
| | | } |
| | | |
| | | /** |
| | | * string ==>> date |
| | | */ |
| | | public static Date convert(String str, String pattern){ |
| | | if (str.length() < pattern.length()){ |
| | | throw new RuntimeException("时间解析失败 ==>> "+str); |
| | | } |
| | | if (str.length() > pattern.length()){ |
| | | str = str.substring(0, pattern.length()); |
| | | } |
| | | SimpleDateFormat format = new SimpleDateFormat(pattern); |
| | | Date date; |
| | | try { |
| | | date = format.parse(str); |
| | | } catch (ParseException e) { |
| | | throw new RuntimeException("时间解析失败 ==>> "+str); |
| | | } |
| | | return date; |
| | | } |
| | | |
| | | public static Date convert(String str){ |
| | | return convert(str, yyyyMMddHHmmss_F); |
| | | } |
| | | |
| | | /** |
| | | * 两个date之间相差的天数,不满一天算一天 |
| | | */ |
| | | public static int diff(Date date1, Date date2){ |
| | | return getDaysByTimestamp(Math.abs(date2.getTime() - date1.getTime())); |
| | | } |
| | | |
| | | public static long diffToMinute(Date date1, Date date2){ |
| | | return Math.abs(date2.getTime() - date1.getTime())/1000/60; |
| | | } |
| | | |
| | | public static long diffToSeconds(Date date1, Date date2){ |
| | | return Math.abs(date2.getTime() - date1.getTime())/1000; |
| | | } |
| | | |
| | | private static int getDaysByTimestamp(long timestamp){ |
| | | double daysPoint = Arith.divides(2, timestamp, (1000 * 3600 * 24)); |
| | | int daysPoint1 = (int) daysPoint; |
| | | double daysPoint2 = (double) daysPoint1; |
| | | if (daysPoint > daysPoint2){ |
| | | return daysPoint1 + 1; |
| | | } |
| | | return daysPoint1; |
| | | } |
| | | |
| | | /** |
| | | * 入参date距离现在的秒数 |
| | | */ |
| | | public static int diffToNow(Date date){ |
| | | long diff = new Date().getTime() - date.getTime(); |
| | | return (int) (Math.abs(diff) / 1000); |
| | | } |
| | | |
| | | /** |
| | | * 当前时间戳(单位:秒) |
| | | */ |
| | | public static String createTimeStamp() { |
| | | return Long.toString(System.currentTimeMillis() / 1000); |
| | | } |
| | | |
| | | /** |
| | | * 时间计算函数 |
| | | * @param date 被计算时间实例 |
| | | * @param val 计算值 |
| | | * @param timeUnit 计算值单位 |
| | | * @param subtraction 减法布尔 true:当前函数为减法计算,false:反之 |
| | | * @return 计算结果 Date |
| | | */ |
| | | public static Date calculate(Date date, Long val, TimeUnit timeUnit, boolean subtraction){ |
| | | if (Objects.isNull(date) || Objects.isNull(val) || Objects.isNull(timeUnit)){ |
| | | return null; |
| | | } |
| | | return new Date(subtraction?date.getTime()-timeUnit.toMillis(val):date.getTime()+timeUnit.toMillis(val)); |
| | | } |
| | | |
| | | public static Date calculate(Date date, Long val, TimeUnit timeUnit){ |
| | | return calculate(date, val, timeUnit, false); |
| | | } |
| | | |
| | | /** |
| | | * 时间对象DateEntity |
| | | */ |
| | | public static DateEntity getDateEntity(Date date){ |
| | | Calendar cal = Calendar.getInstance(); |
| | | cal.setTime(date); |
| | | DateEntity dateEntity = new DateEntity(); |
| | | dateEntity.setYear(cal.get(Calendar.YEAR)); |
| | | dateEntity.setMonth(cal.get(Calendar.MONTH)); |
| | | dateEntity.setDay(cal.get(Calendar.DATE)); |
| | | dateEntity.setHour(cal.get(Calendar.HOUR_OF_DAY)); |
| | | dateEntity.setMinute(cal.get(Calendar.MINUTE)); |
| | | dateEntity.setSecond(cal.get(Calendar.SECOND)); |
| | | return dateEntity; |
| | | } |
| | | |
| | | static class DateEntity { |
| | | int year; |
| | | int month; |
| | | int day; |
| | | int hour; |
| | | int minute; |
| | | int second; |
| | | |
| | | public int getYear() { |
| | | return year; |
| | | } |
| | | |
| | | public void setYear(final int year) { |
| | | this.year = year; |
| | | } |
| | | |
| | | public int getMonth() { |
| | | return month; |
| | | } |
| | | |
| | | public void setMonth(final int month) { |
| | | this.month = month + 1; |
| | | } |
| | | |
| | | public int getDay() { |
| | | return day; |
| | | } |
| | | |
| | | public void setDay(final int day) { |
| | | this.day = day; |
| | | } |
| | | |
| | | public int getHour() { |
| | | return hour; |
| | | } |
| | | |
| | | public void setHour(final int hour) { |
| | | this.hour = hour; |
| | | } |
| | | |
| | | public int getMinute() { |
| | | return minute; |
| | | } |
| | | |
| | | public void setMinute(final int minute) { |
| | | this.minute = minute; |
| | | } |
| | | |
| | | public int getSecond() { |
| | | return second; |
| | | } |
| | | |
| | | public void setSecond(final int second) { |
| | | this.second = second; |
| | | } |
| | | } |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.common; |
| | | |
| | | |
| | | import java.io.Serializable; |
| | | |
| | | /** |
| | | * common result |
| | | * Created by vincent on 2020-04-09 |
| | | */ |
| | | public class Protocol<T> implements Serializable { |
| | | |
| | | private static final long serialVersionUID = 4893280118017319089L; |
| | | |
| | | private int code; |
| | | |
| | | private String msg; |
| | | |
| | | private T data; |
| | | |
| | | public Protocol() { |
| | | } |
| | | |
| | | public Protocol(int code, String msg, T data) { |
| | | super(); |
| | | setCode(code); |
| | | setMsg(msg); |
| | | setData(data); |
| | | } |
| | | |
| | | public Protocol(int code, String message) { |
| | | this(code, message, null); |
| | | } |
| | | |
| | | public static <T> Protocol<T> ok(){ |
| | | return parse(BaseRes.OK); |
| | | } |
| | | |
| | | public static <T> Protocol<T> ok(T result){ |
| | | Protocol<T> protocol = parse(BaseRes.OK); |
| | | protocol.setData(result); |
| | | return protocol; |
| | | } |
| | | |
| | | public static <T> Protocol<T> error(){ |
| | | return parse(BaseRes.ERROR); |
| | | } |
| | | |
| | | public static <T> Protocol<T> error(String message) { |
| | | Protocol<T> protocol = parse(BaseRes.ERROR); |
| | | protocol.setMsg(message); |
| | | return protocol; |
| | | } |
| | | |
| | | public static <T> Protocol<T> parse(String str) { |
| | | if(Cools.isEmpty(str)){ |
| | | return parse(BaseRes.ERROR); |
| | | } |
| | | String[] msg = str.split("-"); |
| | | if(msg.length==2){ |
| | | return new Protocol<>(Integer.parseInt(msg[0]),msg[1]); |
| | | }else{ |
| | | return parse("500-".concat(str)); |
| | | } |
| | | } |
| | | |
| | | public int getCode() { |
| | | return code; |
| | | } |
| | | |
| | | public void setCode(int code) { |
| | | this.code = code; |
| | | } |
| | | |
| | | public String getMsg() { |
| | | return msg; |
| | | } |
| | | |
| | | public void setMsg(String msg) { |
| | | this.msg = msg; |
| | | } |
| | | |
| | | public T getData() { |
| | | return data; |
| | | } |
| | | |
| | | public void setData(T data) { |
| | | this.data = data; |
| | | } |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.common; |
| | | |
| | | import java.util.HashMap; |
| | | |
| | | /** |
| | | * Created by vincent on 2019-06-09 |
| | | */ |
| | | public class R extends HashMap<String, Object> { |
| | | |
| | | private static final long serialVersionUID = 1L; |
| | | |
| | | private static final String CODE = "code"; |
| | | private static final String MSG = "msg"; |
| | | private static final String DATA = "data"; |
| | | |
| | | public R(Integer code, String msg){ |
| | | super.put(CODE, code); |
| | | super.put(MSG, msg); |
| | | } |
| | | |
| | | public static R ok(){ |
| | | return parse(BaseRes.OK); |
| | | } |
| | | |
| | | public static R ok(String msg){ |
| | | R r = ok(); |
| | | r.put(MSG, msg); |
| | | return r; |
| | | } |
| | | |
| | | public static R ok(Object obj){ |
| | | return parse(BaseRes.OK).add(obj); |
| | | } |
| | | |
| | | public static R error(){ |
| | | return parse(BaseRes.ERROR); |
| | | } |
| | | |
| | | public static R error(String msg){ |
| | | R r = error(); |
| | | r.put(MSG, msg); |
| | | return r; |
| | | } |
| | | |
| | | public R add(Object obj){ |
| | | this.put(DATA, obj); |
| | | return this; |
| | | } |
| | | |
| | | public static R parse(String message){ |
| | | if(Cools.isEmpty(message)){ |
| | | return parse(BaseRes.ERROR); |
| | | } |
| | | String[] msg = message.split("-"); |
| | | if(msg.length==2){ |
| | | return new R(Integer.parseInt(msg[0]),msg[1]); |
| | | }else{ |
| | | return parse("500-".concat(message)); |
| | | } |
| | | } |
| | | |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.common; |
| | | |
| | | import java.io.UnsupportedEncodingException; |
| | | import java.nio.charset.Charset; |
| | | |
| | | /** |
| | | * radix tools |
| | | * Created by vincent on 2018/10/6 |
| | | */ |
| | | public class RadixTools { |
| | | |
| | | public static void main(String[] args) { |
| | | String s = RadixTools.toBinaryString((byte) 1); |
| | | System.out.println(s); |
| | | for(int i=s.length()-1;i>=0;i--){ |
| | | char c=s.charAt(i); |
| | | if (i == 7 && c =='1'){ |
| | | System.out.println("==="); |
| | | } |
| | | } |
| | | } |
| | | |
| | | /************************************** BinaryString **********************************************/ |
| | | |
| | | public static String toBinaryString(byte b){ |
| | | return Long.toBinaryString((b & 0xFF) + 0x100).substring(1); |
| | | } |
| | | |
| | | public static String toBinaryString(byte[] bytes){ |
| | | StringBuilder sb = new StringBuilder(); |
| | | for (byte aByte : bytes) { |
| | | sb.append(Long.toBinaryString((aByte & 0xFF) + 0x100).substring(1)); |
| | | } |
| | | return sb.toString(); |
| | | } |
| | | |
| | | /************************************** HexString **********************************************/ |
| | | |
| | | public static byte[] hexStringToBytes(String hexString) { |
| | | if (hexString == null || hexString.equals("")) { |
| | | return null; |
| | | } |
| | | hexString = hexString.toUpperCase(); |
| | | int length = hexString.length() / 2; |
| | | char[] hexChars = hexString.toCharArray(); |
| | | byte[] d = new byte[length]; |
| | | for (int i = 0; i < length; i++) { |
| | | int pos = i * 2; |
| | | d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1])); |
| | | } |
| | | return d; |
| | | } |
| | | |
| | | public static String bytesToHexStr(byte[] bytes){ |
| | | StringBuilder buf = new StringBuilder(bytes.length * 2); |
| | | for(byte b : bytes) { |
| | | buf.append(String.format("%02x", b & 0xff)); |
| | | } |
| | | |
| | | return buf.toString(); |
| | | } |
| | | |
| | | private static byte charToByte(char c) { |
| | | return (byte) "0123456789ABCDEF".indexOf(c); |
| | | } |
| | | |
| | | |
| | | /************************************** String **********************************************/ |
| | | |
| | | public static String bytesToStr(byte[] bytes){ |
| | | return bytesToStr(bytes, Charset.forName("gbk")); |
| | | } |
| | | |
| | | public static String bytesToStr(byte[] bytes, Charset charset){ |
| | | return new String(bytes, charset).trim().toUpperCase(); |
| | | } |
| | | |
| | | public static byte[] strToBytes(String str) throws UnsupportedEncodingException { |
| | | return str.getBytes("gbk"); |
| | | } |
| | | |
| | | /************************************** long **********************************************/ |
| | | |
| | | public static byte[] longToBytes(long number) { |
| | | long temp = number; |
| | | byte[] b = new byte[8]; |
| | | for (int i = 0; i < b.length; i++) { |
| | | b[i] = new Long(temp & 0xff).byteValue();// 将最低位保存在最低位 |
| | | temp = temp >> 8; // 向右移8位 |
| | | } |
| | | return b; |
| | | } |
| | | |
| | | public static long bytesToLong(byte[] bytes) { |
| | | long s = 0; |
| | | long s0 = bytes[0] & 0xff;// 最低位 |
| | | long s1 = bytes[1] & 0xff; |
| | | long s2 = bytes[2] & 0xff; |
| | | long s3 = bytes[3] & 0xff; |
| | | long s4 = bytes[4] & 0xff;// 最低位 |
| | | long s5 = bytes[5] & 0xff; |
| | | long s6 = bytes[6] & 0xff; |
| | | long s7 = bytes[7] & 0xff; |
| | | |
| | | // s0不变 |
| | | s1 <<= 8; |
| | | s2 <<= 16; |
| | | s3 <<= 24; |
| | | s4 <<= 8 * 4; |
| | | s5 <<= 8 * 5; |
| | | s6 <<= 8 * 6; |
| | | s7 <<= 8 * 7; |
| | | s = s0 | s1 | s2 | s3 | s4 | s5 | s6 | s7; |
| | | return s; |
| | | } |
| | | |
| | | |
| | | /************************************** int **********************************************/ |
| | | |
| | | public static byte[] intToBytes(int n) { |
| | | byte[] b = new byte[4]; |
| | | b[3] = (byte) (n & 0xff); |
| | | b[2] = (byte) (n >> 8 & 0xff); |
| | | b[1] = (byte) (n >> 16 & 0xff); |
| | | b[0] = (byte) (n >> 24 & 0xff); |
| | | return b; |
| | | } |
| | | |
| | | |
| | | public static int bytesToInt(byte[] b) { |
| | | int s = 0; |
| | | int s0 = b[0] & 0xff;// 最低位 |
| | | int s1 = b[1] & 0xff; |
| | | int s2 = b[2] & 0xff; |
| | | int s3 = b[3] & 0xff; |
| | | s0 <<= 24; |
| | | s1 <<= 16; |
| | | s2 <<= 8; |
| | | s = s0 | s1 | s2 | s3; |
| | | return s; |
| | | } |
| | | |
| | | /************************************** short **********************************************/ |
| | | |
| | | public static short byteToShort(byte[] b) { |
| | | short s = 0; |
| | | short s0 = (short) (b[1] & 0xff);// 最低位 |
| | | short s1 = (short) (b[0] & 0xff); |
| | | s1 <<= 8; |
| | | s = (short) (s0 | s1); |
| | | return s; |
| | | } |
| | | |
| | | public static byte[] shortToByte(short s){ |
| | | byte[] b = new byte[2]; |
| | | for(int i = 0; i < 2; i++){ |
| | | int offset = 16 - (i+1)*8; //因为byte占4个字节,所以要计算偏移量 |
| | | b[i] = (byte)((s >> offset)&0xff); //把16位分为2个8位进行分别存储 |
| | | } |
| | | return b; |
| | | } |
| | | |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.common; |
| | | |
| | | /** |
| | | * Twitter_Snowflake<br> |
| | | * SnowFlake的结构如下(每部分用-分开):<br> |
| | | * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - |
| | | * 000000000000 <br> |
| | | * 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0<br> |
| | | * 41位时间截(毫秒级),注意,41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截) |
| | | * 得到的值),这里的的开始时间截,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序IdWorker类的startTime属性)。41位的时间截,可以使用69年,年T |
| | | * = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br> |
| | | * 10位的数据机器位,可以部署在1024个节点,包括5位datacenterId和5位workerId<br> |
| | | * 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号<br> |
| | | * 加起来刚好64位,为一个Long型。<br> |
| | | * SnowFlake的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分),并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右。 |
| | | */ |
| | | public class SnowflakeIdWorker { |
| | | |
| | | // ==============================Fields=========================================== |
| | | /** 开始时间截 (2015-01-01) */ |
| | | private final long twepoch = 1420041600000L; |
| | | |
| | | /** 序列值所占的位数 */ |
| | | private final long sequenceBits = 12L; |
| | | |
| | | /** 机器id所占的位数 */ |
| | | private final long workerIdBits = 5L; |
| | | |
| | | /** 机房id所占的位数 */ |
| | | private final long datacenterIdBits = 5L; |
| | | |
| | | /** 机器id向左移12位 */ |
| | | private final long workerIdLeftShift = sequenceBits; |
| | | |
| | | /** 机房id向左移17位(5+12) */ |
| | | private final long datacenterIdLeftShift =workerIdLeftShift + workerIdBits; |
| | | |
| | | /** 时间截向左移22位(5+5+12) */ |
| | | private final long timestampLeftShift = datacenterIdLeftShift + datacenterIdBits; |
| | | |
| | | /** 支持的最大机器id (位数二进制值) */ |
| | | private final long maxWorkerId = -1L ^ (-1L << workerIdBits); |
| | | |
| | | /** 支持的最大数据标识id (位数二进制值) */ |
| | | private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); |
| | | |
| | | /**生成序列的掩码 */ |
| | | private final long sequenceMask = -1L ^ (-1L << sequenceBits); |
| | | |
| | | /** 工作机器ID(0~31) */ |
| | | private long workerId; |
| | | |
| | | /** 数据中心ID(0~31) */ |
| | | private long datacenterId; |
| | | |
| | | /** 毫秒内序列 */ |
| | | private long sequence = 0L; |
| | | |
| | | /** 上次生成ID的时间截 */ |
| | | private long lastTimestamp = -1L; |
| | | |
| | | // ==============================Constructors===================================== |
| | | |
| | | /** |
| | | * 构造函数 |
| | | * |
| | | * @param workerId |
| | | * 工作ID (0~31) |
| | | * @param datacenterId |
| | | * 数据中心ID (0~31) |
| | | */ |
| | | public SnowflakeIdWorker(long workerId, long datacenterId) { |
| | | if (workerId > maxWorkerId || workerId < 0) { |
| | | throw new IllegalArgumentException( |
| | | String.format("worker Id can't be greater than %d or less than 0", maxWorkerId)); |
| | | } |
| | | if (datacenterId > maxDatacenterId || datacenterId < 0) { |
| | | throw new IllegalArgumentException( |
| | | String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId)); |
| | | } |
| | | this.workerId = workerId; |
| | | this.datacenterId = datacenterId; |
| | | } |
| | | |
| | | public SnowflakeIdWorker(){ |
| | | this(0L, 0L); |
| | | } |
| | | |
| | | // ==============================Methods========================================== |
| | | /** |
| | | * 获得下一个ID (该方法是线程安全的) |
| | | * |
| | | * @return SnowflakeId |
| | | */ |
| | | public synchronized long nextId() { |
| | | long timestamp = timeGen(); |
| | | |
| | | // 如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常 |
| | | if (timestamp < lastTimestamp) { |
| | | throw new RuntimeException(String.format( |
| | | "Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); |
| | | } |
| | | |
| | | // 如果是同一时间生成的,则进行毫秒内序列 |
| | | if (lastTimestamp == timestamp) { |
| | | sequence = (sequence + 1) & sequenceMask; |
| | | // 毫秒内序列溢出 |
| | | if (sequence == 0) { |
| | | // 阻塞到下一个毫秒,获得新的时间戳 |
| | | timestamp = tilNextMillis(lastTimestamp); |
| | | } |
| | | } |
| | | // 时间戳改变,毫秒内序列重置 |
| | | else { |
| | | sequence = 0L; |
| | | } |
| | | |
| | | // 上次生成ID的时间截 |
| | | lastTimestamp = timestamp; |
| | | |
| | | // 移位并通过或运算拼到一起组成64位的ID |
| | | return ((timestamp - twepoch) << timestampLeftShift) // |
| | | | (datacenterId << datacenterIdLeftShift) // |
| | | | (workerId << workerIdLeftShift) // |
| | | | sequence; |
| | | } |
| | | |
| | | /** |
| | | * 阻塞到下一个毫秒,直到获得新的时间戳 |
| | | * |
| | | * @param lastTimestamp |
| | | * 上次生成ID的时间截 |
| | | * @return 当前时间戳 |
| | | */ |
| | | protected long tilNextMillis(long lastTimestamp) { |
| | | long timestamp = timeGen(); |
| | | while (timestamp <= lastTimestamp) { |
| | | timestamp = timeGen(); |
| | | } |
| | | return timestamp; |
| | | } |
| | | |
| | | /** |
| | | * 返回以毫秒为单位的当前时间 |
| | | * |
| | | * @return 当前时间(毫秒) |
| | | */ |
| | | protected long timeGen() { |
| | | return System.currentTimeMillis(); |
| | | } |
| | | |
| | | // ==============================Test============================================= |
| | | /** 测试 */ |
| | | public static void main(String[] args) { |
| | | SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0); |
| | | for (int i = 0; i < 1000; i++) { |
| | | long id = idWorker.nextId(); |
| | | System.out.println(Long.toBinaryString(id)); |
| | | System.out.println(id); |
| | | } |
| | | } |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.common; |
| | | |
| | | import com.zy.asrs.framework.exception.CoolException; |
| | | import org.springframework.beans.BeansException; |
| | | import org.springframework.context.ApplicationContext; |
| | | import org.springframework.context.ApplicationContextAware; |
| | | |
| | | public class SpringUtils implements ApplicationContextAware { |
| | | |
| | | private static ApplicationContext application; |
| | | |
| | | public SpringUtils() {} |
| | | |
| | | public static void init(ApplicationContext context) { |
| | | SpringUtils.application = context; |
| | | } |
| | | |
| | | @Override |
| | | public void setApplicationContext(ApplicationContext context) throws BeansException { |
| | | SpringUtils.application = context; |
| | | } |
| | | |
| | | public static ApplicationContext getApplicationContext() { |
| | | if(application==null) { |
| | | throw new CoolException(BaseRes.ERROR); |
| | | } |
| | | return application; |
| | | } |
| | | |
| | | public static <T>T getBean(Class<T> prototype) { |
| | | return getApplicationContext().getBean(prototype); |
| | | } |
| | | |
| | | public static Object getBean(String name) { |
| | | return getApplicationContext().getBean(name); |
| | | } |
| | | |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.config; |
| | | |
| | | //import com.baomidou.mybatisplus.plugins.PaginationInterceptor; |
| | | |
| | | import com.zy.asrs.framework.common.SnowflakeIdWorker; |
| | | import com.zy.asrs.framework.common.SpringUtils; |
| | | import org.springframework.context.annotation.Bean; |
| | | import org.springframework.context.annotation.Configuration; |
| | | |
| | | /** |
| | | * Created by vincent on 2019-06-10 |
| | | */ |
| | | @Configuration |
| | | public class CoolBaseConfig { |
| | | |
| | | // @Bean |
| | | // public PaginationInterceptor paginationInterceptor() { |
| | | // return new PaginationInterceptor(); |
| | | // } |
| | | |
| | | @Bean |
| | | public SpringUtils getSpringUtils(){ |
| | | return new SpringUtils(); |
| | | } |
| | | |
| | | @Bean |
| | | public SnowflakeIdWorker snowflakeIdWorker(){ |
| | | return new SnowflakeIdWorker(); |
| | | } |
| | | |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.controller; |
| | | |
| | | import com.zy.asrs.framework.common.BaseRes; |
| | | import com.zy.asrs.framework.common.Cools; |
| | | import com.zy.asrs.framework.exception.CoolException; |
| | | |
| | | import java.lang.reflect.Method; |
| | | import java.util.ArrayList; |
| | | import java.util.HashMap; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | import java.util.regex.Matcher; |
| | | import java.util.regex.Pattern; |
| | | |
| | | /** |
| | | * Created by vincent on 2019-06-09 |
| | | */ |
| | | public abstract class AbstractBaseController { |
| | | |
| | | public <T> List exportSupport(List<T> list, List<String> fields){ |
| | | if (Cools.isEmpty(list)){ |
| | | throw new CoolException(BaseRes.EMPTY); |
| | | } |
| | | try { |
| | | List<List<Object>> result = new ArrayList<>(); |
| | | Method[] methods = list.get(0).getClass().getMethods(); |
| | | for (T t : list){ |
| | | List<Object> node = new ArrayList<>(); |
| | | for (String field : fields){ |
| | | for (Method method : methods) { |
| | | if (("get" + field).toLowerCase().equals(method.getName().toLowerCase())) { |
| | | Object val = method.invoke(t); |
| | | node.add(val); |
| | | break; |
| | | } |
| | | } |
| | | } |
| | | result.add(node); |
| | | } |
| | | return result; |
| | | } catch (Exception e){ |
| | | throw new RuntimeException(e); |
| | | } |
| | | |
| | | } |
| | | |
| | | public static Map<String, Object> excludeTrash(Map<String, Object> map){ |
| | | if (Cools.isEmpty(map)){ |
| | | return new HashMap<>(); |
| | | } |
| | | map.entrySet().removeIf(next -> next.getKey().equals("curr") |
| | | || next.getKey().equals("limit") |
| | | || next.getKey().equals("orderByField") |
| | | || next.getKey().equals("orderByType") |
| | | || next.getKey().equals("condition") |
| | | || Cools.isEmpty(next.getValue())); |
| | | return map; |
| | | } |
| | | |
| | | public static String humpToLine(String str) { |
| | | Matcher matcher = Pattern.compile("[A-Z]").matcher(str); |
| | | StringBuffer sb = new StringBuffer(); |
| | | while (matcher.find()) { |
| | | matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase()); |
| | | } |
| | | matcher.appendTail(sb); |
| | | return sb.toString(); |
| | | } |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.domain; |
| | | |
| | | /** |
| | | * Created by vincent on 2021/4/13 |
| | | */ |
| | | public class KeyValueVo { |
| | | |
| | | private String name; |
| | | |
| | | private Long value; |
| | | |
| | | public KeyValueVo() { |
| | | } |
| | | |
| | | public KeyValueVo(String name, Long value) { |
| | | this.name = name; |
| | | this.value = value; |
| | | } |
| | | |
| | | public String getName() { |
| | | return name; |
| | | } |
| | | |
| | | public void setName(String name) { |
| | | this.name = name; |
| | | } |
| | | |
| | | public Long getValue() { |
| | | return value; |
| | | } |
| | | |
| | | public void setValue(Long value) { |
| | | this.value = value; |
| | | } |
| | | |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.exception; |
| | | |
| | | /** |
| | | * 应用异常 |
| | | */ |
| | | public class ApplicationException extends RuntimeException { |
| | | |
| | | private static final long serialVersionUID = 1L; |
| | | |
| | | public ApplicationException(Throwable e) { |
| | | super(e); |
| | | } |
| | | |
| | | public ApplicationException(String message) { |
| | | super(message); |
| | | } |
| | | |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.exception; |
| | | |
| | | /** |
| | | * 框架异常 |
| | | * Created by vincent on 2019-09-04 |
| | | */ |
| | | public class CoolException extends RuntimeException { |
| | | |
| | | public CoolException(Throwable e) { |
| | | super(e); |
| | | } |
| | | |
| | | public CoolException(String message) { |
| | | super(message); |
| | | } |
| | | |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.generators; |
| | | |
| | | import com.zy.asrs.framework.common.Cools; |
| | | import com.zy.asrs.framework.generators.constant.SqlOsType; |
| | | import com.zy.asrs.framework.generators.domain.Column; |
| | | import com.zy.asrs.framework.generators.utils.GeneratorUtils; |
| | | import org.springframework.core.io.ClassPathResource; |
| | | |
| | | import java.io.*; |
| | | import java.sql.*; |
| | | import java.util.ArrayList; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | |
| | | /** |
| | | * Created by vincent on 2019-06-18 |
| | | */ |
| | | public class CoolGenerator { |
| | | |
| | | private static final String BASE_DIR = "src/main/"; |
| | | private static final String JAVA_DIR = BASE_DIR + "java/"; |
| | | private static final String XML_DIR = BASE_DIR + "resources/mapper/"; |
| | | private static final String HTML_DIR = BASE_DIR + "webapp/"; |
| | | private static final String[] ALL_TEMPLATES = new String[]{ |
| | | "Controller", |
| | | "Service", |
| | | "ServiceImpl", |
| | | "Mapper", |
| | | "Entity", |
| | | "Xml", |
| | | "Html", |
| | | "HtmlDetail", |
| | | "Js", |
| | | "Sql"}; |
| | | private static final ArrayList<String> SYSTEM_MODEL = new ArrayList<String>(){{ |
| | | add("User"); |
| | | add("Host"); |
| | | }}; |
| | | |
| | | |
| | | public String url; |
| | | public String username; |
| | | public String password; |
| | | public String table; |
| | | public String packagePath; |
| | | public boolean controller = true; |
| | | public boolean service = true; |
| | | public boolean mapper = true; |
| | | public boolean entity = true; |
| | | public boolean xml = true; |
| | | public boolean html = true; |
| | | public boolean htmlDetail = false; |
| | | public boolean js = true; |
| | | public boolean sql = true; |
| | | public SqlOsType sqlOsType; |
| | | |
| | | private List<Column> columns = new ArrayList<>(); |
| | | private String fullEntityName; |
| | | private String simpleEntityName; |
| | | private String entityImport; |
| | | private String entityContent; |
| | | private String xmlContent; |
| | | private String htmlContent; |
| | | private String htmlDialogContent; |
| | | private String jsTableContent; |
| | | private String jsForeignKeyContent; |
| | | private String jsDateContent; |
| | | private String jsPrimaryKeyDoms; |
| | | private String primaryKeyColumn; |
| | | private String majorColumn; |
| | | private String systemPackagePath; |
| | | private String systemPackage; |
| | | |
| | | public void build() throws Exception { |
| | | init(); |
| | | for (String template : ALL_TEMPLATES){ |
| | | boolean pass = false; |
| | | String lowerCase = template.toLowerCase(); |
| | | String templatePath = lowerCase.contains("impl")?lowerCase.substring(0,lowerCase.length()-4)+"/"+lowerCase.substring(lowerCase.length()-4):lowerCase; |
| | | String directory=""; |
| | | String fileName=""; |
| | | switch (template){ |
| | | case "Controller": |
| | | pass = controller; |
| | | directory = JAVA_DIR + packagePath.replace(".", "/")+"/"+templatePath+"/"; |
| | | fileName = fullEntityName+template+".java"; |
| | | break; |
| | | case "Service": |
| | | pass = service; |
| | | directory = JAVA_DIR + packagePath.replace(".", "/")+"/"+templatePath+"/"; |
| | | fileName = fullEntityName+template+".java"; |
| | | break; |
| | | case "ServiceImpl": |
| | | pass = service; |
| | | directory = JAVA_DIR + packagePath.replace(".", "/")+"/"+templatePath+"/"; |
| | | fileName = fullEntityName+template+".java"; |
| | | break; |
| | | case "Mapper": |
| | | pass = mapper; |
| | | directory = JAVA_DIR + packagePath.replace(".", "/")+"/"+templatePath+"/"; |
| | | fileName = fullEntityName+template+".java"; |
| | | break; |
| | | case "Entity": |
| | | pass = entity; |
| | | directory = JAVA_DIR + packagePath.replace(".", "/")+"/"+templatePath+"/"; |
| | | fileName = fullEntityName+".java"; |
| | | break; |
| | | case "Xml": |
| | | pass = xml; |
| | | directory = XML_DIR; |
| | | fileName = fullEntityName+"Mapper.xml"; |
| | | break; |
| | | case "Html": |
| | | pass = html; |
| | | directory = HTML_DIR + "/views/" + simpleEntityName + "/"; |
| | | fileName = simpleEntityName+".html"; |
| | | break; |
| | | case "Js": |
| | | pass = js; |
| | | directory = HTML_DIR + "/static/js/" + simpleEntityName + "/"; |
| | | fileName = simpleEntityName+".js"; |
| | | break; |
| | | case "Sql": |
| | | pass = sql; |
| | | directory = JAVA_DIR; |
| | | fileName = simpleEntityName+".sql"; |
| | | default: |
| | | break; |
| | | } |
| | | if (!pass){ continue; } |
| | | String content = readFile(template); |
| | | writeFile(content, directory, fileName, template); |
| | | } |
| | | } |
| | | |
| | | private void init() throws Exception { |
| | | gainDbInfo(); |
| | | fullEntityName = GeneratorUtils.getNameSpace(table); |
| | | simpleEntityName = fullEntityName.substring(0, 1).toLowerCase()+fullEntityName.substring(1); |
| | | entityContent = createEntityMsg(); |
| | | xmlContent = createXmlMsg(); |
| | | htmlContent = createHtmlMsg(); |
| | | htmlDialogContent = createHtmlDialogMsg(); |
| | | jsTableContent = createJsTableMsg(); |
| | | jsForeignKeyContent = createJsFkContent(); |
| | | jsDateContent = createJsDateContent(); |
| | | jsPrimaryKeyDoms = createJsPrimaryKeyMsg(); |
| | | primaryKeyColumn = createPrimaryMsg(); |
| | | majorColumn = createMajorMsg(); |
| | | String[] packagePathSplit = packagePath.split("\\."); |
| | | systemPackagePath = packagePath.replaceAll(packagePathSplit[packagePathSplit.length-1], "system"); |
| | | String[] split = systemPackagePath.split("\\."); |
| | | systemPackage = ""; |
| | | for (int i = 1;i <= split.length; i++) { |
| | | if (i != split.length) { |
| | | if (i == split.length - 1) { |
| | | systemPackage = systemPackage + split[i-1]; |
| | | } else { |
| | | systemPackage = systemPackage + split[i-1] + "."; |
| | | } |
| | | } |
| | | |
| | | } |
| | | } |
| | | |
| | | private String readFile(String template){ |
| | | StringBuilder txtContentBuilder=new StringBuilder(); |
| | | ClassPathResource classPath=new ClassPathResource("templates/"+template + ".txt"); |
| | | |
| | | try (BufferedReader reader = new BufferedReader(new InputStreamReader(classPath.getInputStream()))) { |
| | | String lineContent; |
| | | while ((lineContent = reader.readLine()) != null) { |
| | | txtContentBuilder.append(lineContent).append("\n"); |
| | | } |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | } |
| | | return txtContentBuilder.toString(); |
| | | } |
| | | |
| | | private void writeFile(String content, String directory, String fileName, String template) throws IOException { |
| | | File codeDirectory=new File(directory); |
| | | if(!codeDirectory.exists()){ |
| | | codeDirectory.mkdirs(); |
| | | } |
| | | File writerFile=new File(directory+fileName); |
| | | if(!writerFile.exists()){ |
| | | content=content. |
| | | replaceAll("@\\{TABLENAME}", table) |
| | | .replaceAll("@\\{ENTITYIMPORT}", entityImport) |
| | | .replaceAll("@\\{ENTITYCONTENT}", entityContent) |
| | | .replaceAll("@\\{ENTITYNAME}", fullEntityName) |
| | | .replaceAll("@\\{SIMPLEENTITYNAME}", simpleEntityName) |
| | | .replaceAll("@\\{UENTITYNAME}", simpleEntityName) |
| | | .replaceAll("@\\{COMPANYNAME}",packagePath) |
| | | .replaceAll("@\\{XMLCONTENT}", xmlContent) |
| | | .replaceAll("@\\{HTMLCONTENT}", htmlContent) |
| | | .replaceAll("@\\{HTMLDIALOGCONTENT}", htmlDialogContent) |
| | | .replaceAll("@\\{JSTABLECONTENT}", jsTableContent) |
| | | .replaceAll("@\\{JSFOREIGNKEYCONTENT}", jsForeignKeyContent) |
| | | .replaceAll("@\\{JSDATECONTENT}", jsDateContent) |
| | | .replaceAll("@\\{JSPRIMARYKEYDOMS}", jsPrimaryKeyDoms) |
| | | .replaceAll("@\\{MAJORCOLUMN}", GeneratorUtils.humpToLine(majorColumn)) |
| | | .replaceAll("@\\{MAJORCOLUMN_UP}", GeneratorUtils.firstCharConvert(GeneratorUtils.humpToLine(majorColumn), false)) |
| | | .replaceAll("@\\{PRIMARYKEYCOLUMN}", GeneratorUtils.firstCharConvert(primaryKeyColumn, false)) |
| | | .replaceAll("@\\{PRIMARYKEYCOLUMN0}", GeneratorUtils.firstCharConvert(primaryKeyColumn, true)) |
| | | .replaceAll("@\\{UPCASEMARJORCOLUMN}", GeneratorUtils.firstCharConvert(primaryKeyColumn, false)) |
| | | .replaceAll("@\\{SYSTEMPACKAGE}",systemPackage) |
| | | ; |
| | | writerFile.createNewFile(); |
| | | BufferedWriter writer=new BufferedWriter(new FileWriter(writerFile)); |
| | | writer.write(content); |
| | | writer.flush(); |
| | | writer.close(); |
| | | System.out.println(fullEntityName+template+" 源文件创建成功!"); |
| | | }else{ |
| | | System.out.println(fullEntityName+template+" 源文件已经存在创建失败!"); |
| | | } |
| | | } |
| | | |
| | | private void gainDbInfo() throws Exception { |
| | | Connection conn; |
| | | if (null == this.sqlOsType) { |
| | | throw new RuntimeException("请指定数据库类型!"); |
| | | } |
| | | switch (this.sqlOsType) { |
| | | case MYSQL: |
| | | Class.forName("com.mysql.jdbc.Driver").newInstance(); |
| | | conn = DriverManager.getConnection("jdbc:mysql://"+url, username, password); |
| | | this.columns = getMysqlColumns(conn, table, true, sqlOsType); |
| | | break; |
| | | case SQL_SERVER: |
| | | Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); |
| | | conn = DriverManager.getConnection("jdbc:sqlserver://"+url, username, password); |
| | | this.columns = getSqlServerColumns(conn, table, true, sqlOsType); |
| | | break; |
| | | default: |
| | | throw new RuntimeException("请指定数据库类型!"); |
| | | } |
| | | |
| | | } |
| | | |
| | | // mysql |
| | | public static List<Column> getMysqlColumns(Connection conn, String table, boolean init, SqlOsType sqlOsType) throws Exception { |
| | | List<Column> result = new ArrayList<>(); |
| | | PreparedStatement ps = conn.prepareStatement("select * from " + table); |
| | | ResultSetMetaData meta = ps.executeQuery().getMetaData(); |
| | | // 单表字段数量 |
| | | int count = meta.getColumnCount(); |
| | | ResultSet resultSet = ps.executeQuery("show full columns from " + table); |
| | | for (int i = 1; i < count + 1; i++) { |
| | | String columnName = meta.getColumnName(i); |
| | | if (resultSet.next() && columnName.equals(resultSet.getString("Field"))){ |
| | | result.add(new Column( |
| | | conn, |
| | | meta.getColumnName(i), |
| | | GeneratorUtils.getType(meta.getColumnType(i)), |
| | | resultSet.getString("Comment"), |
| | | resultSet.getString("Key").equals("PRI"), |
| | | resultSet.getString("Key").equals("PRI"), |
| | | resultSet.getString("Null").equals("NO"), |
| | | GeneratorUtils.getColumnLength(resultSet.getString("Type")), |
| | | init, |
| | | sqlOsType |
| | | )); |
| | | } |
| | | result.forEach(column -> System.out.println(column.toString())); |
| | | } |
| | | return result; |
| | | } |
| | | |
| | | // sqlserver |
| | | public static List<Column> getSqlServerColumns(Connection conn, String table, boolean init, SqlOsType sqlOsType) throws Exception { |
| | | List<Column> result = new ArrayList<>(); |
| | | PreparedStatement ps = conn.prepareStatement("select * from " + table); |
| | | ResultSetMetaData meta = ps.executeQuery().getMetaData(); |
| | | // 单表字段数量 |
| | | int count = meta.getColumnCount(); |
| | | StringBuilder sql = new StringBuilder("SELECT \n" + |
| | | " 'Field'= a.name,\n" + |
| | | " 'Comment'= isnull(g.[value],''),\n" + |
| | | " 'Key'= case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then 'PRI' else '' end,\n" + |
| | | " 'Main'= case when exists(SELECT 1 FROM sysobjects where xtype='PK' and parent_obj=a.id and name in (SELECT name FROM sysindexes WHERE indid in( SELECT indid FROM sysindexkeys WHERE id = a.id AND colid=a.colid))) then 'PRI' else '' end,"+ |
| | | " 'Type'= b.name,\n" + |
| | | " 'Length'= COLUMNPROPERTY(a.id,a.name,'PRECISION'),\n" + |
| | | " 'Decimals'= isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0),\n" + |
| | | " 'Null'= case when a.isnullable=1 then 'Yes' else 'No' end,\n" + |
| | | " 'Default' = isnull(e.text,'')\n" + |
| | | "FROM syscolumns a\n" + |
| | | "LEFT JOIN systypes b on a.xusertype=b.xusertype\n" + |
| | | "INNER JOIN sysobjects d on a.id=d.id and d.xtype='U' and d.name<>'dtproperties'\n" + |
| | | "LEFT JOIN syscomments e on a.cdefault=e.id\n" + |
| | | "LEFT JOIN sys.extended_properties g on a.id=G.major_id and a.colid=g.minor_id \n" + |
| | | "LEFT JOIN sys.extended_properties f on d.id=f.major_id and f.minor_id=0 where d.name = '") |
| | | .append(table).append("' ORDER BY a.colorder ASC"); |
| | | ResultSet resultSet = conn.prepareStatement(sql.toString()).executeQuery(); |
| | | for (int i = 1; i < count + 1; i++) { |
| | | String columnName = meta.getColumnName(i); |
| | | if (resultSet.next() && columnName.equals(resultSet.getString("Field"))){ |
| | | result.add(new Column( |
| | | conn, |
| | | meta.getColumnName(i), |
| | | GeneratorUtils.getType(meta.getColumnType(i)), |
| | | resultSet.getString("Comment"), |
| | | resultSet.getString("Key").equals("PRI"), |
| | | resultSet.getString("Main").equals("PRI"), |
| | | resultSet.getString("Null").equals("No"), |
| | | GeneratorUtils.getColumnLength(resultSet.getString("Type")), |
| | | init, |
| | | sqlOsType |
| | | )); |
| | | } |
| | | } |
| | | result.forEach(column -> System.out.println(column.toString())); |
| | | return result; |
| | | } |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | /**********************************************************************************************/ |
| | | /************************************* Entity动态字段 *******************************************/ |
| | | /**********************************************************************************************/ |
| | | |
| | | private String createEntityMsg(){ |
| | | if (Cools.isEmpty(systemPackagePath)) { |
| | | String[] packagePathSplit = packagePath.split("\\."); |
| | | systemPackagePath = packagePath.replaceAll(packagePathSplit[packagePathSplit.length-1], "system"); |
| | | } |
| | | if (columns.isEmpty()){ |
| | | return null; |
| | | } |
| | | StringBuilder sb = new StringBuilder(); |
| | | StringBuilder entityIm = new StringBuilder("import com.core.common.Cools;"); |
| | | boolean setTableField = true; |
| | | boolean setTableId = true; |
| | | boolean setDateTimeFormat = true; |
| | | for (Column column : columns){ |
| | | if (column.getType().equals("Date")){ |
| | | entityIm.append("import java.text.SimpleDateFormat;\n") |
| | | .append("import java.util.Date;\n"); |
| | | } |
| | | |
| | | // 注释 |
| | | if (!Cools.isEmpty(column.getComment())){ |
| | | sb.append(" /**\n") |
| | | .append(" * ") |
| | | .append(column.getWholeComment()) |
| | | .append("\n") |
| | | .append(" */") |
| | | .append("\n"); |
| | | } |
| | | |
| | | // swagger |
| | | sb.append(" @ApiModelProperty(value= \"") |
| | | .append(column.getWholeComment()) |
| | | .append("\")\n"); |
| | | |
| | | |
| | | // 主键修饰 |
| | | if (column.isMainKey()){ |
| | | if (setTableId){ |
| | | entityIm.append("import com.baomidou.mybatisplus.annotations.TableId;").append("\n") |
| | | .append("import com.baomidou.mybatisplus.enums.IdType;").append("\n"); |
| | | setTableId = false; |
| | | } |
| | | if (column.isOnly()){ |
| | | sb.append(" ") |
| | | .append("@TableId(value = \"") |
| | | .append(column.getName()) |
| | | .append("\", type = IdType.AUTO)") |
| | | .append("\n"); |
| | | } else { |
| | | sb.append(" ") |
| | | .append("@TableId(value = \"") |
| | | .append(column.getName()) |
| | | .append("\", type = IdType.INPUT)") |
| | | .append("\n"); |
| | | } |
| | | |
| | | } |
| | | |
| | | // 外键修饰 |
| | | if (!Cools.isEmpty(column.getForeignKeyMajor())){ |
| | | entityIm.append("import com.core.common.SpringUtils;\n") |
| | | .append("import ").append(SYSTEM_MODEL.contains(column.getForeignKey())?systemPackagePath:packagePath).append(".service.").append(column.getForeignKey()).append("Service;\n") |
| | | .append("import ").append(SYSTEM_MODEL.contains(column.getForeignKey())?systemPackagePath:packagePath).append(".entity.").append(column.getForeignKey()).append(";\n"); |
| | | } |
| | | |
| | | // 命名转换注解 |
| | | if (!column.getName().equals(column.getHumpName())){ |
| | | if (setTableField){ |
| | | entityIm.append("import com.baomidou.mybatisplus.annotations.TableField;").append("\n"); |
| | | setTableField = false; |
| | | } |
| | | sb.append(" ") |
| | | .append("@TableField(\"") |
| | | .append(column.getName()) |
| | | .append("\")") |
| | | .append("\n"); |
| | | } |
| | | |
| | | if ("Date".equals(column.getType())){ |
| | | if (setDateTimeFormat){ |
| | | entityIm.append("import org.springframework.format.annotation.DateTimeFormat;").append("\n"); |
| | | setDateTimeFormat = false; |
| | | } |
| | | sb.append(" ") |
| | | .append("@DateTimeFormat(pattern=\"yyyy-MM-dd HH:mm:ss\")") |
| | | .append("\n"); |
| | | } |
| | | |
| | | sb.append(" ") |
| | | .append("private ") |
| | | .append(column.getType()) |
| | | .append(" ") |
| | | .append(column.getHumpName()) |
| | | .append(";") |
| | | .append("\n") |
| | | .append("\n"); |
| | | } |
| | | |
| | | // default constructor |
| | | sb.append(" public ").append(fullEntityName).append("() {}\n\n"); |
| | | // full constructor |
| | | sb.append(" public ").append(fullEntityName).append("("); |
| | | for (Column column : columns){ |
| | | if (column.isOnly()){ continue;} |
| | | sb.append(column.getType()).append(" ").append(column.getHumpName()).append(","); |
| | | } |
| | | sb.deleteCharAt(sb.length()-1); |
| | | sb.append(") {\n"); |
| | | for (Column column : columns){ |
| | | if (column.isPrimaryKey()){ continue;} |
| | | sb.append(" this.").append(column.getHumpName()).append(" = ").append(column.getHumpName()).append(";\n"); |
| | | } |
| | | sb.append(" }\n\n"); |
| | | // constructor tips |
| | | sb.append("// ").append(fullEntityName).append(" ").append(simpleEntityName).append(" = new ").append(fullEntityName).append("(\n"); |
| | | for (int i = 0; i<columns.size(); i++) { |
| | | if (columns.get(i).isOnly()){ continue;} |
| | | sb.append("// null"); |
| | | if (i < columns.size()-1){ |
| | | sb.append(","); |
| | | } |
| | | sb.append(" // ").append(columns.get(i).getComment()).append(columns.get(i).isNotNull()?"[非空]":""); |
| | | if (i < columns.size()-1){ |
| | | sb.append("\n"); |
| | | } |
| | | } |
| | | sb.append("\n// );\n\n"); |
| | | |
| | | // get set |
| | | for (Column column : columns){ |
| | | // 时间字段增加$格式化 |
| | | if ("Date".equals(column.getType())){ |
| | | sb.append(" public String get") |
| | | .append(column.getHumpName().substring(0, 1).toUpperCase()).append(column.getHumpName().substring(1)) |
| | | .append("\\$") |
| | | .append("(){\n") |
| | | .append(" if (Cools.isEmpty(this.").append(column.getHumpName()).append(")){\n") |
| | | .append(" return \"\";\n") |
| | | .append(" }\n") |
| | | .append(" return new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\").format(this.") |
| | | .append(column.getHumpName()) |
| | | .append(");\n") |
| | | .append(" }\n\n"); |
| | | // 枚举字段增加$格式化 |
| | | } else if (!Cools.isEmpty(column.getEnums())){ |
| | | sb.append(" public String get") |
| | | .append(column.getHumpName().substring(0, 1).toUpperCase()).append(column.getHumpName().substring(1)) |
| | | .append("\\$") |
| | | .append("(){\n") |
| | | .append(" if (null == this.").append(column.getHumpName()).append("){ return null; }\n") |
| | | .append(" switch (this.").append(column.getHumpName()).append("){\n"); |
| | | for (Map<String, Object> map : column.getEnums()){ |
| | | for (Map.Entry<String, Object> entry : map.entrySet()){ |
| | | sb.append(" case ").append(entry.getKey()).append(":\n") |
| | | .append(" return \"").append(entry.getValue()).append("\";\n"); |
| | | } |
| | | } |
| | | sb.append(" default:\n") |
| | | .append(" return String.valueOf(this.").append(column.getHumpName()).append(");\n") |
| | | .append(" }\n") |
| | | .append(" }\n\n"); |
| | | } |
| | | |
| | | // 外键修饰 |
| | | if (!Cools.isEmpty(column.getForeignKeyMajor())){ |
| | | sb.append(" public String get").append(column.getHumpName().substring(0, 1).toUpperCase()).append(column.getHumpName().substring(1)).append("\\$").append("(){\n") |
| | | .append(" ").append(column.getForeignKey()).append("Service service = SpringUtils.getBean(").append(column.getForeignKey()).append("Service.class);\n") |
| | | .append(" ").append(column.getForeignKey()).append(" ").append(GeneratorUtils.firstCharConvert(column.getForeignKey())) |
| | | .append(" = service.selectById(this.").append(column.getHumpName()).append(");\n") |
| | | .append(" if (!Cools.isEmpty(").append(GeneratorUtils.firstCharConvert(column.getForeignKey())).append(")){\n") |
| | | .append(" return String.valueOf(").append(GeneratorUtils.firstCharConvert(column.getForeignKey())).append(".get").append(column.getForeignKeyMajor()).append("());\n") |
| | | .append(" }\n") |
| | | .append(" return null;\n") |
| | | .append(" }\n\n"); |
| | | } |
| | | |
| | | } |
| | | entityImport = entityIm.toString(); |
| | | return sb.toString(); |
| | | } |
| | | |
| | | /**********************************************************************************************/ |
| | | /*********************************** Controller动态字段 *****************************************/ |
| | | /**********************************************************************************************/ |
| | | |
| | | private String createPrimaryMsg(){ |
| | | String defaultMajor = "id"; |
| | | boolean havePrimary = false; |
| | | for (Column column: columns){ |
| | | if (column.isPrimaryKey()){ |
| | | defaultMajor = column.getHumpName(); |
| | | havePrimary = true; |
| | | } |
| | | } |
| | | if (!havePrimary) { |
| | | for (Column column: columns){ |
| | | if (column.isMainKey()){ |
| | | defaultMajor = column.getHumpName(); |
| | | } |
| | | } |
| | | } |
| | | return defaultMajor; |
| | | } |
| | | |
| | | private String createMajorMsg(){ |
| | | String defaultMajor = "id"; |
| | | for (Column column: columns){ |
| | | if (column.isPrimaryKey()){ |
| | | defaultMajor = column.getHumpName(); |
| | | } |
| | | if (column.isMajor()){ |
| | | return column.getHumpName(); |
| | | } |
| | | } |
| | | return defaultMajor; |
| | | } |
| | | |
| | | /**********************************************************************************************/ |
| | | /*************************************** Xml动态字段 ********************************************/ |
| | | /**********************************************************************************************/ |
| | | |
| | | private String createXmlMsg(){ |
| | | StringBuilder sb = new StringBuilder(); |
| | | for (Column column : columns){ |
| | | sb.append(" ") |
| | | .append("<") |
| | | .append(column.isOnly()?"id":"result") |
| | | .append(" column=\"") |
| | | .append(column.getName()) |
| | | .append("\" property=\"") |
| | | .append(column.getHumpName()) |
| | | .append("\" />\n"); |
| | | } |
| | | return sb.toString(); |
| | | } |
| | | |
| | | /**********************************************************************************************/ |
| | | /************************************** Html动态字段 *******************************************/ |
| | | /**********************************************************************************************/ |
| | | |
| | | private String createHtmlMsg(){ |
| | | StringBuilder sb = new StringBuilder(); |
| | | for (Column column : columns){ |
| | | if (column.isPrimaryKey()){ continue;} |
| | | if (!Cools.isEmpty(column.getForeignKeyMajor())){ |
| | | sb.append(" <div class=\"layui-inline\">\n") |
| | | .append(" <div class=\"layui-input-inline cool-auto-complete\">\n") |
| | | .append(" <input id=\"").append(column.getHumpName()).append("\"") |
| | | .append(" class=\"layui-input\" name=\"").append(column.getName()).append("\" type=\"text\" placeholder=\"请输入\" autocomplete=\"off\" style=\"display: none\">\n") |
| | | .append(" <input id=\"").append(column.getHumpName()).append("\\$") |
| | | .append("\" class=\"layui-input cool-auto-complete-div\" onclick=\"autoShow(this.id)\" type=\"text\" placeholder=\"").append(GeneratorUtils.supportHtmlName(column.getComment())).append("\" onfocus=this.blur()>\n") |
| | | .append(" <div class=\"cool-auto-complete-window\">\n") |
| | | .append(" <input class=\"cool-auto-complete-window-input\" data-key=\"").append(GeneratorUtils.firstCharConvert(column.getForeignKey())).append("Query").append("By").append(column.getHumpName()).append("\" onkeyup=\"autoLoad(this.getAttribute('data-key'))\">\n") |
| | | .append(" <select class=\"cool-auto-complete-window-select\" data-key=\"").append(GeneratorUtils.firstCharConvert(column.getForeignKey())).append("Query").append("By").append(column.getHumpName()).append("Select\" onchange=\"confirmed(this.getAttribute('data-key'))\" multiple=\"multiple\">\n") |
| | | .append(" </select>\n") |
| | | .append(" </div>\n") |
| | | .append(" </div>\n") |
| | | .append(" </div>\n"); |
| | | } |
| | | } |
| | | return sb.toString(); |
| | | } |
| | | |
| | | private String createHtmlDialogMsg() { |
| | | StringBuilder sb = new StringBuilder(); |
| | | for (Column column : columns){ |
| | | if (column.isPrimaryKey()) { |
| | | continue; |
| | | } |
| | | sb.append(" <div class=\"layui-form-item\">\n"); |
| | | sb.append(" <label class=\"layui-form-label"); |
| | | if (column.isNotNull()){ |
| | | sb.append(" layui-form-required"); |
| | | } |
| | | sb.append("\">").append(column.getComment()).append(": </label>\n"); |
| | | sb.append(" <div class=\"layui-input-block"); |
| | | // 关联外键 |
| | | if (!Cools.isEmpty(column.getForeignKeyMajor())){ |
| | | sb.append(" cool-auto-complete"); |
| | | } |
| | | sb.append("\">\n"); |
| | | // 输入框类型 |
| | | if (Cools.isEmpty(column.getEnums())){ |
| | | sb.append(" <input class=\"layui-input\" name=\"").append(column.getHumpName()); |
| | | if ("Date".equals(column.getType())){ |
| | | sb.append("\" id=\"").append(column.getHumpName()).append("\\$"); |
| | | } |
| | | sb.append("\" placeholder=\"请输入").append(column.getComment()).append("\""); |
| | | if (column.isNotNull()){ |
| | | sb.append(" lay-vertype=\"tips\" lay-verify=\"required\""); |
| | | } |
| | | // 关联外键 |
| | | if (!Cools.isEmpty(column.getForeignKeyMajor())){ |
| | | sb.append(" style=\"display: none\""); |
| | | } |
| | | sb.append(">\n"); |
| | | |
| | | // 关联外键 |
| | | if (!Cools.isEmpty(column.getForeignKeyMajor())){ |
| | | sb.append(" <input id=\"").append(column.getHumpName()).append("\\$").append("\" name=\"").append(column.getHumpName()).append("\\$") |
| | | .append("\" class=\"layui-input cool-auto-complete-div\" onclick=\"autoShow(this.id)\" type=\"text\" placeholder=\"请输入").append(column.getComment()).append("\" onfocus=this.blur()>\n"); |
| | | sb.append(" <div class=\"cool-auto-complete-window\">\n") |
| | | .append(" <input class=\"cool-auto-complete-window-input\" data-key=\"") |
| | | .append(GeneratorUtils.firstCharConvert(column.getForeignKey())).append("Query").append("By").append(column.getHumpName()).append("\" onkeyup=\"autoLoad(this.getAttribute('data-key'))\">\n") |
| | | .append(" <select class=\"cool-auto-complete-window-select\" data-key=\"").append(GeneratorUtils.firstCharConvert(column.getForeignKey())).append("Query").append("By").append(column.getHumpName()).append("Select\" onchange=\"confirmed(this.getAttribute('data-key'))\" multiple=\"multiple\">\n") |
| | | .append(" </select>\n") |
| | | .append(" </div>\n"); |
| | | } |
| | | // 枚举类型 |
| | | } else { |
| | | sb.append(" <select name=\"").append(column.getHumpName()).append("\""); |
| | | if (column.isNotNull()){ |
| | | sb.append(" lay-vertype=\"tips\" lay-verify=\"required\""); |
| | | } |
| | | sb.append(">\n"); |
| | | sb.append(" <option value=\"\">").append("请选择").append(column.getComment()).append("</option>\n"); |
| | | for (Map<String, Object> map : column.getEnums()){ |
| | | for (Map.Entry<String, Object> entry : map.entrySet()){ |
| | | sb.append(" <option value=\"") |
| | | .append(entry.getKey()) |
| | | .append("\">") |
| | | .append(entry.getValue()) |
| | | .append("</option>\n"); |
| | | } |
| | | } |
| | | sb.append(" </select>\n"); |
| | | } |
| | | |
| | | sb.append(" </div>\n"); |
| | | sb.append(" </div>\n"); |
| | | } |
| | | return sb.toString(); |
| | | } |
| | | |
| | | private String createJsTableMsg(){ |
| | | StringBuilder sb = new StringBuilder(); |
| | | for (Column column : columns){ |
| | | // if (column.isPrimaryKey()){ continue;} |
| | | sb.append(" ,{field: '"); |
| | | if ("Date".equals(column.getType()) || !Cools.isEmpty(column.getEnums())){ |
| | | // 时间、枚举 格式化 |
| | | sb.append(column.getHumpName()).append("\\$"); |
| | | } else { |
| | | // 主键修饰 |
| | | if (!Cools.isEmpty(column.getForeignKeyMajor())){ |
| | | sb.append(column.getHumpName()).append("\\$"); |
| | | } else { |
| | | sb.append(column.getHumpName()); |
| | | } |
| | | } |
| | | sb.append("', align: 'center',title: '").append(column.getComment()).append("'"); |
| | | // 复选框 |
| | | if (column.isCheckBox()){ |
| | | sb.append(", templet:function(row){\n") |
| | | .append(" var html = \"<input value='") |
| | | .append(column.getHumpName()).append("' type='checkbox' lay-skin='primary' lay-filter='tableCheckbox' table-index='\"+row.LAY_TABLE_INDEX+\"'\";\n") |
| | | .append(" if(row.").append(column.getHumpName()).append(" === 'Y'){html += \" checked \";}\n") |
| | | .append(" html += \">\";\n") |
| | | .append(" return html;\n") |
| | | .append(" }"); |
| | | } |
| | | sb.append("}\n"); |
| | | } |
| | | return sb.toString(); |
| | | } |
| | | |
| | | private String createJsFkContent(){ |
| | | StringBuilder sb = new StringBuilder(); |
| | | for (Column column : columns){ |
| | | // 如果有关联外健 |
| | | if (!Cools.isEmpty(column.getForeignKeyMajor())){ |
| | | sb.append(" window.load").append(column.getForeignKey()).append("Sel = function () {").append("\n") |
| | | .append(" return xmSelect.render({").append("\n") |
| | | .append(" el: '#").append(GeneratorUtils.firstCharConvert(column.getForeignKey(), true)).append("XmlSel',").append("\n") |
| | | .append(" autoRow: true,").append("\n") |
| | | .append(" filterable: true,").append("\n") |
| | | .append(" remoteSearch: true,").append("\n") |
| | | .append(" radio: true,").append("\n") |
| | | .append(" remoteMethod: function (val, cb, show) {").append("\n") |
| | | .append(" \\$.ajax({").append("\n") |
| | | .append(" url: baseUrl + \"/").append(GeneratorUtils.firstCharConvert(column.getForeignKey(), true)).append("/all/get/kv\",").append("\n") |
| | | .append(" headers: {'token': localStorage.getItem('token')},").append("\n") |
| | | .append(" data: {").append("\n") |
| | | .append(" condition: val").append("\n") |
| | | .append(" },").append("\n") |
| | | .append(" method: 'POST',").append("\n") |
| | | .append(" success: function (res) {").append("\n") |
| | | .append(" if (res.code === 200) {").append("\n") |
| | | .append(" cb(res.data)").append("\n") |
| | | .append(" } else {").append("\n") |
| | | .append(" cb([]);").append("\n") |
| | | .append(" layer.msg(res.msg, {icon: 2});").append("\n") |
| | | .append(" }").append("\n") |
| | | .append(" }").append("\n") |
| | | .append(" });").append("\n") |
| | | .append(" }").append("\n") |
| | | .append(" });").append("\n") |
| | | .append(" }").append("\n") |
| | | .append("\n"); |
| | | } |
| | | } |
| | | return sb.toString(); |
| | | } |
| | | |
| | | private String createJsDateContent(){ |
| | | StringBuilder sb = new StringBuilder(); |
| | | for (Column column : columns) { |
| | | if (column.isPrimaryKey()) { |
| | | continue; |
| | | } |
| | | if ("Date".equals(column.getType())){ |
| | | sb.append(" layDate.render({\n") |
| | | .append(" elem: '#").append(column.getHumpName()).append("\\\\\\\\\\$',\n") |
| | | .append(" type: 'datetime',\n") |
| | | .append(" value: data!==undefined?data['").append(column.getHumpName()).append("$'").append("]:null\n") |
| | | .append(" });\n"); |
| | | } |
| | | } |
| | | return sb.toString(); |
| | | } |
| | | |
| | | private String createJsPrimaryKeyMsg(){ |
| | | StringBuilder sb = new StringBuilder(); |
| | | for (Column column : columns) { |
| | | if (column.isPrimaryKey()) { |
| | | sb.append("#").append(column.getHumpName()).append(","); |
| | | } |
| | | } |
| | | if (sb.length() > 1){ |
| | | if (sb.substring(sb.length() - 1).equals(",")) { |
| | | sb.deleteCharAt(sb.length()-1); |
| | | } |
| | | } |
| | | return sb.toString(); |
| | | } |
| | | |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.generators.constant; |
| | | |
| | | public enum SqlOsType { |
| | | |
| | | MYSQL, |
| | | SQL_SERVER, |
| | | ; |
| | | |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.generators.domain; |
| | | |
| | | import com.zy.asrs.framework.common.Cools; |
| | | import com.zy.asrs.framework.generators.CoolGenerator; |
| | | import com.zy.asrs.framework.generators.constant.SqlOsType; |
| | | import com.zy.asrs.framework.generators.utils.GeneratorUtils; |
| | | |
| | | import java.sql.Connection; |
| | | import java.util.ArrayList; |
| | | import java.util.HashMap; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | import java.util.regex.Matcher; |
| | | import java.util.regex.Pattern; |
| | | |
| | | /** |
| | | * Created by vincent on 2019-06-18 |
| | | */ |
| | | public class Column { |
| | | |
| | | private String name; // 表字段名 |
| | | private String type; // 类型 |
| | | private String comment; // 备注 |
| | | private String humpName; // 小驼峰 |
| | | private boolean primaryKey; // 唯一主键 |
| | | private boolean mainKey; // 普通主键 |
| | | private boolean notNull; // 非空 |
| | | private boolean major; // 主要 |
| | | private boolean image; // 图片 |
| | | private boolean checkBox; // 复选框 |
| | | private String foreignKey; // 外健实例名(大驼峰,如sys_user ==> User) |
| | | private String foreignKeyMajor; // 外键(小驼峰) |
| | | private List<Map<String, Object>> enums; // 枚举值 |
| | | private Integer length; // 字段长度 |
| | | |
| | | public Column(Connection conn, String name, String type, String comment, boolean primaryKey, boolean mainKey, boolean notNull, Integer length, boolean init, SqlOsType sqlOsType) { |
| | | this.name = name; |
| | | this.type = type; |
| | | this.comment = ""; |
| | | if (!Cools.isEmpty(comment)){ |
| | | // 枚举 |
| | | Pattern pattern1 = Pattern.compile("(.+?)(?=\\{)"); |
| | | Matcher matcher1 = pattern1.matcher(comment); |
| | | // 外键 |
| | | Pattern pattern11 = Pattern.compile("(.+?)(?=\\[)"); |
| | | Matcher matcher11 = pattern11.matcher(comment); |
| | | // 枚举 |
| | | if (matcher1.find()) { |
| | | this.comment = matcher1.group(); |
| | | Pattern pattern2 = Pattern.compile("(?<=\\{)(.+?)(?=})"); |
| | | Matcher matcher2 = pattern2.matcher(comment); |
| | | if (matcher2.find()) { |
| | | String group = matcher2.group(); |
| | | if (!Cools.isEmpty(group)) { |
| | | String[] values = group.split(","); |
| | | this.enums = new ArrayList<>(); |
| | | for (String val : values) { |
| | | Map<String, Object> map = new HashMap<>(); |
| | | String[] split = val.split(":"); |
| | | map.put(split[0], split[1]); |
| | | enums.add(map); |
| | | } |
| | | } |
| | | } |
| | | // 外键 |
| | | } else if (matcher11.find()){ |
| | | this.comment = matcher11.group(); |
| | | Pattern pattern22 = Pattern.compile("(?<=\\[)(.+?)(?=])"); |
| | | Matcher matcher22 = pattern22.matcher(comment); |
| | | if (matcher22.find()) { |
| | | String group = matcher22.group(); |
| | | if (!Cools.isEmpty(group)) { |
| | | this.foreignKey = GeneratorUtils.getNameSpace(group); |
| | | List<Column> foreignColumns = new ArrayList<>(); |
| | | if (init) { |
| | | try { |
| | | switch (sqlOsType) { |
| | | case MYSQL: |
| | | foreignColumns = CoolGenerator.getMysqlColumns(conn, group, false, sqlOsType); |
| | | break; |
| | | case SQL_SERVER: |
| | | foreignColumns = CoolGenerator.getSqlServerColumns(conn, group, false, sqlOsType); |
| | | break; |
| | | default: |
| | | break; |
| | | } |
| | | |
| | | } catch (Exception e){ |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | | if (!Cools.isEmpty(foreignColumns)){ |
| | | for (Column column : foreignColumns){ |
| | | if (column.isMajor()){ |
| | | this.foreignKeyMajor = GeneratorUtils.firstCharConvert(column.getHumpName(), false); |
| | | } |
| | | } |
| | | if (Cools.isEmpty(this.foreignKeyMajor)){ |
| | | this.foreignKeyMajor = "Id"; |
| | | } |
| | | } |
| | | } |
| | | } |
| | | } else { |
| | | this.comment = comment; |
| | | } |
| | | // 主要字段 |
| | | if (comment.endsWith("(*)")){ |
| | | this.comment = comment.substring(0, comment.length()-3); |
| | | this.major = true; |
| | | } |
| | | // 图片字段 |
| | | if (comment.endsWith("(img)")){ |
| | | this.comment = comment.substring(0, comment.length()-5); |
| | | this.image = true; |
| | | } |
| | | // 复选框 |
| | | if (comment.endsWith("(checkbox)")){ |
| | | this.comment = comment.substring(0, comment.length()-10); |
| | | this.checkBox = true; |
| | | } |
| | | } |
| | | // if (primaryKey || mainKey){ |
| | | // this.primaryKey = true; |
| | | // } else { |
| | | // this.primaryKey = false; |
| | | // } |
| | | this.primaryKey = primaryKey; |
| | | this.mainKey = mainKey; |
| | | this.notNull = notNull; |
| | | this.length = length; |
| | | this.humpName = GeneratorUtils._convert(name); |
| | | } |
| | | |
| | | public String getName() { |
| | | return name; |
| | | } |
| | | |
| | | public void setName(final String name) { |
| | | this.name = name; |
| | | } |
| | | |
| | | public String getType() { |
| | | return type; |
| | | } |
| | | |
| | | public void setType(final String type) { |
| | | this.type = type; |
| | | } |
| | | |
| | | public String getComment() { |
| | | return comment; |
| | | } |
| | | |
| | | public String getWholeComment() { |
| | | if (!Cools.isEmpty(this.enums)){ |
| | | StringBuilder sb = new StringBuilder(" "); |
| | | for (Map<String, Object> val : enums){ |
| | | for (Map.Entry<String, Object> entry : val.entrySet()){ |
| | | sb.append(entry.getKey()) |
| | | .append(": ") |
| | | .append(entry.getValue()) |
| | | .append(" "); |
| | | } |
| | | } |
| | | return comment + sb.toString(); |
| | | } |
| | | return comment; |
| | | } |
| | | |
| | | public void setComment(final String comment) { |
| | | this.comment = comment; |
| | | } |
| | | |
| | | public String getHumpName() { |
| | | return humpName; |
| | | } |
| | | |
| | | // public boolean isPrimaryKey() { |
| | | // return primaryKey || mainKey; |
| | | // } |
| | | |
| | | public boolean isPrimaryKey() { |
| | | return primaryKey; |
| | | } |
| | | |
| | | public boolean isOnly(){ |
| | | return primaryKey; |
| | | } |
| | | |
| | | public void setPrimaryKey(boolean primaryKey) { |
| | | this.primaryKey = primaryKey; |
| | | } |
| | | |
| | | public boolean isNotNull() { |
| | | return notNull; |
| | | } |
| | | |
| | | public void setNotNull(final boolean notNull) { |
| | | this.notNull = notNull; |
| | | } |
| | | |
| | | public String getForeignKey() { |
| | | return foreignKey; |
| | | } |
| | | |
| | | public void setForeignKey(final String foreignKey) { |
| | | this.foreignKey = foreignKey; |
| | | } |
| | | |
| | | public String getForeignKeyMajor() { |
| | | return foreignKeyMajor; |
| | | } |
| | | |
| | | public void setForeignKeyMajor(final String foreignKeyMajor) { |
| | | this.foreignKeyMajor = foreignKeyMajor; |
| | | } |
| | | |
| | | public List<Map<String, Object>> getEnums() { |
| | | return enums; |
| | | } |
| | | |
| | | public void setEnums(List<Map<String, Object>> enums) { |
| | | this.enums = enums; |
| | | } |
| | | |
| | | public Integer getLength() { |
| | | return length; |
| | | } |
| | | |
| | | public void setLength(final Integer length) { |
| | | this.length = length; |
| | | } |
| | | |
| | | public boolean isMajor() { |
| | | return major; |
| | | } |
| | | |
| | | public void setMajor(final boolean major) { |
| | | this.major = major; |
| | | } |
| | | |
| | | public boolean isImage() { |
| | | return image; |
| | | } |
| | | |
| | | public void setImage(final boolean image) { |
| | | this.image = image; |
| | | } |
| | | |
| | | public boolean isCheckBox() { |
| | | return checkBox; |
| | | } |
| | | |
| | | public void setCheckBox(boolean checkBox) { |
| | | this.checkBox = checkBox; |
| | | } |
| | | |
| | | public boolean isMainKey() { |
| | | return mainKey; |
| | | } |
| | | |
| | | public void setMainKey(boolean mainKey) { |
| | | this.mainKey = mainKey; |
| | | } |
| | | |
| | | @Override |
| | | public String toString() { |
| | | return "Column{" + |
| | | "name='" + name + '\'' + |
| | | ", type='" + type + '\'' + |
| | | ", comment='" + comment + '\'' + |
| | | ", humpName='" + humpName + '\'' + |
| | | ", primaryKey=" + primaryKey + |
| | | ", notNull=" + notNull + |
| | | ", major=" + major + |
| | | ", image=" + image + |
| | | ", foreignKey='" + foreignKey + '\'' + |
| | | ", foreignKeyMajor='" + foreignKeyMajor + '\'' + |
| | | ", enums=" + enums + |
| | | ", length=" + length + |
| | | '}'; |
| | | } |
| | | |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.generators.utils; |
| | | |
| | | import com.core.common.Cools; |
| | | |
| | | import java.util.regex.Matcher; |
| | | import java.util.regex.Pattern; |
| | | |
| | | import static java.sql.Types.*; |
| | | |
| | | /** |
| | | * Created by vincent on 2019-06-18 |
| | | */ |
| | | public class GeneratorUtils { |
| | | |
| | | /** |
| | | * 下划线 ===>> 驼峰命名 |
| | | * @param smallHump 小驼峰命名 |
| | | */ |
| | | public static String _convert(String str, boolean smallHump){ |
| | | String[] split = str.split("_"); |
| | | StringBuilder sb = new StringBuilder(); |
| | | for (int i=0;i<split.length;i++){ |
| | | sb.append(i==0&&smallHump?split[i]:split[i].substring(0, 1).toUpperCase()+split[i].substring(1)); |
| | | } |
| | | return sb.toString(); |
| | | } |
| | | |
| | | public static String _convert(String str){ |
| | | return _convert(str, true); |
| | | } |
| | | |
| | | // sql类型 ===>> java类型 |
| | | public static String getType(int type){ |
| | | switch (type){ |
| | | case BIT: |
| | | return "Boolean"; |
| | | case TINYINT: |
| | | return "Short"; |
| | | case SMALLINT: |
| | | return "Short"; |
| | | case INTEGER: |
| | | return "Integer"; |
| | | case BIGINT: |
| | | return "Long"; |
| | | case DOUBLE: |
| | | return "Double"; |
| | | case DECIMAL: |
| | | return "Double"; |
| | | case NCHAR: |
| | | return "String"; |
| | | case NVARCHAR: |
| | | return "String"; |
| | | case CHAR: |
| | | return "String"; |
| | | case VARCHAR: |
| | | return "String"; |
| | | case DATE: |
| | | return "Date"; |
| | | case TIMESTAMP: |
| | | return "Date"; |
| | | case BLOB: |
| | | return "String"; |
| | | case LONGVARCHAR: |
| | | return "String"; |
| | | default: |
| | | return null; |
| | | } |
| | | } |
| | | |
| | | // sql表名 ===>> 去前缀 大驼峰 |
| | | public static String getNameSpace(String tableName){ |
| | | String[] strings = tableName.split("_"); |
| | | StringBuilder sb = new StringBuilder(); |
| | | for (int i=1;i<strings.length;i++){ |
| | | if (i!=1){ |
| | | sb.append("_"); |
| | | } |
| | | sb.append(strings[i]); |
| | | } |
| | | return _convert(sb.toString(), false); |
| | | } |
| | | |
| | | // htmlDetail 字符适配 |
| | | public static String supportHtmlName(String comment){ |
| | | if (Cools.isEmpty(comment)){ |
| | | return ""; |
| | | } |
| | | if (comment.length() == 2){ |
| | | return comment.charAt(0) + " " + comment.charAt(1); |
| | | } else if (comment.length() == 3){ |
| | | return comment.charAt(0) + " " + comment.charAt(1) + " " +comment.charAt(2); |
| | | } |
| | | return comment; |
| | | } |
| | | |
| | | /** |
| | | * 获取mysql表字段长度 |
| | | */ |
| | | public static Integer getColumnLength(String typeMsg){ |
| | | if (Cools.isEmpty(typeMsg)){ |
| | | return null; |
| | | } |
| | | Pattern pattern = Pattern.compile("(?<=\\()(.+?)(?=\\))"); |
| | | Matcher matcher = pattern.matcher(typeMsg); |
| | | if (matcher.find()){ |
| | | String group = matcher.group(); |
| | | if (group.contains(",")) { |
| | | group = group.split(",")[0]; |
| | | } |
| | | return Integer.parseInt(group); |
| | | } |
| | | return null; |
| | | } |
| | | |
| | | /** |
| | | * 字符串首字母大小写转换 |
| | | * @param str 字符串 |
| | | * @param low true:小写 / false:大写 |
| | | * @return the result |
| | | */ |
| | | public static String firstCharConvert(String str, boolean low){ |
| | | if (Cools.isEmpty(str)){ |
| | | return ""; |
| | | } |
| | | String firstChar = str.substring(0, 1); |
| | | if (low){ |
| | | firstChar = firstChar.toLowerCase(); |
| | | } else { |
| | | firstChar = firstChar.toUpperCase(); |
| | | } |
| | | return firstChar + str.substring(1); |
| | | } |
| | | |
| | | public static String firstCharConvert(String str){ |
| | | return firstCharConvert(str, true); |
| | | } |
| | | |
| | | /** 驼峰转下划线 */ |
| | | public static String humpToLine(String str) { |
| | | Matcher matcher = Pattern.compile("[A-Z]").matcher(str); |
| | | StringBuffer sb = new StringBuffer(); |
| | | while (matcher.find()) { |
| | | matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase()); |
| | | } |
| | | matcher.appendTail(sb); |
| | | return sb.toString(); |
| | | } |
| | | |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.utils; |
| | | |
| | | /** |
| | | * 算法 |
| | | * Created by vincent on 2023/3/8 |
| | | */ |
| | | public class Algorithm { |
| | | |
| | | /** |
| | | * |
| | | * Floyd 弗洛伊德算法 |
| | | * |
| | | * x | 1 | 2 | 3 | 4 |
| | | * 1 | 0 | 3 | 4 | 2 |
| | | * 2 | 3 | 0 | 0 | 0 |
| | | * 3 | 4 | 0 | 0 | 3 |
| | | * 4 | 2 | 0 | 3 | 0 |
| | | */ |
| | | |
| | | |
| | | |
| | | } |
New file |
| | |
| | | package com.zy.asrs.framework.utils; |
| | | |
| | | import com.core.common.Cools; |
| | | |
| | | import java.util.ArrayList; |
| | | import java.util.Arrays; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | |
| | | import static javax.xml.bind.JAXBIntrospector.getValue; |
| | | |
| | | /** |
| | | * Created by vincent on 2020-01-06 |
| | | */ |
| | | public class SignUtils { |
| | | |
| | | /** |
| | | * 生成签名 |
| | | * (规则如下: |
| | | * 第一步: |
| | | * 设所有发送或者接收到的数据为集合M, |
| | | * 将集合M内非空参数值的参数按照参数名ASCII码从小到大排序(字典序), |
| | | * 使用URL键值对的格式(即key1=value1&key2=value2…)拼接成字符串stringA |
| | | * |
| | | * 第二步: |
| | | * 在stringA最后拼接上key得到stringSignTemp字符串, |
| | | * 并对stringSignTemp进行MD5运算,再将得到的字符串所有字符转换为大写, |
| | | * 得到sign值signValue |
| | | * ) |
| | | * @param map 参数集合 |
| | | * @param secret 密钥 |
| | | * @return the sign 签名 |
| | | */ |
| | | public static String sign(Map<String, Object> map, String secret) { |
| | | List<String> list = new ArrayList<>(); |
| | | for (String key : map.keySet()) { |
| | | if (!key.equals("sign") && map.get(key) != null) { |
| | | list.add(key + "=" + getValue(key) + "&"); |
| | | } |
| | | } |
| | | int size = list.size(); |
| | | String[] arrayToSort = list.toArray(new String[size]); |
| | | Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER); |
| | | StringBuilder sb = new StringBuilder(); |
| | | for (int i = 0; i < size; i++) { |
| | | sb.append(arrayToSort[i]); |
| | | } |
| | | String stringA = sb.toString(); |
| | | stringA += "key=" + secret; |
| | | return Cools.md5(stringA).toUpperCase(); |
| | | } |
| | | |
| | | } |
New file |
| | |
| | | org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.core.config.CoolBaseConfig |
New file |
| | |
| | | package @{COMPANYNAME}.controller; |
| | | |
| | | import com.alibaba.fastjson.JSONArray; |
| | | import com.alibaba.fastjson.JSONObject; |
| | | import com.baomidou.mybatisplus.mapper.EntityWrapper; |
| | | import com.baomidou.mybatisplus.mapper.Wrapper; |
| | | import com.baomidou.mybatisplus.plugins.Page; |
| | | import com.core.common.DateUtils; |
| | | import @{COMPANYNAME}.entity.@{ENTITYNAME}; |
| | | import @{COMPANYNAME}.service.@{ENTITYNAME}Service; |
| | | import com.core.annotations.ManagerAuth; |
| | | import com.core.common.BaseRes; |
| | | import com.core.common.Cools; |
| | | import com.core.common.R; |
| | | import com.core.domain.KeyValueVo; |
| | | import @{SYSTEMPACKAGE}.common.web.BaseController; |
| | | import org.springframework.beans.factory.annotation.Autowired; |
| | | import org.springframework.web.bind.annotation.*; |
| | | |
| | | import java.util.*; |
| | | |
| | | @RestController |
| | | public class @{ENTITYNAME}Controller extends BaseController { |
| | | |
| | | @Autowired |
| | | private @{ENTITYNAME}Service @{SIMPLEENTITYNAME}Service; |
| | | |
| | | @RequestMapping(value = "/@{SIMPLEENTITYNAME}/{id}/auth") |
| | | @ManagerAuth |
| | | public R get(@PathVariable("id") String id) { |
| | | return R.ok(@{SIMPLEENTITYNAME}Service.selectById(String.valueOf(id))); |
| | | } |
| | | |
| | | @RequestMapping(value = "/@{SIMPLEENTITYNAME}/page/auth") |
| | | @ManagerAuth |
| | | public R page(@RequestParam(defaultValue = "1")Integer curr, |
| | | @RequestParam(defaultValue = "10")Integer limit, |
| | | @RequestParam(required = false)String orderByField, |
| | | @RequestParam(required = false)String orderByType, |
| | | @RequestParam(required = false)String condition, |
| | | @RequestParam Map<String, Object> param){ |
| | | EntityWrapper<@{ENTITYNAME}> wrapper = new EntityWrapper<>(); |
| | | excludeTrash(param); |
| | | convert(param, wrapper); |
| | | allLike(@{ENTITYNAME}.class, param.keySet(), wrapper, condition); |
| | | if (!Cools.isEmpty(orderByField)){wrapper.orderBy(humpToLine(orderByField), "asc".equals(orderByType));} |
| | | return R.ok(@{SIMPLEENTITYNAME}Service.selectPage(new Page<>(curr, limit), wrapper)); |
| | | } |
| | | |
| | | private <T> void convert(Map<String, Object> map, EntityWrapper<T> wrapper){ |
| | | for (Map.Entry<String, Object> entry : map.entrySet()){ |
| | | String val = String.valueOf(entry.getValue()); |
| | | if (val.contains(RANGE_TIME_LINK)){ |
| | | String[] dates = val.split(RANGE_TIME_LINK); |
| | | wrapper.ge(entry.getKey(), DateUtils.convert(dates[0])); |
| | | wrapper.le(entry.getKey(), DateUtils.convert(dates[1])); |
| | | } else { |
| | | wrapper.like(entry.getKey(), val); |
| | | } |
| | | } |
| | | } |
| | | |
| | | @RequestMapping(value = "/@{SIMPLEENTITYNAME}/add/auth") |
| | | @ManagerAuth |
| | | public R add(@{ENTITYNAME} @{SIMPLEENTITYNAME}) { |
| | | @{SIMPLEENTITYNAME}Service.insert(@{SIMPLEENTITYNAME}); |
| | | return R.ok(); |
| | | } |
| | | |
| | | @RequestMapping(value = "/@{SIMPLEENTITYNAME}/update/auth") |
| | | @ManagerAuth |
| | | public R update(@{ENTITYNAME} @{SIMPLEENTITYNAME}){ |
| | | if (Cools.isEmpty(@{SIMPLEENTITYNAME}) || null==@{SIMPLEENTITYNAME}.get@{PRIMARYKEYCOLUMN}()){ |
| | | return R.error(); |
| | | } |
| | | @{SIMPLEENTITYNAME}Service.updateById(@{SIMPLEENTITYNAME}); |
| | | return R.ok(); |
| | | } |
| | | |
| | | @RequestMapping(value = "/@{SIMPLEENTITYNAME}/delete/auth") |
| | | @ManagerAuth |
| | | public R delete(@RequestParam(value="ids[]") Long[] ids){ |
| | | for (Long id : ids){ |
| | | @{SIMPLEENTITYNAME}Service.deleteById(id); |
| | | } |
| | | return R.ok(); |
| | | } |
| | | |
| | | @RequestMapping(value = "/@{SIMPLEENTITYNAME}/export/auth") |
| | | @ManagerAuth |
| | | public R export(@RequestBody JSONObject param){ |
| | | EntityWrapper<@{ENTITYNAME}> wrapper = new EntityWrapper<>(); |
| | | List<String> fields = JSONObject.parseArray(param.getJSONArray("fields").toJSONString(), String.class); |
| | | Map<String, Object> map = excludeTrash(param.getJSONObject("@{SIMPLEENTITYNAME}")); |
| | | convert(map, wrapper); |
| | | List<@{ENTITYNAME}> list = @{SIMPLEENTITYNAME}Service.selectList(wrapper); |
| | | return R.ok(exportSupport(list, fields)); |
| | | } |
| | | |
| | | @RequestMapping(value = "/@{SIMPLEENTITYNAME}Query/auth") |
| | | @ManagerAuth |
| | | public R query(String condition) { |
| | | EntityWrapper<@{ENTITYNAME}> wrapper = new EntityWrapper<>(); |
| | | wrapper.like("@{MAJORCOLUMN}", condition); |
| | | Page<@{ENTITYNAME}> page = @{SIMPLEENTITYNAME}Service.selectPage(new Page<>(0, 10), wrapper); |
| | | List<Map<String, Object>> result = new ArrayList<>(); |
| | | for (@{ENTITYNAME} @{SIMPLEENTITYNAME} : page.getRecords()){ |
| | | Map<String, Object> map = new HashMap<>(); |
| | | map.put("id", @{SIMPLEENTITYNAME}.get@{PRIMARYKEYCOLUMN}()); |
| | | map.put("value", @{SIMPLEENTITYNAME}.get@{MAJORCOLUMN_UP}()); |
| | | result.add(map); |
| | | } |
| | | return R.ok(result); |
| | | } |
| | | |
| | | @RequestMapping(value = "/@{SIMPLEENTITYNAME}/check/column/auth") |
| | | @ManagerAuth |
| | | public R query(@RequestBody JSONObject param) { |
| | | Wrapper<@{ENTITYNAME}> wrapper = new EntityWrapper<@{ENTITYNAME}>().eq(humpToLine(String.valueOf(param.get("key"))), param.get("val")); |
| | | if (null != @{SIMPLEENTITYNAME}Service.selectOne(wrapper)){ |
| | | return R.parse(BaseRes.REPEAT).add(getComment(@{ENTITYNAME}.class, String.valueOf(param.get("key")))); |
| | | } |
| | | return R.ok(); |
| | | } |
| | | |
| | | @RequestMapping("/@{SIMPLEENTITYNAME}/all/get/kv") |
| | | @ManagerAuth |
| | | public R getDataKV(@RequestParam(required = false) String condition) { |
| | | List<KeyValueVo> vos = new ArrayList<>(); |
| | | Wrapper<@{ENTITYNAME}> wrapper = new EntityWrapper<@{ENTITYNAME}>().andNew().like("@{MAJORCOLUMN}", condition).orderBy("create_time", false); |
| | | @{SIMPLEENTITYNAME}Service.selectPage(new Page<>(1, 30), wrapper).getRecords().forEach(item -> vos.add(new KeyValueVo(String.valueOf(item.get@{MAJORCOLUMN_UP}()), item.get@{PRIMARYKEYCOLUMN}()))); |
| | | return R.ok().add(vos); |
| | | } |
| | | |
| | | } |
New file |
| | |
| | | package @{COMPANYNAME}.entity; |
| | | |
| | | @{ENTITYIMPORT} |
| | | import io.swagger.annotations.ApiModelProperty; |
| | | import lombok.Data; |
| | | import com.baomidou.mybatisplus.annotations.TableName; |
| | | import java.io.Serializable; |
| | | |
| | | @Data |
| | | @TableName("@{TABLENAME}") |
| | | public class @{ENTITYNAME} implements Serializable { |
| | | |
| | | private static final long serialVersionUID = 1L; |
| | | |
| | | @{ENTITYCONTENT} |
| | | } |
New file |
| | |
| | | <!DOCTYPE html> |
| | | <html lang="en"> |
| | | <head> |
| | | <meta charset="utf-8"> |
| | | <title></title> |
| | | <meta name="renderer" content="webkit"> |
| | | <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> |
| | | <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> |
| | | <link rel="stylesheet" href="../../static/layui/css/layui.css" media="all"> |
| | | <link rel="stylesheet" href="../../static/css/admin.css?v=318" media="all"> |
| | | <link rel="stylesheet" href="../../static/css/cool.css" media="all"> |
| | | </head> |
| | | <body> |
| | | |
| | | <div class="layui-fluid"> |
| | | <div class="layui-card"> |
| | | <div class="layui-card-body"> |
| | | <div class="layui-form toolbar" id="search-box"> |
| | | <div class="layui-form-item"> |
| | | <div class="layui-inline"> |
| | | <div class="layui-input-inline"> |
| | | <input class="layui-input" type="text" name="id" placeholder="编号" autocomplete="off"> |
| | | </div> |
| | | </div> |
| | | <div class="layui-inline" style="width: 300px"> |
| | | <div class="layui-input-inline"> |
| | | <input class="layui-input layui-laydate-range" name="create_time" type="text" placeholder="起始时间 - 终止时间" autocomplete="off" style="width: 300px"> |
| | | </div> |
| | | </div> |
| | | <div class="layui-inline"> |
| | | <div class="layui-input-inline"> |
| | | <input class="layui-input" type="text" name="condition" placeholder="请输入" autocomplete="off"> |
| | | </div> |
| | | </div> |
| | | <div class="layui-inline">  |
| | | <button class="layui-btn icon-btn" lay-filter="search" lay-submit> |
| | | <i class="layui-icon"></i>搜索 |
| | | </button> |
| | | <button class="layui-btn icon-btn" lay-filter="reset" lay-submit> |
| | | <i class="layui-icon"></i>重置 |
| | | </button> |
| | | </div> |
| | | </div> |
| | | </div> |
| | | <table class="layui-hide" id="@{SIMPLEENTITYNAME}" lay-filter="@{SIMPLEENTITYNAME}"></table> |
| | | </div> |
| | | </div> |
| | | </div> |
| | | |
| | | <script type="text/html" id="toolbar"> |
| | | <div class="layui-btn-container"> |
| | | <button class="layui-btn layui-btn-sm" id="btn-add" lay-event="addData">新增</button> |
| | | <button class="layui-btn layui-btn-sm layui-btn-danger" id="btn-delete" lay-event="deleteData">删除</button> |
| | | <button class="layui-btn layui-btn-primary layui-btn-sm" id="btn-export" lay-event="exportData" style="float: right">导出</button> |
| | | </div> |
| | | </script> |
| | | |
| | | <script type="text/html" id="operate"> |
| | | <a class="layui-btn layui-btn-primary layui-btn-xs btn-edit" lay-event="edit">修改</a> |
| | | <a class="layui-btn layui-btn-danger layui-btn-xs btn-edit" lay-event="del">删除</a> |
| | | </script> |
| | | |
| | | <script type="text/javascript" src="../../static/js/jquery/jquery-3.3.1.min.js"></script> |
| | | <script type="text/javascript" src="../../static/layui/layui.js" charset="utf-8"></script> |
| | | <script type="text/javascript" src="../../static/js/common.js" charset="utf-8"></script> |
| | | <script type="text/javascript" src="../../static/js/cool.js" charset="utf-8"></script> |
| | | <script type="text/javascript" src="../../static/js/@{SIMPLEENTITYNAME}/@{SIMPLEENTITYNAME}.js" charset="utf-8"></script> |
| | | </body> |
| | | <!-- 表单弹窗 --> |
| | | <script type="text/html" id="editDialog"> |
| | | <div id="detail" lay-filter="detail" class="layui-form admin-form model-form"> |
| | | <input name="id" type="hidden"> |
| | | <div class="layui-row"> |
| | | <div class="layui-col-md12"> |
| | | @{HTMLDIALOGCONTENT} |
| | | </div> |
| | | </div> |
| | | <hr class="layui-bg-gray"> |
| | | <div class="layui-form-item text-right"> |
| | | <button class="layui-btn" lay-filter="editSubmit" lay-submit="">保存</button> |
| | | <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button> |
| | | </div> |
| | | </div> |
| | | </script> |
| | | </html> |
| | | |
New file |
| | |
| | | var pageCurr; |
| | | var pageCount = 0; |
| | | layui.config({ |
| | | base: baseUrl + "/static/layui/lay/modules/" |
| | | }).use(['table','laydate', 'form', 'admin', 'xmSelect'], function(){ |
| | | var table = layui.table; |
| | | var $ = layui.jquery; |
| | | var layer = layui.layer; |
| | | var layDate = layui.laydate; |
| | | var form = layui.form; |
| | | var admin = layui.admin; |
| | | var xmSelect = layui.xmSelect; |
| | | |
| | | // 数据渲染 |
| | | tableIns = table.render({ |
| | | elem: '#@{SIMPLEENTITYNAME}', |
| | | headers: {token: localStorage.getItem('token')}, |
| | | url: baseUrl+'/@{SIMPLEENTITYNAME}/page/auth', |
| | | page: true, |
| | | limit: 15, |
| | | limits: [15, 30, 50, 100, 200, 500], |
| | | toolbar: '#toolbar', |
| | | cellMinWidth: 50, |
| | | height: 'full-120', |
| | | cols: [[ |
| | | {type: 'checkbox'} |
| | | @{JSTABLECONTENT} |
| | | ,{fixed: 'right', title:'操作', align: 'center', toolbar: '#operate', width:120} |
| | | ]], |
| | | request: { |
| | | pageName: 'curr', |
| | | pageSize: 'limit' |
| | | }, |
| | | parseData: function (res) { |
| | | return { |
| | | 'code': res.code, |
| | | 'msg': res.msg, |
| | | 'count': res.data.total, |
| | | 'data': res.data.records |
| | | } |
| | | }, |
| | | response: { |
| | | statusCode: 200 |
| | | }, |
| | | done: function(res, curr, count) { |
| | | if (res.code === 403) { |
| | | top.location.href = baseUrl+"/"; |
| | | } |
| | | pageCurr=curr;pageCount=count; |
| | | limit(); |
| | | } |
| | | }); |
| | | |
| | | // 监听排序事件 |
| | | table.on('sort(@{SIMPLEENTITYNAME})', function (obj) { |
| | | var searchData = {}; |
| | | $.each($('#search-box [name]').serializeArray(), function() { |
| | | searchData[this.name] = this.value; |
| | | }); |
| | | searchData['orderByField'] = obj.field; |
| | | searchData['orderByType'] = obj.type; |
| | | tableIns.reload({ |
| | | where: searchData, |
| | | page: {curr: 1} |
| | | }); |
| | | }); |
| | | |
| | | // 监听头工具栏事件 |
| | | table.on('toolbar(@{SIMPLEENTITYNAME})', function (obj) { |
| | | var checkStatus = table.checkStatus(obj.config.id).data; |
| | | switch(obj.event) { |
| | | case 'addData': |
| | | showEditModel(); |
| | | break; |
| | | case 'deleteData': |
| | | if (checkStatus.length === 0) { |
| | | layer.msg('请选择要删除的数据', {icon: 2}); |
| | | return; |
| | | } |
| | | del(checkStatus.map(function (d) { |
| | | return d.@{PRIMARYKEYCOLUMN0}; |
| | | })); |
| | | break; |
| | | case 'exportData': |
| | | admin.confirm('确定导出Excel吗', {shadeClose: true}, function(){ |
| | | var titles=[]; |
| | | var fields=[]; |
| | | obj.config.cols[0].map(function (col) { |
| | | if (col.type === 'normal' && col.hide === false && col.toolbar == null) { |
| | | titles.push(col.title); |
| | | fields.push(col.field); |
| | | } |
| | | }); |
| | | var exportData = {}; |
| | | $.each($('#search-box [name]').serializeArray(), function() { |
| | | exportData[this.name] = this.value; |
| | | }); |
| | | var param = { |
| | | '@{SIMPLEENTITYNAME}': exportData, |
| | | 'fields': fields |
| | | }; |
| | | $.ajax({ |
| | | url: baseUrl+"/@{SIMPLEENTITYNAME}/export/auth", |
| | | headers: {'token': localStorage.getItem('token')}, |
| | | data: JSON.stringify(param), |
| | | dataType:'json', |
| | | contentType:'application/json;charset=UTF-8', |
| | | method: 'POST', |
| | | success: function (res) { |
| | | layer.closeAll(); |
| | | if (res.code === 200) { |
| | | table.exportFile(titles,res.data,'xls'); |
| | | } else if (res.code === 403) { |
| | | top.location.href = baseUrl+"/"; |
| | | } else { |
| | | layer.msg(res.msg, {icon: 2}) |
| | | } |
| | | } |
| | | }); |
| | | }); |
| | | break; |
| | | } |
| | | }); |
| | | |
| | | // 监听行工具事件 |
| | | table.on('tool(@{SIMPLEENTITYNAME})', function(obj){ |
| | | var data = obj.data; |
| | | switch (obj.event) { |
| | | case 'edit': |
| | | showEditModel(data); |
| | | break; |
| | | case "del": |
| | | del([data.@{PRIMARYKEYCOLUMN0}]); |
| | | break; |
| | | } |
| | | }); |
| | | |
| | | /* 弹窗 - 新增、修改 */ |
| | | function showEditModel(mData) { |
| | | admin.open({ |
| | | type: 1, |
| | | area: '600px', |
| | | title: (mData ? '修改' : '添加') + '', |
| | | content: $('#editDialog').html(), |
| | | success: function (layero, dIndex) { |
| | | layDateRender(mData); |
| | | form.val('detail', mData); |
| | | form.on('submit(editSubmit)', function (data) { |
| | | var loadIndex = layer.load(2); |
| | | $.ajax({ |
| | | url: baseUrl+"/@{SIMPLEENTITYNAME}/"+(mData?'update':'add')+"/auth", |
| | | headers: {'token': localStorage.getItem('token')}, |
| | | data: data.field, |
| | | method: 'POST', |
| | | success: function (res) { |
| | | layer.close(loadIndex); |
| | | if (res.code === 200){ |
| | | layer.close(dIndex); |
| | | layer.msg(res.msg, {icon: 1}); |
| | | tableReload(); |
| | | } else if (res.code === 403){ |
| | | top.location.href = baseUrl+"/"; |
| | | }else { |
| | | layer.msg(res.msg, {icon: 2}); |
| | | } |
| | | } |
| | | }) |
| | | return false; |
| | | }); |
| | | $(layero).children('.layui-layer-content').css('overflow', 'visible'); |
| | | layui.form.render('select'); |
| | | } |
| | | }); |
| | | } |
| | | |
| | | /* 删除 */ |
| | | function del(ids) { |
| | | layer.confirm('确定要删除选中数据吗?', { |
| | | skin: 'layui-layer-admin', |
| | | shade: .1 |
| | | }, function (i) { |
| | | layer.close(i); |
| | | var loadIndex = layer.load(2); |
| | | $.ajax({ |
| | | url: baseUrl+"/@{SIMPLEENTITYNAME}/delete/auth", |
| | | headers: {'token': localStorage.getItem('token')}, |
| | | data: {ids: ids}, |
| | | method: 'POST', |
| | | success: function (res) { |
| | | layer.close(loadIndex); |
| | | if (res.code === 200){ |
| | | layer.msg(res.msg, {icon: 1}); |
| | | tableReload(); |
| | | } else if (res.code === 403){ |
| | | top.location.href = baseUrl+"/"; |
| | | } else { |
| | | layer.msg(res.msg, {icon: 2}); |
| | | } |
| | | } |
| | | }) |
| | | }); |
| | | } |
| | | |
| | | // 搜索 |
| | | form.on('submit(search)', function (data) { |
| | | pageCurr = 1; |
| | | tableReload(true); |
| | | }); |
| | | |
| | | // 重置 |
| | | form.on('submit(reset)', function (data) { |
| | | pageCurr = 1; |
| | | clearFormVal($('#search-box')); |
| | | tableReload(true); |
| | | }); |
| | | |
| | | // 时间选择器 |
| | | function layDateRender(data) { |
| | | setTimeout(function () { |
| | | layDate.render({ |
| | | elem: '.layui-laydate-range' |
| | | ,type: 'datetime' |
| | | ,range: true |
| | | }); |
| | | @{JSDATECONTENT} |
| | | }, 300); |
| | | } |
| | | layDateRender(); |
| | | |
| | | @{JSFOREIGNKEYCONTENT} |
| | | |
| | | }); |
| | | |
| | | // 关闭动作 |
| | | $(document).on('click','#data-detail-close', function () { |
| | | parent.layer.closeAll(); |
| | | }); |
| | | |
| | | function tableReload(search) { |
| | | if (pageCount === 0 || search) { |
| | | let searchData = {}; |
| | | $.each($('#search-box [name]').serializeArray(), function() { |
| | | searchData[this.name] = this.value; |
| | | }); |
| | | tableIns.reload({ |
| | | where: searchData, |
| | | page: {curr: pageCurr} |
| | | }); |
| | | } else { |
| | | $(".layui-laypage-btn")[0].click(); |
| | | } |
| | | } |
New file |
| | |
| | | package @{COMPANYNAME}.mapper; |
| | | |
| | | import @{COMPANYNAME}.entity.@{ENTITYNAME}; |
| | | import com.baomidou.mybatisplus.mapper.BaseMapper; |
| | | import org.apache.ibatis.annotations.Mapper; |
| | | import org.springframework.stereotype.Repository; |
| | | |
| | | @Mapper |
| | | @Repository |
| | | public interface @{ENTITYNAME}Mapper extends BaseMapper<@{ENTITYNAME}> { |
| | | |
| | | } |
New file |
| | |
| | | package @{COMPANYNAME}.service; |
| | | |
| | | import @{COMPANYNAME}.entity.@{ENTITYNAME}; |
| | | import com.baomidou.mybatisplus.service.IService; |
| | | |
| | | public interface @{ENTITYNAME}Service extends IService<@{ENTITYNAME}> { |
| | | |
| | | } |
New file |
| | |
| | | package @{COMPANYNAME}.service.impl; |
| | | |
| | | import @{COMPANYNAME}.mapper.@{ENTITYNAME}Mapper; |
| | | import @{COMPANYNAME}.entity.@{ENTITYNAME}; |
| | | import @{COMPANYNAME}.service.@{ENTITYNAME}Service; |
| | | import com.baomidou.mybatisplus.service.impl.ServiceImpl; |
| | | import org.springframework.stereotype.Service; |
| | | |
| | | @Service("@{SIMPLEENTITYNAME}Service") |
| | | public class @{ENTITYNAME}ServiceImpl extends ServiceImpl<@{ENTITYNAME}Mapper, @{ENTITYNAME}> implements @{ENTITYNAME}Service { |
| | | |
| | | } |
New file |
| | |
| | | -- save @{SIMPLEENTITYNAME} record |
| | | -- mysql |
| | | insert into `sys_resource` ( `code`, `name`, `resource_id`, `level`, `sort`, `status`) values ( '@{SIMPLEENTITYNAME}/@{SIMPLEENTITYNAME}.html', '@{SIMPLEENTITYNAME}管理', null , '2', null , '1'); |
| | | |
| | | insert into `sys_resource` ( `code`, `name`, `resource_id`, `level`, `sort`, `status`) values ( '@{SIMPLEENTITYNAME}#view', '查询', '', '3', '0', '1'); |
| | | insert into `sys_resource` ( `code`, `name`, `resource_id`, `level`, `sort`, `status`) values ( '@{SIMPLEENTITYNAME}#btn-add', '新增', '', '3', '1', '1'); |
| | | insert into `sys_resource` ( `code`, `name`, `resource_id`, `level`, `sort`, `status`) values ( '@{SIMPLEENTITYNAME}#btn-edit', '编辑', '', '3', '2', '1'); |
| | | insert into `sys_resource` ( `code`, `name`, `resource_id`, `level`, `sort`, `status`) values ( '@{SIMPLEENTITYNAME}#btn-delete', '删除', '', '3', '3', '1'); |
| | | insert into `sys_resource` ( `code`, `name`, `resource_id`, `level`, `sort`, `status`) values ( '@{SIMPLEENTITYNAME}#btn-export', '导出', '', '3', '4', '1'); |
| | | |
| | | -- sqlserver |
| | | insert [dbo].[sys_resource] ( [code], [name], [resource_id], [level], [sort], [status]) values ( N'@{SIMPLEENTITYNAME}/@{SIMPLEENTITYNAME}.html', N'@{SIMPLEENTITYNAME}管理', null, '2', null, '1'); |
| | | |
| | | insert [dbo].[sys_resource] ( [code], [name], [resource_id], [level], [sort], [status]) values ( N'@{SIMPLEENTITYNAME}#view', N'查询', '', '3', '0', '1'); |
| | | insert [dbo].[sys_resource] ( [code], [name], [resource_id], [level], [sort], [status]) values ( N'@{SIMPLEENTITYNAME}#btn-add', N'新增', '', '3', '1', '1'); |
| | | insert [dbo].[sys_resource] ( [code], [name], [resource_id], [level], [sort], [status]) values ( N'@{SIMPLEENTITYNAME}#btn-edit', N'编辑', '', '3', '2', '1'); |
| | | insert [dbo].[sys_resource] ( [code], [name], [resource_id], [level], [sort], [status]) values ( N'@{SIMPLEENTITYNAME}#btn-delete', N'删除', '', '3', '3', '1'); |
| | | insert [dbo].[sys_resource] ( [code], [name], [resource_id], [level], [sort], [status]) values ( N'@{SIMPLEENTITYNAME}#btn-export', N'导出', '', '3', '4', '1'); |
New file |
| | |
| | | <?xml version="1.0" encoding="UTF-8"?> |
| | | <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> |
| | | <mapper namespace="@{COMPANYNAME}.mapper.@{ENTITYNAME}Mapper"> |
| | | |
| | | <!-- 通用查询映射结果 --> |
| | | <resultMap id="BaseResultMap" type="@{COMPANYNAME}.entity.@{ENTITYNAME}"> |
| | | @{XMLCONTENT} |
| | | </resultMap> |
| | | |
| | | </mapper> |