Commit b23101e3 authored by yanzg's avatar yanzg

Merge remote-tracking branch 'origin/master'

parents bed37658 2a6fb6bd
//package com.yanzuoguang.util;
//
//import com.yanzuoguang.util.base.MethodField;
//import com.yanzuoguang.util.base.ObjectHelper;
//import com.yanzuoguang.util.helper.JsonHelper;
//import com.yanzuoguang.util.helper.StringHelper;
//import com.yanzuoguang.util.vo.BaseVo;
//import com.yanzuoguang.util.vo.InitDao;
//
//import java.util.HashMap;
//
///**
// * 座次图关联表
// *
// * @author 朱磊
// */
//public class SetSetpictureVo extends BaseVo implements InitDao {
//
// /**
// * 座次图关联ID
// */
// private String setPictureId = "setPictureId";
// /**
// * 座次图ID
// */
// private String pictureId = "pictureId";
//
// @Override
// public void init() {
// this.setPictureId = StringHelper.getFirst(this.setPictureId, StringHelper.EMPTY);
// this.pictureId = StringHelper.getFirst(this.pictureId, StringHelper.EMPTY);
// }
//
// public String getSetPictureId() {
// return setPictureId;
// }
//
// public void setSetPictureId(String setPictureId) {
// this.setPictureId = setPictureId;
// }
//
// public String getPictureId() {
// return pictureId;
// }
//
// public void setPictureId(String pictureId) {
// this.pictureId = pictureId;
// }
//
// public static void main(String[] args) {
// SetSetpictureVo set = new SetSetpictureVo();
// System.out.println(ObjectHelper.get(set, "setPictureId"));
// System.out.println(ObjectHelper.get(set, "pictureId"));
//
// HashMap<String, MethodField> initTypeField = ObjectHelper.getTypeField(SetSetpictureVo.class);
// System.out.println(JsonHelper.serialize(initTypeField));
// }
//}
......@@ -12,21 +12,62 @@ public class MethodField {
/**
* 名称
*/
public String name;
private String name;
/**
* 缩写名称
*/
public String nameSimple;
private String nameSimple;
/**
* 对应的字段
*/
public Field field;
private Field field;
/**
* 对应的获取方法
*/
public Method getMethod;
private Method getMethod;
/**
* 对应的设置方法
*/
public Method setMethod;
private Method setMethod;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNameSimple() {
return nameSimple;
}
public void setNameSimple(String nameSimple) {
this.nameSimple = nameSimple;
}
public Field getField() {
return field;
}
public void setField(Field field) {
this.field = field;
}
public Method getGetMethod() {
return getMethod;
}
public void setGetMethod(Method getMethod) {
this.getMethod = getMethod;
}
public Method getSetMethod() {
return setMethod;
}
public void setSetMethod(Method setMethod) {
this.setMethod = setMethod;
}
}
......@@ -5,10 +5,7 @@ import com.yanzuoguang.util.exception.CodeException;
import com.yanzuoguang.util.exception.ExceptionHelper;
import com.yanzuoguang.util.helper.StringHelper;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.*;
import java.util.*;
/**
......@@ -156,10 +153,10 @@ public class ObjectHelper {
return null;
}
try {
if (item.field != null && Modifier.isPublic(item.field.getModifiers())) {
return item.field.get(target);
} else if (item.getMethod != null && Modifier.isPublic(item.getMethod.getModifiers())) {
return item.getMethod.invoke(target);
if (item.getField() != null && Modifier.isPublic(item.getField().getModifiers())) {
return item.getField().get(target);
} else if (item.getGetMethod() != null && Modifier.isPublic(item.getGetMethod().getModifiers())) {
return item.getGetMethod().invoke(target);
}
} catch (Exception ex) {
ExceptionHelper.handleException(ObjectHelper.class, ex, field);
......@@ -206,17 +203,21 @@ public class ObjectHelper {
return;
}
try {
if (item.field != null && Modifier.isPublic(item.field.getModifiers())) {
Class toType = item.field.getType();
setByType(target, item, value);
} catch (Exception ex) {
ExceptionHelper.handleException(ObjectHelper.class, ex, item.getName());
}
}
public static void setByType(Object target, MethodField item, Object value) throws IllegalAccessException, InvocationTargetException {
if (item.getField() != null && Modifier.isPublic(item.getField().getModifiers())) {
Class toType = item.getField().getType();
Object toValue = StringHelper.to(toType, value);
item.field.set(target, toValue);
} else if (item.setMethod != null && Modifier.isPublic(item.setMethod.getModifiers())) {
Class toType = item.setMethod.getParameterTypes()[0];
item.getField().set(target, toValue);
} else if (item.getSetMethod() != null && Modifier.isPublic(item.getSetMethod().getModifiers())) {
Class toType = item.getSetMethod().getParameterTypes()[0];
Object toValue = StringHelper.to(toType, value);
item.setMethod.invoke(target, toValue);
}
} catch (Exception ex) {
ExceptionHelper.handleException(ObjectHelper.class, ex, field);
item.getSetMethod().invoke(target, toValue);
}
}
......@@ -247,15 +248,15 @@ public class ObjectHelper {
* 获取缓存中的字段
* @param typeCache 类型
* @param fromName 来源名称
* @param toName 目标名称
* @return
*/
private static MethodField getField(HashMap<String, MethodField> typeCache, String fromName) {
String toName = getSimpleName(fromName);
private static MethodField getField(HashMap<String, MethodField> typeCache, String fromName, String toName) {
if (!typeCache.containsKey(toName)) {
MethodField newObj = new MethodField();
typeCache.put(toName, newObj);
newObj.name = fromName;
newObj.nameSimple = toName;
newObj.setName(fromName);
newObj.setNameSimple(toName);
}
return typeCache.get(toName);
}
......@@ -267,7 +268,7 @@ public class ObjectHelper {
* @return
*/
private static String getSimpleName(String fromName) {
String toName = fromName.toLowerCase().replace("_", "");
String toName = getSimpleFieldName(fromName);
if (toName.startsWith(METHOD_IS)) {
toName = toName.substring(METHOD_IS.length());
} else if (toName.startsWith(METHOD_GET)) {
......@@ -277,7 +278,18 @@ public class ObjectHelper {
} else {
return toName;
}
return getSimpleName(toName);
return toName;
}
/**
* 获取字段处理名称
*
* @param fromName 字段名称
* @return 属性名称
*/
private static String getSimpleFieldName(String fromName) {
String toName = fromName.toLowerCase().replace("_", "");
return toName;
}
/**
......@@ -303,12 +315,13 @@ public class ObjectHelper {
// 忽略大小写、忽略下划线 _
for (Field field : fields) {
MethodField obj = getField(typeCache, field.getName());
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
if (obj.field == null) {
obj.field = field;
String toName = getSimpleFieldName(field.getName());
MethodField obj = getField(typeCache, field.getName(), toName);
if (obj.getField() == null) {
obj.setField(field);
}
}
for (Method method : methods) {
......@@ -317,31 +330,32 @@ public class ObjectHelper {
}
String methodNameSource = method.getName();
String methodNameSimple = methodNameSource.toLowerCase();
String toName = getSimpleName(methodNameSource);
if ("getClass".equals(methodNameSource)) {
continue;
} else if (methodNameSimple.startsWith("set")) {
if (method.getParameterTypes().length != 1) {
continue;
}
MethodField obj = getField(typeCache, methodNameSource);
if (obj.setMethod == null) {
obj.setMethod = method;
MethodField obj = getField(typeCache, methodNameSource,toName);
if (obj.getSetMethod() == null) {
obj.setSetMethod(method);
}
} else if (methodNameSimple.startsWith("get")) {
if (method.getReturnType() == null) {
continue;
}
MethodField obj = getField(typeCache, methodNameSource);
if (obj.getMethod == null) {
obj.getMethod = method;
MethodField obj = getField(typeCache, methodNameSource,toName);
if (obj.getGetMethod() == null) {
obj.setGetMethod(method);
}
} else if (methodNameSimple.startsWith("is")) {
if (method.getReturnType() == null) {
continue;
}
MethodField obj = getField(typeCache, methodNameSource);
if (obj.getMethod == null) {
obj.getMethod = method;
MethodField obj = getField(typeCache, methodNameSource,toName);
if (obj.getGetMethod() == null) {
obj.setGetMethod(method);
}
}
}
......@@ -374,7 +388,7 @@ public class ObjectHelper {
*/
private static MethodField getMethodField(Class<?> type, String name) {
HashMap<String, MethodField> typeCache = getTypeField(type);
name = getSimpleName(name);
name = getSimpleFieldName(name);
return typeCache.containsKey(name) ? typeCache.get(name) : null;
}
......@@ -538,7 +552,7 @@ public class ObjectHelper {
return to;
}
for (Map.Entry<String, MethodField> field : mapField.entrySet()) {
String name = field.getValue().name;
String name = field.getValue().getName();
Object fromValue = ObjectHelper.get(from, name);
if (StringHelper.isEmpty(fromValue)) {
continue;
......
......@@ -16,7 +16,7 @@ public class MemoryCacheCenter {
/**
* 缓存的对象
*/
public static List<MemoryCache> CLEAR_LIST = new Vector<MemoryCache>();
public final static List<MemoryCache> CLEAR_LIST = new Vector<MemoryCache>();
static {
init();
......
......@@ -2,6 +2,7 @@ package com.yanzuoguang.util.exception;
/**
* 途比达异常信息
*
* @author 颜佐光
*/
public class CodeException extends RuntimeException {
......@@ -57,6 +58,15 @@ public class CodeException extends RuntimeException {
this.code = code;
}
/**
* 构造函数
* throw new CodeException("01","该订单已过期",order);
* throw new CodeException("02","该订单未到使用时间",order);
*
* @param code  错误码
* @param message  错误消息
* @param target  错误数据源,如订单数据
*/
public CodeException(String code, String message, Object target) {
super(message);
this.code = code;
......
......@@ -29,6 +29,8 @@ public class ByteHelper {
*/
public static final int BCD_MAX_FLAG = 100;
private ByteHelper(){}
// --------------------------------------- toLH -------------------------------------
/**
......@@ -554,6 +556,7 @@ public class ByteHelper {
* @return 转换之后的值
*/
public static int fromBCD(byte from) {
return (from / BYTE_HEX_UNIT) * BYTE_TEN_UNIT + from % BYTE_HEX_UNIT;
return (from / BYTE_HEX_UNIT) * BYTE_TEN_UNIT + from %
BYTE_HEX_UNIT;
}
}
......@@ -11,12 +11,13 @@ import java.util.regex.Pattern;
/**
* 参数业务逻辑校验
*
* @author 颜佐光
*/
public final class CheckerHelper {
public static final String PARAM_NOT_NULL_TIPS = "param [%s] is null";
public static final String PARAM_NOT_EMPTY_TIPS = "param [%s] is empty";
public static final String PARAM_NOT_NUMBER = "param [%s] must be number";
public static final String PARAM_NOT_NUMBER = "param [%s] value [%s] must be number";
public static final String PARAM_OVER_MAX_LENGTH = "param [%s] maxlength is ";
public static final String PARAM_NOT_DATE_MONTH = "param [%s] must be yyyyMM";
......@@ -176,9 +177,6 @@ public final class CheckerHelper {
String eL = "";
String msg = "";
if (StringHelper.isEmpty(paramVal)) {
msg = PARAM_NOT_NULL_TIPS;
this.checkResult = String.format(msg, paramName, paramVal);
this.setValid(false);
return this;
}
if (DATE_CHECK_TYPE_DAY.equals(queryType)) {
......@@ -272,7 +270,7 @@ public final class CheckerHelper {
SimpleDateFormat format = new SimpleDateFormat(formatStr);
format.parse(paramVal);
} else {
DateAutoHelper.getAutoDate(formatStr);
DateAutoHelper.getAutoDate(paramVal);
}
} catch (ParseException e) {
this.checkResult = String.format(PARAM_NOT_DATE, paramName, formatStr);
......@@ -328,7 +326,7 @@ public final class CheckerHelper {
return this;
}
if (paramVal < min) {
this.checkResult = String.format(PARAM_NOT_MIN, min, paramName);
this.checkResult = String.format(PARAM_NOT_MIN, paramName, min);
this.setValid(false);
}
return this;
......@@ -347,7 +345,7 @@ public final class CheckerHelper {
return this;
}
if (paramVal > max) {
this.checkResult = String.format(PARAM_NOT_MAX, max, paramName);
this.checkResult = String.format(PARAM_NOT_MAX, paramName, max);
this.setValid(false);
}
return this;
......@@ -367,7 +365,7 @@ public final class CheckerHelper {
return this;
}
if (paramVal > max || paramVal < min) {
this.checkResult = String.format(PARAM_NOT_RANGE, min, max, paramName);
this.checkResult = String.format(PARAM_NOT_RANGE, paramName, min, max);
this.setValid(false);
}
return this;
......
......@@ -87,19 +87,25 @@ public class FileHelper {
try {
// 删除文件
if (file.exists()) {
file.delete();
if (!file.delete()) {
throw new CodeException("文件删除失败");
}
}
if (file.exists()) {
throw new CodeException("文件删除失败");
}
// 创建文件夹
File parentFile = file.getParentFile();
if (parentFile != null && !parentFile.exists()) {
parentFile.mkdirs();
if (parentFile != null) {
if (!parentFile.exists()) {
if (!parentFile.mkdirs()) {
throw new CodeException("创建文件夹失败");
}
}
if (!parentFile.exists()) {
throw new CodeException("创建文件夹失败");
}
}
file.createNewFile();
// 写入文件
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
......
......@@ -86,7 +86,7 @@ public class HttpHelper {
*/
public static String post(HttpURLConnection httpConn, String jsonString) throws IOException {
// 返回的结果
String result = "";
StringBuilder result = new StringBuilder();
// 读取响应输入流
BufferedReader in = null;
PrintWriter out = null;
......@@ -107,7 +107,7 @@ public class HttpHelper {
String line;
// 读取返回的内容
while ((line = in.readLine()) != null) {
result += line;
result.append(line);
}
} finally {
if (out != null) {
......@@ -117,7 +117,7 @@ public class HttpHelper {
in.close();
}
}
return result;
return result.toString();
}
/**
......
......@@ -2,10 +2,12 @@ package com.yanzuoguang.util.helper;
import com.yanzuoguang.util.contants.SystemContants;
import java.util.Random;
import java.util.UUID;
/**
* 随机码生成工具
*
* @author 颜佐光
*/
public final class RandomHelper {
......@@ -102,12 +104,12 @@ public final class RandomHelper {
* @return
*/
private static String generateRandomCodeOne(String charset, int len) {
int index = (int) (Math.random() * len);
int index = new Random().nextInt(len);
return String.valueOf(charset.charAt(index));
}
private static String replace(String str, String olds, String news) {
if(null == str) {
if (null == str) {
return "";
}
while (str.indexOf(olds) > -1) {
......
......@@ -13,7 +13,7 @@ public class RunHelper {
/**
* 执行次数
*/
public static int REQ_SIZE = 3;
public final static int REQ_SIZE = 3;
/**
* 执行次数,并且获取最后一次的异常
......
......@@ -5,6 +5,7 @@ import com.yanzuoguang.util.exception.CodeException;
import com.yanzuoguang.util.exception.ExceptionHelper;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
......@@ -329,31 +330,34 @@ public class StringHelper {
* @return 返回获取的值
*/
public static <T> T to(Class<T> cls, Object from) {
if (from == null) {
return null;
}
String vName = cls.getName();
Object to = null;
if (cls.isEnum()) {
String strValue = toString(from);
to = EnumHelper.toEnum(cls, strValue);
} else if (isType(cls, String.class)) {
if (isType(cls, String.class)) {
to = toString(from);
} else if (TYPE_BOOL.equals(vName) || isType(cls, Boolean.class)) {
} else if (TYPE_BOOL.equals(vName)
|| (isType(cls, Boolean.class) && from != null)) {
String strValue = toString(from);
to = toBoolean(strValue);
} else if (TYPE_INT.equals(vName) || isType(cls, Integer.class)) {
} else if (TYPE_INT.equals(vName)
|| (isType(cls, Integer.class) && from != null)) {
to = toInt(from);
} else if (TYPE_DOUBLE.equals(vName) || isType(cls, Double.class)) {
} else if (TYPE_DOUBLE.equals(vName) ||
(isType(cls, Double.class) && from != null)) {
to = toDouble(from);
} else if (TYPE_FLOAT.equals(vName) || isType(cls, Float.class)) {
} else if (TYPE_FLOAT.equals(vName)
|| (isType(cls, Float.class) && from != null)) {
to = toDouble(from);
} else if (isType(cls, Double.class)) {
to = toDecimal(from);
} else if (isType(cls, Date.class)) {
to = DateHelper.getDateTime(from);
} else if (cls.isEnum()) {
String strValue = toString(from);
if (strValue != null) {
to = EnumHelper.toEnum(cls, strValue);
}
if (to != null) {
}
if (to == null && from == null) {
return null;
} else if (to != null) {
return (T) to;
} else {
if (ObjectHelper.isSub(cls, from.getClass())) {
......@@ -572,7 +576,7 @@ public class StringHelper {
try {
buff = from.getBytes(charset);
// 将字节流转换为字符串
from = new String(buff);
from = new String(buff, charset);
from = from.replace("\0", "").replace("\n", "");
} catch (UnsupportedEncodingException e) {
ExceptionHelper.handleException(StringHelper.class, e, from);
......@@ -822,7 +826,7 @@ public class StringHelper {
// 生成实现指定摘要算法的 MessageDigest 对象。
MessageDigest md = MessageDigest.getInstance("MD5");
// 使用指定的字节数组更新摘要。
md.update(from.getBytes());
md.update(from.getBytes(Charset.forName("utf-8")));
// 通过执行诸如填充之类的最终操作完成哈希计算。
byte[] b = md.digest();
// 生成具体的md5密码到buf数组
......
......@@ -2,7 +2,7 @@ package com.yanzuoguang.util.table;
/**
* 列头
* 列头,A.B , A.C
* @author 颜佐光
*/
public class TableHeadItem {
......
......@@ -16,7 +16,7 @@ public abstract class AbstractThreadList<T extends Object> implements ThreadWait
/**
* 线程等待间隔
*/
public static int PrintTimeout = 1000 * 2;
public final static int PrintTimeout = 1000 * 2;
/**
* 线程数量
......@@ -283,7 +283,7 @@ public abstract class AbstractThreadList<T extends Object> implements ThreadWait
}
ThreadListData<T> data = cacheThread.get(Thread.currentThread());
data.setDate(new Date());
data.setDate(System.currentTimeMillis());
data.setData(item);
try {
this.run(item);
......
......@@ -10,6 +10,7 @@ import java.util.List;
/**
* 自动执行任务
*
* @author 颜佐光
*/
public class RunPlan {
......@@ -82,7 +83,7 @@ public class RunPlan {
*/
public final void run(boolean isRemove, int maxError) {
for (int i = list.size() - 1; i >= 0; i--) {
Date now = new Date();
long now = System.currentTimeMillis();
RunPlanData item;
synchronized (this.lock) {
item = list.size() > i ? list.get(i) : null;
......@@ -96,10 +97,10 @@ public class RunPlan {
// 在Window CE中时间相减可能会出错
try {
// 处理非法改动时间
if (item.getDate().compareTo(now) > 0) {
if (item.getDate() > now) {
item.setDate(now);
}
millSeconds = (now.getTime() - item.getDate().getTime());
millSeconds = (now - item.getDate());
} catch (Exception ex) {
ExceptionHelper.handleException(ThreadHelper.class, ex);
}
......
......@@ -10,7 +10,7 @@ public class RunPlanData {
/**
* 任务开始时间
*/
private Date date;
private long date;
/**
* 执行标记
*/
......@@ -39,11 +39,11 @@ public class RunPlanData {
this.initDate();
}
public Date getDate() {
public long getDate() {
return date;
}
public void setDate(Date date) {
public void setDate(long date) {
this.date = date;
}
......@@ -106,6 +106,6 @@ public class RunPlanData {
* 重置时间
*/
public void initDate() {
this.date = new Date();
this.date = System.currentTimeMillis();
}
}
......@@ -17,7 +17,7 @@ public final class RunnableListAuto {
/**
* 是否打印线程日志
*/
public static boolean IsLog = false;
public final static boolean IsLog = false;
/**
* 缓存的执行对象的数据大小
......
......@@ -13,18 +13,18 @@ public class ThreadListData<T> {
/**
* 执行时间
*/
private Date date;
private long date;
/**
* 执行的数据
*/
private T data;
public Date getDate() {
public long getDate() {
return date;
}
public void setDate(Date date) {
public void setDate(long date) {
this.date = date;
}
......
......@@ -3,11 +3,15 @@ package com.yanzuoguang.util.vo;
/**
* 引用值,方便修改
*
int func(Ref<Interger> int1,Ref<Integer> int2){
int1.value =1 ;
}
* @param <T>
* @author 颜佐光
*/
public class Ref<T> {
public T value;
public Ref(T value) {
this.value = value;
}
......
......@@ -2,7 +2,6 @@ package com.yanzuoguang.cloud.aop;
import com.yanzuoguang.cloud.CloudContans;
import com.yanzuoguang.cloud.service.TokenServiceCall;
import com.yanzuoguang.util.base.ObjectHelper;
import com.yanzuoguang.util.contants.ResultConstants;
import com.yanzuoguang.util.exception.ExceptionHelper;
import com.yanzuoguang.util.helper.JsonHelper;
......@@ -20,6 +19,7 @@ import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.servlet.ServletRequest;
......@@ -42,6 +42,9 @@ public class WebAspect extends BaseRequestAspect {
@Autowired
private TokenServiceCall tokenServiceCall;
@Value("${yzg.reqUrl:order,check,use}")
private String reqUrl;
/**
* exec aop point aspect
*/
......@@ -116,30 +119,55 @@ public class WebAspect extends BaseRequestAspect {
* @throws NoSuchMethodException
*/
private Type getReturnType(ProceedingJoinPoint joinPoint) {
Method m = getMethod(joinPoint);
Type t = m.getAnnotatedReturnType().getType();
return t;
}
/**
* 获取返回的至类型
*
* @param joinPoint
* @return
* @throws NoSuchMethodException
*/
private Method getMethod(ProceedingJoinPoint joinPoint) {
//获取返回值类型
Signature s = joinPoint.getSignature();
MethodSignature ms = (MethodSignature) s;
Method m = ms.getMethod();
Type t = m.getAnnotatedReturnType().getType();
return t;
return m;
}
/**
* 执行方法
*
* @param joinPoint 需要执行的方法
* @param name 方法名称
* @return 返回结果
* @throws Throwable
*/
private Object executeMethod(ProceedingJoinPoint joinPoint, String name) throws Throwable {
boolean dataArgs = joinPoint.getArgs().length != 1
|| joinPoint.getArgs().length == 1 &&
(joinPoint.getArgs()[0] instanceof ServletResponse || joinPoint.getArgs()[0] instanceof ServletRequest);
if (dataArgs) {
Method method = getMethod(joinPoint);
boolean isUrl = false;
if (!StringHelper.isEmpty(reqUrl)) {
String[] urls = reqUrl.split(",");
for (String url : urls) {
if (method.getName().matches(url)) {
isUrl = true;
break;
}
}
}
if (dataArgs || !isUrl) {
return joinPoint.proceed();
} else {
// 获取请求编号
Object firstArgs = joinPoint.getArgs().length > 0 ? joinPoint.getArgs()[0] : null;
String reqId = ObjectHelper.getString(firstArgs, "reqId");
if (StringHelper.isEmpty(reqId)) {
reqId = StringHelper.md5(JsonHelper.serialize(firstArgs));
} else {
// 请求编号和公司编号挂钩
reqId = StringHelper.getId(ObjectHelper.getString(firstArgs, "companyId"), reqId);
}
String reqId = StringHelper.md5(JsonHelper.serialize(firstArgs));
String reqFull = StringHelper.getId(reqId, HttpAspectUtil.getHttpRequestUrl());
RequestCacheResult req = cacheResult.get(reqFull, new RequestCacheResult(reqFull));
// 缓存的键值对
......
package com.yanzuoguang.cloud.aop;
import com.yanzuoguang.util.log.Log;
import org.springframework.boot.web.servlet.filter.OrderedHiddenHttpMethodFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 跨域的支持
*
* @author 颜佐光
*/
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
public WebConfig() {
Log.info(WebConfig.class, "跨域已开启支持");
}
@Bean
public HiddenHttpMethodFilter hiddenHttpMethodFilter() {
return new OrderedHiddenHttpMethodFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
filterChain.doFilter(request, response);
}
};
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.maxAge(3600);
}
}
......@@ -10,6 +10,7 @@ import java.util.Random;
/**
* 加密算法0版实现
*
* @author 颜佐光
*/
public class CodePwdImpl implements CodePwd {
......@@ -38,25 +39,26 @@ public class CodePwdImpl implements CodePwd {
*/
@Override
public String getCode(String rand, String day, String index, String pwd) {
String ret = "";
StringBuilder ret = new StringBuilder();
// 1. 将随即数和天数进行组合生成字符串
String randDay = "";
StringBuilder sb = new StringBuilder();
{
int randSize = rand.length();
int daySize = day.length();
int maxLen = Math.max(rand.length(), day.length());
for (int i = 0; i < maxLen; i++) {
if (i < daySize) {
randDay += day.charAt(i);
sb.append(day.charAt(i));
}
if (i < randSize) {
randDay += rand.charAt(i);
sb.append(rand.charAt(i));
}
}
}
// 2. 将组合后的数字进行交换
String randDay = sb.toString();
int randDaySize = randDay.length();
char[] dayChars = new char[randDaySize];
{
......@@ -71,7 +73,7 @@ public class CodePwdImpl implements CodePwd {
}
}
for (int i = 0; i < randDaySize; i++) {
ret += dayChars[i];
ret.append(dayChars[i]);
}
}
......@@ -121,10 +123,10 @@ public class CodePwdImpl implements CodePwd {
for (int i = 0; i < newSize; i++) {
newValue[i] = (newValue[i] % 10 + 10) % 10;
ret += newValue[i];
ret.append(newValue[i]);
}
return ret;
return ret.toString();
}
public static void test(String[] args) {
......
package com.yanzuoguang.dao;
import com.yanzuoguang.util.vo.PageSizeData;
import com.yanzuoguang.util.vo.PageSizeReqVo;
import java.util.List;
/**
* 数据基本操作接口
*
* @author 颜佐光
*/
public interface BaseDao {
......@@ -35,31 +39,41 @@ public interface BaseDao {
String save(Object model);
/**
* 删除数据
*
* @param model 需要删除的数据
* 删除数据,可以用于父子表删除,如通过订单删除游客信息 visitorDao.remove({orderId:1});
* int field;
* @param model 需要删除的数据,可以是主键字符串(Int),或者是包含主键的实体,或者是包含其他非主键的实体完全匹配.
* @return 删除的记录数量
*/
int remove(Object model);
/**
* 加载数据
* 加载数据,可以用于父子表删除,如通过订单删除游客信息 visitorDao.load({orderId:1});
*
* @param model 加载数据的请求参数
* @param cls 需要加载的数据的类型
* @param model 加载数据的请求参数,可以是主键字符串(Int),或者是包含主键的实体,或者是包含其他非主键的实体完全匹配.
* @param resultClass 需要加载的数据的类型
* @param <T> 返回数据的类型
* @return 需要返回的数据
*/
<T extends Object> T load(Object model, Class<T> cls);
<T extends Object> T load(Object model, Class<T> resultClass);
/**
* 加载列表数据
* 加载列表数据,可以用于父子表删除,如通过订单删除游客信息 visitorDao.loadList({orderId:1});
*
* @param model 加载数据的请求参数,可以是主键字符串(Int),或者是包含主键的实体,或者是包含其他非主键的实体完全匹配.
* @param resultClass 需要加载的数据的类型
* @param <T> 返回数据的类型
* @return 需要返回的数据
*/
<T extends Object> List<T> loadList(Object model, Class<T> resultClass);
/**
* 加载分页数据
*
* @param model 加载数据的请求参数
* @param cls 需要加载的数据的类型
* @param model 加载数据的请求参数,可以是主键字符串(Int),或者是包含主键的实体,或者是包含其他非主键的实体完全匹配.
* @param resultClass 需要加载的数据的类型
* @param <T> 返回数据的类型
* @return 需要返回的数据
*/
<T extends Object> List<T> loadList(Object model, Class<T> cls);
<T extends Object> PageSizeData<T> loadPage(PageSizeReqVo model, Class<T> resultClass);
}
......@@ -53,6 +53,11 @@ public class DaoConst {
*/
public static final String GROUP_QUERY = "GroupQuery";
/**
* 根据某个字段保存
*/
public static final String SAVE_WITH = "SaveWith";
/**
* 驼峰式命名
*/
......@@ -69,51 +74,119 @@ public class DaoConst {
* 单位地址
*/
public static final int CODE_UNIT = 2;
/**
* 插入SQL语句模板
*/
public static final String SQL_INSERT = "INSERT INTO {TABLE}({FIELD}) VALUES({VALUES})";
/**
* 更新SQL语句模板
*/
public static final String SQL_UPDATE = "UPDATE {TABLE} AS a {INNER} SET {FIELD} WHERE 1=1 {WHERE}";
/**
* 删除SQL语句模板
*/
public static final String SQL_REMOVE = "DELETE a FROM {TABLE} AS a {INNER} WHERE 1=1 {WHERE}";
/**
* 加载SQL语句模板
*/
public static final String SQL_LOAD = "SELECT a.*{FIELD} FROM {TABLE} AS a {INNER} WHERE 1=1 {WHERE}";
/**
* 表名代码片段
*/
public static final String TABLE_CODE = "{TABLE}";
public static final String CODE_TABLE = "{TABLE}";
/**
* 字段代码片段
*/
public static final String FIELD_CODE = "{FIELD}";
public static final String CODE_FIELD = "{FIELD}";
/**
* 值代码片段
*/
public static final String VALUES_CODE = "{VALUES}";
public static final String CODE_VALUES = "{VALUES}";
/**
* WHERE条件代码片段
*/
public static final String WHERE_CODE = "{WHERE}";
public static final String CODE_WHERE = "{WHERE}";
/**
* 插入SQL语句模板
* 更新字段模板
*/
public static final String INSERT_MODEL = "INSERT INTO {TABLE}({FIELD}) VALUES({VALUES})";
public static final String CODE_UPDATE_FIELD = "a.%s=%s";
/**
* 更新SQL语句模板
* 更新字段模板主键
*/
public static final String UPDATE_MODEL = "UPDATE {TABLE} SET {FIELD} WHERE 1=1 {WHERE}";
public static final String CODE_UPDATE_PRIMARY = "a.%s=a.%s";
/**
* 删除SQL语句模板
* 更新字段模板参数
*/
public static final String REMOVE_MODEL = "DELETE FROM {TABLE} WHERE 1=1 {WHERE}";
public static final String CODE_UPDATE_FIELD_PARA = ",a.%s=?";
/**
* 加载SQL语句模板
* 更新字段模板参数
*/
public static final String CODE_UPDATE_FIELD_REMOVE = "a.%s=1";
/**
* 等于条件
*/
public static final String LOAD_MODEL = "SELECT a.*{FIELD} FROM {TABLE} AS a {INNER} WHERE 1=1 {WHERE}";
public static final String CODE_WHERE_EQUALS = "AND %s%s=%s";
/**
* 等于条件参数
*/
public static final String CODE_WHERE_EQUALS_PARA = "AND a.%s=?";
/**
* 未删除条件
*/
public static final String CODE_WHERE_EQUALS_NOT_REMOVE = "AND a.%s=0";
/**
* 版本好字段
*/
public static final String CODE_UPDATE_VERSION_FIELD = ",a.%s=1+a.%s";
/**
* 不等于条件
*/
public static final String CODE_WHERE_NOT_EQUALS = "AND %s%s<>%s";
/**
* 不等于条件
*/
public static final String CODE_WHERE_NOT_EQUALS_PARA = "AND a.%s<>?";
/**
* 默认表标记
*/
public static final String CODE_TAG = "a.";
/**
* 参数标记
*/
public static final String CODE_PARA = "?";
/**
* 增加修改语句的分割符号
*/
public static final String CODE_SPLIT = ",";
/**
* 统计语句增加字段模板
*/
public static final String CODE_GROUP_ADD = "a.{FIELD}=a.{FIELD}+?";
/**
* 版本号字段名称
*/
public static final String VERSON = "verson";
public static final String VERSION_FLAG = "version";
/**
* 删除字段名称
*/
public static final String ISREMOVE = "isremove";
public static final String REMOVE_FLAG = "remove";
/**
* 创建字段名称
*/
public static final String CREATE_FLAG = "create";
/**
* 更新字段名称
*/
public static final String UPDATE_FLAG = "update";
/**
* MD5标记字段
*/
public static final String MD5_KEY_FLAG = "md5key";
/**
* 删除字符串长度变量
*/
public static final String ISREMOVE_CONTANS = "contans____isremove";
public static final String REMOVE_FLAG_INPUT = "remove_input";
/**
* ID字段
*/
......@@ -122,4 +195,85 @@ public class DaoConst {
* 集合初始化大小
*/
public static final int COLLECTION_INIT_SIZE = 15;
/**
* 查询条件默认代码片段
*/
public static final String[] LAST_AUTO_ADD = new String[]{"{WHERE}", "{GROUP}", "{HAVING}", "{ORDER}", "{LIMIT}"};
/**
* 普通字段
*/
public static final int FIELD_NONE = -1;
/**
* 普通字段
*/
public static final int FIELD_COMMON = 0;
/**
* 删除标记
*/
public static final int FIELD_REMOVE = 1;
/**
* 版本号字段
*/
public static final int FIELD_VERSION = 2;
/**
* 主键字段
*/
public static final int FIELD_PRIMARY = 3;
/**
* MD5标记字段,用于统计字段
*/
public static final int FIELD_MD5 = 4;
/**
* 删除时记录操作状态的字段
*/
public static final int FIELD_REMOVE_UPDATE = 5;
/**
* 删除时记录操作状态的字段
*/
public static final int FIELD_CREATE = 6;
/**
* 根据字段保存
*/
public static final int FIELD_SAVE_WITH = 7;
/**
* 根据字段添加统计
*/
public static final int FIELD_ADD_GROUP = 8;
/**
* SQL语句类型-普通语句
*/
public static final int SQL_TYPE_COMMON = 0;
/**
* SQL语句类型-创建语句
*/
public static final int SQL_TYPE_CREATE = 1;
/**
* SQL语句类型-更新语句
*/
public static final int SQL_TYPE_UPDATE = 2;
/**
* SQL语句类型-删除语句
*/
public static final int SQL_TYPE_REMOVE = 3;
/**
* SQL语句类型-加载语句
*/
public static final int SQL_TYPE_LOAD = 4;
/**
* SQL语句类型-是否存在
*/
public static final int SQL_TYPE_EXISTS = 5;
/**
* SQL语句类型-根据字段保存
*/
public static final int SQL_TYPE_SAVE_WITH = 6;
/**
* SQL语句类型-添加统计
*/
public static final int SQL_TYPE_ADD_GROUP = 7;
}
package com.yanzuoguang.dao;
import com.yanzuoguang.util.helper.StringHelper;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
......@@ -18,5 +20,11 @@ public @interface TableAnnotation {
*
* @return
*/
String value();
String value() default StringHelper.EMPTY;
/**
* 字段类型
* @return
*/
int type() default DaoConst.FIELD_NONE;
}
......@@ -2,18 +2,21 @@ package com.yanzuoguang.dao.impl;
import com.yanzuoguang.dao.BaseDao;
import com.yanzuoguang.dao.DaoConst;
import com.yanzuoguang.db.impl.AllBeanRowMapper;
import com.yanzuoguang.util.base.ObjectHelper;
import com.yanzuoguang.util.exception.CodeException;
import com.yanzuoguang.util.helper.DateHelper;
import com.yanzuoguang.util.helper.StringHelper;
import com.yanzuoguang.util.vo.InitDao;
import com.yanzuoguang.util.vo.MapRow;
import com.yanzuoguang.util.vo.*;
import java.util.*;
/**
* 数据库操作的基本工具类
* 1. 实现了基本的增删该查
* 2. 实现了统计的增肌和修改
* 3. 实现了一定功能的基本验证,验证数据是否存在
* 4. 数据主键的获取等功能。
* 5. 获取自增等功能
*
* @author 颜佐光
*/
......@@ -145,6 +148,9 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao {
this.check(DaoConst.OPERATOR_TYPE_UPDATE, keyString, model);
SqlData sqlData = this.getSql(DaoConst.UPDATE);
int ret = updateSql(sqlData, model);
if (ret == 0) {
throw new CodeException("修改失败,请确认是否被其他人修改,版本号传入是否正确");
}
String retVal = ret > 0 ? keyString : "";
return retVal;
}
......@@ -161,6 +167,14 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao {
InitDao to = (InitDao) model;
to.init();
}
if (operatorType == DaoConst.OPERATOR_TYPE_CREATE || operatorType == DaoConst.OPERATOR_TYPE_UPDATE) {
List<SqlData> sqlArray = this.table.getSqlType(DaoConst.SQL_TYPE_SAVE_WITH);
if (sqlArray != null) {
for (SqlData sql : sqlArray) {
this.checkExist(sql.getName(), model, String.format("%s已经存在", sql.getName()));
}
}
}
}
/**
......@@ -197,16 +211,12 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao {
this.setKeyString(from, keyString);
// 调用删除日志
this.check(DaoConst.OPERATOR_TYPE_REMOVE, keyString, from);
} else {
List<MapRow> rows = this.query(MapRow.class, DaoConst.LOAD, from);
for (MapRow row : rows) {
keyString = this.getKeyString(from);
if (StringHelper.isEmpty(keyString)) {
keyString = StringHelper.toString(AllBeanRowMapper.getLoweRowField(row, this.getKey()));
}
// 调用删除日志
this.check(DaoConst.OPERATOR_TYPE_REMOVE, keyString, row);
}
// 处理来源值
for (TableFieldVo fieldVo : this.table.getTable().getRemoveUpdate()) {
Object fromValue = ObjectHelper.get(model, fieldVo.inputName);
ObjectHelper.set(from, fieldVo.inputName, fromValue);
}
// 调用删除语句
......@@ -218,12 +228,12 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao {
* 加载数据
*
* @param model 加载数据的请求参数
* @param cls 需要加载的数据的类型
* @param resultClass 需要加载的数据的类型
* @param <T> 返回数据的类型
* @return 需要返回的数据
*/
@Override
public <T extends Object> T load(Object model, Class<T> cls) {
public <T extends Object> T load(Object model, Class<T> resultClass) {
// 获取来源主键
Object from = model;
String key = this.getInputKey(from);
......@@ -235,7 +245,7 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao {
}
// 通过传入数据进行加载
T to = this.queryFirst(cls, DaoConst.LOAD, from);
T to = this.queryFirst(resultClass, DaoConst.LOAD, from);
if (to == null) {
return to;
}
......@@ -255,12 +265,12 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao {
* 加载数据
*
* @param model 加载数据的请求参数
* @param cls 需要加载的数据的类型
* @param resultClass 需要加载的数据的类型
* @param <T> 返回数据的类型
* @return 需要返回的数据
*/
@Override
public <T extends Object> List<T> loadList(Object model, Class<T> cls) {
public <T extends Object> List<T> loadList(Object model, Class<T> resultClass) {
// 获取来源主键
Object from = model;
String key = this.getInputKey(from);
......@@ -272,7 +282,7 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao {
}
// 通过传入数据进行加载
List<T> to = this.query(cls, DaoConst.LOAD, from);
List<T> to = this.query(resultClass, DaoConst.LOAD, from);
if (to == null || to.size() == 0) {
return new ArrayList<>();
}
......@@ -290,6 +300,46 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao {
return to;
}
/**
* 加载分页数据
*
* @param model 加载数据的请求参数
* @param resultClass 需要加载的数据的类型
* @param <T> 返回数据的类型
* @return 需要返回的数据
*/
@Override
public <T extends Object> PageSizeData<T> loadPage(PageSizeReqVo model, Class<T> resultClass) {
// 获取来源主键
Object from = model;
String key = this.getInputKey(from);
// 当主键存在时,只通过主键加载
if (!StringHelper.isEmpty(key)) {
from = new HashMap<String, Object>(DaoConst.COLLECTION_INIT_SIZE);
this.setKeyString(from, key);
}
// 通过传入数据进行加载
PageSizeData<T> to = this.queryPage(resultClass, model, DaoConst.LOAD, from);
if (to == null || to.getPageTotal() == 0) {
return to;
}
// 判断来源主键是否存在,不存在则获取加载后的主键
if (StringHelper.isEmpty(key)) {
check(DaoConst.OPERATOR_TYPE_LOAD, key, to);
} else {
for (Object item : to.getList()) {
key = this.getKeyString(item);
check(DaoConst.OPERATOR_TYPE_LOAD, key, to);
}
}
return to;
}
/**
* 添加统计数据
*
......
......@@ -19,7 +19,7 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* SQL语句基本操作类
* SQL语句基本操作类,包括SQL语句的解析,参数的组装,查询缓存的处理
*
* @author 颜佐光
*/
......@@ -44,7 +44,7 @@ public abstract class BaseDaoSql {
/**
* 缓存的表结构和SQL语句
*/
protected static MemoryCache<TableSqlCache> cache = new MemoryCache<>();
protected final static MemoryCache<TableSqlCache> cache = new MemoryCache<>();
/**
* 获取数据库执行类
......@@ -131,7 +131,7 @@ public abstract class BaseDaoSql {
if (this.table == null) {
throw new CodeException("类" + this.getClass().getName() + "未发现表结构");
}
SqlData sql = this.table.getSqls().get(name);
SqlData sql = this.table.getNameCache().get(name);
if (isThrow && sql == null) {
throw new CodeException("类" + this.getClass().getName() + "未发现SQL语句" + name);
}
......@@ -186,7 +186,7 @@ public abstract class BaseDaoSql {
protected Object queryCell(SqlData sqlData, Object model) {
List<Object> paras = new ArrayList<>();
String sql = this.getQueryPara(paras, sqlData, model);
Object cell = this.queryCellWithCache(sql, sqlData.getName(), paras.toArray());
Object cell = this.queryCellWithCache(sqlData.getName(), sql, paras.toArray());
return cell;
}
......@@ -412,20 +412,19 @@ public abstract class BaseDaoSql {
* @return SQL条件
*/
protected String getQueryPara(List<Object> paras, SqlData sqlData, Object model) {
// 定义可替换片段
String[] lastCode = new String[]{"{WHERE}", "{GROUP}", "{HAVING}", "{ORDER}", "{LIMIT}"};
// 将SQL语句进行代码片段追加
String sql = sqlData.getSql();
for (String code : lastCode) {
if (sql.indexOf(code) == -1) {
sql += code;
StringBuilder sb = new StringBuilder(sqlData.getSql());
for (String code : DaoConst.LAST_AUTO_ADD) {
if (sb.indexOf(code) == -1) {
sb.append(code);
}
}
// 代码片段缓存
Map<String, List<String>> codeMap = new HashMap<>(DaoConst.COLLECTION_INIT_SIZE);
// 处理字段以及代码片段
String sql = sb.toString();
sql = handleCodeRelease(sql, sqlData, model, codeMap);
sql = handleCodeReplace(sql, codeMap);
......@@ -548,7 +547,7 @@ public abstract class BaseDaoSql {
*/
private Object getParaValue(Object val) {
if (val instanceof Boolean) {
val = 0;
val = (Boolean)val ? 1 : 0;
}
val = StringHelper.toString(val);
return val;
......@@ -682,7 +681,7 @@ public abstract class BaseDaoSql {
}
// 将对象转换为 Map 对象
Map to = new HashMap<String, Object>(DaoConst.COLLECTION_INIT_SIZE);
Map<String, Object> to = new HashMap<>(DaoConst.COLLECTION_INIT_SIZE);
if (from instanceof Map) {
to = (Map) from;
} else {
......@@ -694,16 +693,16 @@ public abstract class BaseDaoSql {
sb.append(" SELECT ");
// 处理列
for (Object oItemKey : to.keySet()) {
for (Map.Entry<String, Object> oItemKey : to.entrySet()) {
if (column > 0) {
sb.append(",");
}
String itemKey = StringHelper.toString(oItemKey);
String itemKey = oItemKey.getKey();
sb.append("? AS " + itemKey);
// 处理参数
Object itemValue = to.get(oItemKey);
Object itemValue = oItemKey.getValue();
itemValue = this.getParaValue(itemValue);
paras.add(itemValue);
column++;
......
......@@ -12,9 +12,9 @@ import java.util.List;
public class SqlData {
/**
* 对应的参数顺序
* SQL语句类型
*/
private List<SqlDataField> sqlDataFields = new ArrayList<SqlDataField>();
private int sqlType = DaoConst.SQL_TYPE_COMMON;
/**
* SQL语句的名称
......@@ -26,6 +26,11 @@ public class SqlData {
*/
private String sql;
/**
* 对应的参数顺序
*/
private List<SqlDataField> sqlDataFields = new ArrayList<SqlDataField>();
/**
* 构造函数
*/
......@@ -33,6 +38,22 @@ public class SqlData {
this("", "");
}
/**
* Sql语句类型
* @return Sql语句类型
*/
public int getSqlType() {
return sqlType;
}
/**
* Sql语句类型
* @param sqlType Sql语句类型
*/
public void setSqlType(int sqlType) {
this.sqlType = sqlType;
}
public List<SqlDataField> getSqlDataFields() {
return sqlDataFields;
}
......@@ -231,7 +252,7 @@ public class SqlData {
* @return
*/
public SqlData removeFieldRemove() {
this.removeField(DaoConst.ISREMOVE_CONTANS);
this.removeField(DaoConst.REMOVE_FLAG_INPUT);
return this;
}
......
package com.yanzuoguang.dao.impl;
import com.yanzuoguang.util.helper.StringHelper;
import java.util.ArrayList;
import java.util.List;
......@@ -12,9 +14,11 @@ public class SqlDataField {
/**
* 前台参数名称,当没有前台参数时,则把当前字段当常量代码片段处理
*/
public String paraName = "";
public String paraName = StringHelper.EMPTY;
/**
* 是否根据前台参数自动添加,false时保持永久添加模式
* 是否根据前台参数自动添加,false时保持永久添加模式,
* 1. true为条件模式,即前台不输入参数时,则不增加相关代码片段
* 2. false为敞亮模式,不管前台是否输入,该参数和片段必然会增加到后台执行语句中
*/
public boolean auto = true;
/**
......
......@@ -28,14 +28,28 @@ public class TableFieldVo {
this.type = type;
}
/**
* 表字段的原名称
*/
public String name;
/**
* 表子弹的名称小写
*/
public String lName;
/**
* 前台输入参数的名称
*/
public String inputName;
/**
* 前台输入的参数的小写
*/
public String inputLName;
/**
* 实体的参数的类型
*/
public Class<?> type = String.class;
;
}
......@@ -14,6 +14,7 @@ import java.util.regex.Pattern;
/**
* 缓存的SQL语句信息
*
* @author 颜佐光
*/
public class TableSqlCache {
......@@ -24,14 +25,19 @@ public class TableSqlCache {
public static final String PAGE_SIZE_TAG = "_PageSize";
/**
* 表信息
* 表结构信息
*/
private TableStruct table;
/**
* 缓存的SQL信息
* 缓存的SQL信息,按照名称进行缓存
*/
private MemoryCache<SqlData> sqls = new MemoryCache<SqlData>();
private MemoryCache<SqlData> nameCache = new MemoryCache<SqlData>();
/**
* 根据Sql语句类型进行缓存,按照类型进行缓存
*/
private MemoryCache<List<SqlData>> typeCache = new MemoryCache<>();
/**
* 构造函数
......@@ -58,11 +64,25 @@ public class TableSqlCache {
*/
public SqlData add(SqlData sql) {
if (sql != null) {
this.sqls.put(sql.getName(), sql);
this.nameCache.put(sql.getName(), sql);
String keyType = String.valueOf(sql.getSqlType());
this.typeCache.get(keyType, new ArrayList<>()).add(sql);
}
return sql;
}
/**
* 获取所有的Sql语句执行类型
*
* @param sqlType Sql语句执行类型
* @return Sql语句列表
*/
public List<SqlData> getSqlType(int sqlType) {
String keyType = String.valueOf(sqlType);
return typeCache.get(keyType);
}
/**
* 添加SQL
*
......@@ -278,8 +298,8 @@ public class TableSqlCache {
}
private String replaceString(Map<String, StringBuilder> map, String sql) {
for (String key : map.keySet()) {
sql = sql.replace(key, map.get(key).toString());
for (Map.Entry<String, StringBuilder> key : map.entrySet()) {
sql = sql.replace(key.getKey(), key.getValue().toString());
}
return sql;
}
......@@ -292,11 +312,11 @@ public class TableSqlCache {
this.table = table;
}
public MemoryCache<SqlData> getSqls() {
return sqls;
public MemoryCache<SqlData> getNameCache() {
return nameCache;
}
public void setSqls(MemoryCache<SqlData> sqls) {
this.sqls = sqls;
public void setNameCache(MemoryCache<SqlData> nameCache) {
this.nameCache = nameCache;
}
}
package com.yanzuoguang.db.impl;
import com.yanzuoguang.dao.DaoConst;
import com.yanzuoguang.dao.TableAnnotation;
import com.yanzuoguang.extend.ConfigDb;
import com.yanzuoguang.util.base.MethodField;
import com.yanzuoguang.util.base.ObjectHelper;
import com.yanzuoguang.util.helper.StringHelper;
import com.yanzuoguang.util.log.Log;
......@@ -13,9 +15,6 @@ import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
......@@ -25,6 +24,7 @@ import java.util.Map;
/**
* 将数据映射为结果
*
* @author 颜佐光
*/
public class AllBeanRowMapper<T> implements RowMapper<T> {
......@@ -35,24 +35,14 @@ public class AllBeanRowMapper<T> implements RowMapper<T> {
private Class<T> mappedClass;
/**
* Mappings是否属于字段s
*/
private Map<String, Boolean> mappedIsFields;
/**
* 需要映射的字段
*/
private Map<String, Field> mappedFields;
/**
* 需要映射的属性
* 是否属于映射方式
*/
private Map<String, PropertyDescriptor> mappedPropertys;
private boolean isMapping = false;
/**
* 是否属于映射方式
* 获取字段映射关系
*/
private boolean isMapping = false;
private Map<String, MethodField> typeField;
/**
* 配置信息
......@@ -76,32 +66,29 @@ public class AllBeanRowMapper<T> implements RowMapper<T> {
*/
protected void initialize(Class<T> mappedClass) {
this.mappedClass = mappedClass;
this.mappedFields = new HashMap<>(DaoConst.COLLECTION_INIT_SIZE);
this.mappedPropertys = new HashMap<>(DaoConst.COLLECTION_INIT_SIZE);
this.mappedIsFields = new HashMap<>(DaoConst.COLLECTION_INIT_SIZE);
if (ObjectHelper.isSub(MapRow.class, mappedClass) || ObjectHelper.isSub(Map.class, mappedClass)) {
isMapping = true;
} else {
Field[] fields = mappedClass.getFields();
for (Field item : fields) {
if (Modifier.isStatic(item.getModifiers())) {
continue;
Map<String, MethodField> temp = ObjectHelper.getTypeField(mappedClass);
typeField = new HashMap<>(temp.size());
for (Map.Entry<String, MethodField> item : temp.entrySet()) {
String name = item.getKey();
// 获取字段值
MethodField field = item.getValue();
// 获取名称
TableAnnotation annotation = null;
if (field.getField() != null) {
annotation = field.getField().getAnnotation(TableAnnotation.class);
} else if (field.getGetMethod() != null) {
annotation = field.getGetMethod().getAnnotation(TableAnnotation.class);
}
String name = item.getName();
String underscoredName = underscoreName(name);
this.mappedFields.put(underscoredName, item);
this.mappedIsFields.put(underscoredName, true);
if (annotation != null && !StringHelper.isEmpty(annotation.value())) {
name = annotation.value();
}
PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
for (PropertyDescriptor item : pds) {
if (item.getWriteMethod() != null) {
String name = item.getName();
String underscoredName = underscoreName(name);
this.mappedPropertys.put(underscoredName, item);
this.mappedIsFields.put(underscoredName, false);
}
this.typeField.put(underscoredName, item.getValue());
}
}
}
......@@ -138,8 +125,8 @@ public class AllBeanRowMapper<T> implements RowMapper<T> {
*/
public static MapRow toLoweRow(MapRow from) {
MapRow to = new MapRow();
for (String key : from.keySet()) {
to.put(underscoreNameBase(key), from.get(key));
for (Map.Entry<String, Object> key : from.entrySet()) {
to.put(underscoreNameBase(key.getKey()), key.getValue());
}
return to;
}
......@@ -152,9 +139,9 @@ public class AllBeanRowMapper<T> implements RowMapper<T> {
*/
public static Object getLoweRowField(MapRow from, String field) {
field = underscoreNameBase(field);
for (String key : from.keySet()) {
if (underscoreNameBase(key).equals(field)) {
return from.get(key);
for (Map.Entry<String, Object> key : from.entrySet()) {
if (underscoreNameBase(key.getKey()).equals(field)) {
return key.getValue();
}
}
return null;
......@@ -170,8 +157,6 @@ public class AllBeanRowMapper<T> implements RowMapper<T> {
public T mapRow(ResultSet rs, int rowNumber) throws SQLException, TypeMismatchException {
Assert.state(this.mappedClass != null, "Mapped class was not specified");
T mappedObject = BeanUtils.instantiate(this.mappedClass);
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
initBeanWrapper(bw);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
......@@ -185,53 +170,36 @@ public class AllBeanRowMapper<T> implements RowMapper<T> {
value = JdbcUtils.getResultSetValue(rs, index, String.class);
}
((Map) mappedObject).put(getCamelCase(column), value);
} else if (!this.mappedIsFields.containsKey(underscoredName)) {
} else if (!this.typeField.containsKey(underscoredName)) {
continue;
} else if (!this.mappedIsFields.get(underscoredName)) {
PropertyDescriptor pd = this.mappedPropertys.get(underscoredName);
Class<?> type = pd.getPropertyType();
try {
Object value = JdbcUtils.getResultSetValue(rs, index, type);
if (configDb.isPrintMapper() && rowNumber == 0) {
Log.info(AllBeanRowMapper.class, "Mapping column '%s' to property '%s' of type %s", column, pd.getName(), type);
}
try {
bw.setPropertyValue(pd.getName(), value);
} catch (TypeMismatchException e) {
if (value == null) {
Log.info(AllBeanRowMapper.class,
"Intercepted TypeMismatchException for row %d and column '%s' with " +
"value %s when setting property '%s' of type %s on object: %s",
rowNumber, column, value, pd.getName(), type, mappedObject);
} else {
throw e;
}
}
} catch (NotWritablePropertyException ex) {
throw new DataRetrievalFailureException("Unable to map column " + column + " to property " + pd.getName(), ex);
}
MethodField pd = this.typeField.get(underscoredName);
Class<?> type;
if (pd.getField() != null) {
type = pd.getField().getType();
} else {
Field pd = this.mappedFields.get(underscoredName);
Class<?> type = pd.getType();
type = pd.getGetMethod().getReturnType();
}
Object value = null;
try {
Object value = JdbcUtils.getResultSetValue(rs, index, type);
value = JdbcUtils.getResultSetValue(rs, index, type);
if (configDb.isPrintMapper() && rowNumber == 0) {
Log.info(AllBeanRowMapper.class, "Mapping column '%s' to property '%s' of type %s", column, pd.getName(), type);
}
try {
pd.set(mappedObject, value);
} catch (IllegalAccessException e) {
ObjectHelper.setByType(mappedObject, pd, value);
} catch (TypeMismatchException e) {
if (value == null) {
Log.info(AllBeanRowMapper.class,
"Intercepted TypeMismatchException for row %d and column '%s' with " +
"value %s when setting property '%s' of type %s on object: %s",
rowNumber, column, value, pd.getName(), type, mappedObject);
rowNumber, column, StringHelper.EMPTY, pd.getName(), type, mappedObject);
} else {
throw e;
}
}
} catch (IllegalAccessException ex) {
throw new DataRetrievalFailureException("Unable to map column " + column + " to field " + pd.getName(), ex);
} catch (Exception ex) {
throw new DataRetrievalFailureException("Unable to map column " + column + " to property " + pd.getName(), ex);
}
}
}
......@@ -257,17 +225,6 @@ public class AllBeanRowMapper<T> implements RowMapper<T> {
return column;
}
/**
* Initialize the given BeanWrapper to be used for row mapping.
* To be called for each row.
* <p>The default implementation is empty. Can be overridden in subclasses.
*
* @param bw the BeanWrapper to initialize
*/
protected void initBeanWrapper(BeanWrapper bw) {
}
/**
* 缓存的处理类
*/
......
......@@ -336,7 +336,10 @@ public class ExcelConsole<T extends Object> implements DbRow<T> {
workbook = null;
}
File file = new File(this.getFileName());
if (file.exists() && file.delete()) {
if (file.exists()) {
if (!file.delete()) {
throw new CodeException("文件删除失败");
}
}
return this;
}
......
......@@ -49,7 +49,7 @@ public abstract class BaseServiceImpl<T> implements BaseService<T> {
*/
@Override
public List<String> create(T... models) {
List<String> ids = new ArrayList<String>();
List<String> ids = new ArrayList<>();
for (T t : models) {
String id = createItem(t);
ids.add(id);
......@@ -76,7 +76,7 @@ public abstract class BaseServiceImpl<T> implements BaseService<T> {
*/
@Override
public List<String> update(T... models) {
List<String> ids = new ArrayList<String>();
List<String> ids = new ArrayList<>();
for (T t : models) {
String id = updateItem(t);
ids.add(id);
......@@ -103,7 +103,7 @@ public abstract class BaseServiceImpl<T> implements BaseService<T> {
*/
@Override
public List<String> save(T... models) {
List<String> ids = new ArrayList<String>();
List<String> ids = new ArrayList<>();
for (T item : models) {
String id = saveItem(item);
ids.add(id);
......@@ -157,7 +157,7 @@ public abstract class BaseServiceImpl<T> implements BaseService<T> {
*/
@Override
public List<T> load(T... models) {
List<T> tos = new ArrayList<T>();
List<T> tos = new ArrayList<>();
for (T item : models) {
T to = loadItem(item);
tos.add(to);
......
......@@ -40,7 +40,7 @@ public class TokenHelper {
/**
* 内存缓存
*/
protected static MemoryCache<TokenData> cache = new MemoryCache<>();
protected final static MemoryCache<TokenData> cache = new MemoryCache<>();
/**
......
package com.yanzuoguang.token;
import com.yanzuoguang.util.vo.MapRow;
/**
* 动态加载Token
*
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment