Commit 1c523cd9 authored by yanzg's avatar yanzg

日期检测

parent ddb9462b
package com.yanzuoguang.util.helper;
import com.yanzuoguang.util.exception.CodeException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 参数业务逻辑校验
*/
public final class CheckerHelper {
public static final String PARAM_NOT_NULL_TIPS = "param [%s] is null";
public static final String PARAM_NOT_NUMBER = "param [%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";
public static final String PARAM_NOT_DATE_DAY = "param [%s] must be yyyyMMdd ";
public static final String PARAM_NOT_DATE = "param [%s] must be [%s]";
public static final String PARAM_NOT_PHONE = "param [%s] must be phone no";
public static final String PARAM_NOT_ID_CARD = "param [%s] must be id card";
private boolean isValid = true;
private String checkResult;
public static CheckerHelper newInstance() {
return new CheckerHelper();
}
public boolean isValid() {
return this.isValid;
}
public boolean isNotValid() {
return !isValid();
}
public void setValid(boolean valid) {
this.isValid = valid;
}
/**
* 非空检查
*
* @param paramName
* @param paramVal
* @return
*/
public CheckerHelper notBlankCheck(String paramName, Object paramVal) {
if (!isValid()) {
return this;
}
if (StringHelper.isEmpty(paramVal)) {
this.checkResult = String.format(PARAM_NOT_NULL_TIPS, paramName);
this.setValid(false);
}
return this;
}
/**
* 非空检查
*
* @param paramName
* @param list
* @return
*/
public CheckerHelper notBlankListCheck(String paramName, List list) {
if (!isValid()) {
return this;
}
if (null == list || list.isEmpty()) {
this.checkResult = String.format(PARAM_NOT_NULL_TIPS, paramName);
this.setValid(false);
}
return this;
}
/**
* 数字类型检查
*
* @param paramName
* @param paramVal
* @return
*/
public CheckerHelper notNumberCheck(String paramName, String paramVal) {
if (!isValid()) {
return this;
}
if (!StringHelper.isNumber(paramVal)) {
this.checkResult = String.format(PARAM_NOT_NUMBER, paramName, paramVal);
this.setValid(false);
}
return this;
}
/**
* 非空时数字类型检查
*
* @param paramName
* @param paramVal
* @return
*/
public CheckerHelper notNullNumberCheck(String paramName, String paramVal) {
if (!isValid()) {
return this;
}
if (!StringHelper.isEmpty(paramVal) && !StringHelper.isNumber(paramVal)) {
this.checkResult = String.format(PARAM_NOT_NUMBER, paramName, paramVal);
this.setValid(false);
}
return this;
}
/**
* 检验IP是否合法
*
* @param paramName
* @param paramVal
* @return
*/
public CheckerHelper notIpCheck(String paramName, String paramVal) {
if (!isValid()) {
return this;
}
String rexp = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
if (!StringHelper.isEmpty(paramVal) && !paramVal.matches(rexp)) {
this.checkResult = String.format(PARAM_NOT_NUMBER, paramName, paramVal);
this.setValid(false);
}
return this;
}
public CheckerHelper notDateCheck(String paramName, String paramVal, String queryType) {
if (!isValid()) {
return this;
}
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 ("day".equals(queryType)) {
eL = "[0-9]{4}[0-9]{2}[0-9]{2}";
msg = PARAM_NOT_DATE_DAY;
} else if ("month".equals(queryType)) {
eL = "[0-9]{4}[0-9]{2}";
msg = PARAM_NOT_DATE_MONTH;
}
Pattern p = Pattern.compile(eL);
Matcher m = p.matcher(paramVal);
boolean dateFlag = m.matches();
if (!StringHelper.isEmpty(paramVal) && !dateFlag) {
this.checkResult = String.format(msg, paramName, paramVal);
this.setValid(false);
}
return this;
}
/**
* 手机号校验
* 仅支持大陆手机号码校验
*
* @param paramVal
* @return
*/
public CheckerHelper checkPhoneNo(String paramName, String paramVal) {
if (!isValid()) {
return this;
}
if (paramVal == null || paramVal.length() < 1) {
return this;
}
String regExp = "^1\\d{10}$";
Pattern p = Pattern.compile(regExp);
if (!p.matcher(paramVal).matches()) {
this.checkResult = String.format(PARAM_NOT_PHONE, paramName);
this.setValid(false);
}
return this;
}
/**
* 长度检查
*
* @param paramName
* @param paramVal
* @param length
* @return
*/
public CheckerHelper paramLengthCheck(String paramName, String paramVal, int length) {
if (!isValid())
return this;
if (!StringHelper.isEmpty(paramVal) && length < paramVal.length()) {
this.checkResult = String.format(PARAM_OVER_MAX_LENGTH, paramName) + length;
this.setValid(false);
}
return this;
}
/**
* 日期字符串
*
* @param paramName 参数名称
* @param paramVal 参数值
* @param formatStr 日期格式
* @return
*/
public CheckerHelper paramDateCheck(String paramName, String paramVal, String formatStr) {
if (!isValid()) {
return this;
}
if (StringHelper.isEmpty(paramVal)) {
return this;
}
try {
if (!StringHelper.isEmpty(formatStr)) {
SimpleDateFormat format = new SimpleDateFormat(formatStr);
format.parse(paramVal);
} else {
DateAutoHelper.getAutoDate(formatStr);
}
} catch (ParseException e) {
this.checkResult = String.format(PARAM_NOT_DATE, paramName, formatStr);
this.setValid(false);
}
return this;
}
/**
* 检测身份证
*
* @param paramName 参数名称
* @param paramVal 参数值
* @return
*/
public CheckerHelper checkIdCard(String paramName, String paramVal) {
if (!isValid()) {
return this;
}
if (StringHelper.isEmpty(paramVal)) {
return this;
}
String regExp = "^\\d{6}(18|19|20)?\\d{2}(0[1-9]|1[012])(0[1-9]|[12]\\d|3[01])\\d{3}(\\d|X)$";
Pattern p = Pattern.compile(regExp);
if (!p.matcher(paramVal.toUpperCase()).matches()) {
this.checkResult = String.format(PARAM_NOT_ID_CARD, paramName);
this.setValid(false);
}
return this;
}
/**
* 检测结果是否异常
*/
public void checkException() {
if (!StringHelper.isEmpty(this.checkResult)) {
throw new CodeException(this.checkResult);
}
}
/**
* 获取检测结果的错误信息
*
* @return
*/
public String getCheckResult() {
return this.checkResult;
}
}
...@@ -9,6 +9,8 @@ import java.util.Arrays; ...@@ -9,6 +9,8 @@ import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** /**
* 字符串帮主类 * 字符串帮主类
...@@ -95,6 +97,128 @@ public class StringHelper { ...@@ -95,6 +97,128 @@ public class StringHelper {
return EMPTY; return EMPTY;
} }
/**
* 检测值是否为数字
*
* @param from 需要检测的值
* @return 检测结果
*/
public static boolean isNumber(String from) {
if (StringHelper.isEmpty(from)) {
return false;
}
final char[] chars = from.toCharArray();
int sz = chars.length;
boolean hasExp = false;
boolean hasDecPoint = false;
boolean allowSigns = false;
boolean foundDigit = false;
// deal with any possible sign up front
final int start = (chars[0] == '-') ? 1 : 0;
if (sz > start + 1 && chars[start] == '0') { // leading 0
if (
(chars[start + 1] == 'x') ||
(chars[start + 1] == 'X')
) { // leading 0x/0X
int i = start + 2;
if (i == sz) {
return false; // str == "0x"
}
// checking hex (it can't be anything else)
for (; i < chars.length; i++) {
if ((chars[i] < '0' || chars[i] > '9')
&& (chars[i] < 'a' || chars[i] > 'f')
&& (chars[i] < 'A' || chars[i] > 'F')) {
return false;
}
}
return true;
} else if (Character.isDigit(chars[start + 1])) {
// leading 0, but not hex, must be octal
int i = start + 1;
for (; i < chars.length; i++) {
if (chars[i] < '0' || chars[i] > '7') {
return false;
}
}
return true;
}
}
sz--; // don't want to loop to the last char, check it afterwords
// for type qualifiers
int i = start;
// loop to the next to last char or to the last char if we need another digit to
// make a valid number (e.g. chars[0..5] = "1234E")
while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) {
if (chars[i] >= '0' && chars[i] <= '9') {
foundDigit = true;
allowSigns = false;
} else if (chars[i] == '.') {
if (hasDecPoint || hasExp) {
// two decimal points or dec in exponent
return false;
}
hasDecPoint = true;
} else if (chars[i] == 'e' || chars[i] == 'E') {
// we've already taken care of hex.
if (hasExp) {
// two E's
return false;
}
if (!foundDigit) {
return false;
}
hasExp = true;
allowSigns = true;
} else if (chars[i] == '+' || chars[i] == '-') {
if (!allowSigns) {
return false;
}
allowSigns = false;
foundDigit = false; // we need a digit after the E
} else {
return false;
}
i++;
}
if (i < chars.length) {
if (chars[i] >= '0' && chars[i] <= '9') {
// no type qualifier, OK
return true;
}
if (chars[i] == 'e' || chars[i] == 'E') {
// can't have an E at the last byte
return false;
}
if (chars[i] == '.') {
if (hasDecPoint || hasExp) {
// two decimal points or dec in exponent
return false;
}
// single trailing decimal point after non-exponent is ok
return foundDigit;
}
if (!allowSigns
&& (chars[i] == 'd'
|| chars[i] == 'D'
|| chars[i] == 'f'
|| chars[i] == 'F')) {
return foundDigit;
}
if (chars[i] == 'l'
|| chars[i] == 'L') {
// not allowing L with an exponent or decimal point
return foundDigit && !hasExp && !hasDecPoint;
}
// last character is illegal
return false;
}
// allowSigns is true iff the val ends in 'E'
// found digit it to make sure weird stuff like '.' and '1E-' doesn't pass
return !allowSigns && foundDigit;
}
//------------------------------------------------------ 转换值 ----------------------------------------------------------------------- //------------------------------------------------------ 转换值 -----------------------------------------------------------------------
/** /**
......
//package com.yanzuoguang.cloud.aop;
//
//import com.tourbida.sys.common.AbstractValidateAspect;
//import com.tourbida.sys.exception.CodeException;
//import com.tourbida.sys.vo.ResponseResult;
//import com.tourbida.sys.vo.ResponseResultBuilder;
//import com.tourbida.sys.web.BaseController;
//import org.aspectj.lang.ProceedingJoinPoint;
//import org.aspectj.lang.annotation.Around;
//import org.aspectj.lang.annotation.Aspect;
//import org.aspectj.lang.annotation.Pointcut;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.stereotype.Component;
//
///**
// * 接口切面,用于验证接口回调返回参数
// */
//@Aspect
//@Component
//public class FeignAspect extends AbstractValidateAspect {
//
// private static final Logger logger = LoggerFactory.getLogger(FeignAspect.class);
//
// /**
// * AOP的表达式
// */
// @Pointcut("execution(* com.panding..feign..*(..))")
// public void feignAspect() {
// }
//
// /**
// * 执行环形切面
// *
// * @param joinPoint
// * @return
// */
// @Around(value = "feignAspect()")
// public Object requestFeignAround(ProceedingJoinPoint joinPoint) throws Throwable {
// String name = joinPoint.getSignature().getName();
// Object result = null;
// long start = System.currentTimeMillis();
// try {
// logger.info("=================[ {} ] feign params is {} =================", name, joinPoint.getArgs());
// result = joinPoint.proceed();
//
// // 假如是标准格式,则验证接口是否成功,不成功则抛出异常
// if (result instanceof ResponseResult) {
// ResponseResult responseResult = (ResponseResult) result;
// if (!ResponseResultBuilder.SUCCESS.equals(responseResult.getCode())) {
// throw new CodeException(responseResult.getCode(), responseResult.getMessage());
// }
// }
// return result;
// } catch (CodeException ex) {
// logger.info("=================[ {} ] feign is error {} =================", name, ex);
// result = new ResponseResult(ex.getCode(), ex.getMessage());
// throw ex;
// } catch (Exception e) {
// ResponseResult responseResult = BaseController.getError(logger, "=================[ " + name + " ] feign is error {} =================", e);
// result = responseResult;
// throw new CodeException(responseResult.getCode(), responseResult.getMessage());
// } finally {
// // 记录服务调用时间,请求日志
// long end = System.currentTimeMillis();
// logger.info("=================[ {} ] feign time ({})ms, result is {} =================", name, (end - start), result);
// }
// }
//
//
//}
//package com.yanzuoguang.cloud.aop;
//
//import java.util.Date;
//
///**
// * 请求缓存的数据
// */
//public class RequestCacheResult {
//
// /**
// * 构造函数
// */
// public RequestCacheResult(String reqID) {
// this.date = new Date();
// this.reqID = reqID;
// this.result = null;
// }
//
// /**
// * 请求编号
// */
// private String reqID;
//
// /**
// * 结果
// */
// private Object result;
//
// /**
// * 时间
// */
// private Date date;
//
// /**
// * 获取毫秒数
// *
// * @return
// */
// public long getMillsecond() {
// return new Date().getTime() - date.getTime();
// }
//
// /**
// * 获取结果
// *
// * @return
// */
// public Object getResult() {
// return result;
// }
//
// /**
// * 返回结果
// *
// * @param result
// */
// public void setResult(Object result) {
// this.date = new Date();
// this.result = result;
// }
//}
//package com.yanzuoguang.cloud.aop;
//
//import com.alibaba.fastjson.JSON;
//import com.tourbida.sys.common.AbstractValidateAspect;
//import com.tourbida.sys.common.utils.ThreadNext;
//import com.tourbida.sys.core.Config;
//import com.tourbida.sys.core.cache.LocalCacheData;
//import com.tourbida.sys.core.util.JSONHelper;
//import com.tourbida.sys.core.util.Log;
//import com.tourbida.sys.core.util.ObjectHelper;
//import com.tourbida.sys.core.util.StringHelper;
//import com.tourbida.sys.feign.LogFeign;
//import com.tourbida.sys.vo.LogVo;
//import com.tourbida.sys.vo.ResponseResult;
//import com.tourbida.sys.vo.ResponseResultBuilder;
//import com.tourbida.sys.web.BaseController;
//import org.aspectj.lang.ProceedingJoinPoint;
//import org.aspectj.lang.Signature;
//import org.aspectj.lang.annotation.Around;
//import org.aspectj.lang.annotation.Aspect;
//import org.aspectj.lang.annotation.Pointcut;
//import org.aspectj.lang.reflect.MethodSignature;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Component;
//
//import javax.servlet.ServletRequest;
//import javax.servlet.ServletResponse;
//import java.lang.reflect.Method;
//import java.lang.reflect.Type;
//import java.util.concurrent.LinkedBlockingQueue;
//
///**
// * LogsAspect(接口请求日志切面)
// *
// * @author: Kang
// * @time: 2018年04月25日 11:43
// */
//@Aspect
//@Component
//public class WebAspect extends AbstractValidateAspect implements ThreadNext.Next {
//
// private static final Logger logger = LoggerFactory.getLogger(WebAspect.class);
//
// @Value("${spring.application.name}")
// private String applicationName;
//
// @Value("${config.logAll:false}")
// private boolean logAll = false;
//
// @Value("${config.cacheTime:120}")
// private int cacheTime = 120;
//
// private LogFeign logInterFeign;
//
// /**
// * 缓存队列
// */
// private volatile LinkedBlockingQueue<LogVo> cache = new LinkedBlockingQueue<LogVo>();
//
// // 缓存的每次请求的结果
// private LocalCacheData<RequestCacheResult> _cacheResult = new LocalCacheData<RequestCacheResult>(cacheTime);
//
// public WebAspect() {
// ThreadNext.start(logger, this, "save log error");
// }
//
// /**
// * exec aop point aspect
// */
// @Pointcut("execution(* com.tourbida..web..*(..))")
// public void webAspect() {
// }
//
// /**
// * 获取返回的至类型
// *
// * @param joinPoint
// * @return
// * @throws NoSuchMethodException
// */
// private Type getReturnType(ProceedingJoinPoint joinPoint) {
// //获取返回值类型
// Signature s = joinPoint.getSignature();
// MethodSignature ms = (MethodSignature) s;
// Method m = ms.getMethod();
// Type t = m.getAnnotatedReturnType().getType();
// return t;
// }
//
// /**
// * 执行环形切面
// *
// * @param joinPoint
// * @return
// */
// @Around(value = "webAspect()")
// public Object requestWebAround(ProceedingJoinPoint joinPoint) throws Throwable {
// Log.threadBegin();
// ResponseResult responseResult = null; // 用户数据库记录
// long start = System.currentTimeMillis();
// String name = joinPoint.getSignature().getName();
// try {
// logger.info("=================[ {} ] request params is {} =================", name, joinPoint.getArgs());
// Object result = executeMethod(joinPoint, name);
// if (result instanceof ResponseResult) {
// responseResult = (ResponseResult) result;
// } else {
// responseResult = ResponseResult.result(result);
// }
// return result;
// } catch (Exception e) {
// responseResult = BaseController.getError(logger, "=================[ " + name + " ] is error {} =================", e);
// if (getReturnType(joinPoint).getTypeName().indexOf(ResponseResult.class.getName()) > -1) {
// return responseResult;
// } else {
// throw e;
// }
// } finally {
// long end = System.currentTimeMillis();
// Log.threadCommit();
// saveInterLogs(joinPoint, responseResult);
// logger.info("=================[ {} ] time ({})ms, result is {} =================", name, (end - start), responseResult);
// }
// }
//
// private Object executeMethod(ProceedingJoinPoint joinPoint, String name) throws Throwable {
// if (joinPoint.getArgs().length != 1
// || joinPoint.getArgs().length == 1 &&
// (joinPoint.getArgs()[0] instanceof ServletResponse || joinPoint.getArgs()[0] instanceof ServletRequest)
// ) {
// return joinPoint.proceed();
// } else {
// // 获取请求编号
// Object firstArgs = joinPoint.getArgs().length > 0 ? joinPoint.getArgs()[0] : null;
// String reqId = StringHelper.GetLastString(
// ObjectHelper.GetString(firstArgs, "__req"),
// ObjectHelper.GetString(firstArgs, "reqId"),
// ObjectHelper.GetString(firstArgs, "repeatCode"),
// ObjectHelper.GetString(firstArgs, "thirdOrderId")
// );
// if (StringHelper.IsEmpty(reqId)) {
// reqId = StringHelper.md5(JSONHelper.SerializeObject(firstArgs));
// } else {
// // 请求编号和公司编号挂钩
// reqId = StringHelper.GetID(ObjectHelper.GetString(firstArgs, "companyId"), reqId);
// }
// String reqFull = StringHelper.GetID(reqId, getHttpRequestUrl());
// RequestCacheResult req = _cacheResult.get(reqFull, new RequestCacheResult(reqFull));
// // 缓存的键值对
// if (req.getResult() == null) {
// synchronized (req) {
// if (req.getResult() == null) {
// try {
// req.setResult(joinPoint.proceed());
// } catch (Exception ex) {
// req.setResult(ex);
// }
// }
// }
// }
// Object result = req.getResult();
// if (result instanceof Throwable) {
// throw (Throwable) result;
// }
// return result;
// }
// }
//
// /**
// * deal with inter api logs
// *
// * @param joinPoint 请求参数
// * @param responseResult 返回参数
// */
// private void saveInterLogs(ProceedingJoinPoint joinPoint, ResponseResult responseResult) {
// // 日志请求不记录,防止死循环递归
// if (applicationName.indexOf("log") >= 0) {
// return;
// }
// // 正常请求不记录
// if (!logAll && responseResult.getCode() == ResponseResultBuilder.SUCCESS) {
// return;
// }
// LogVo logVo = initLogInterVo(getHttpRequestUrl(), joinPoint, responseResult);
// addLog(logVo);
// }
//
// /**
// * 添加日志到缓存中,并不是立即添加,而是通过线程执行,防止对环境造成影响
// *
// * @param logVo
// */
// public void addLog(LogVo logVo) {
// cache.add(logVo);
// }
//
// /**
// * 初始化日志Vo
// *
// * @param url 请求路径
// * @param joinPoint 请求参数
// * @param responseResult 返回参数
// * @return
// */
// private LogVo initLogInterVo(String url, ProceedingJoinPoint joinPoint, ResponseResult responseResult) {
// LogVo logInterVo = new LogVo();
// logInterVo.setLogId(StringHelper.GetNewID());
// logInterVo.setLogSources(applicationName);//平台名
// logInterVo.setInterUrl(url);//请求URL
// Object para = joinPoint.getArgs();
// if (joinPoint.getArgs().length == 1) {
// para = joinPoint.getArgs()[0];
// }
// logInterVo.setContent(JSON.toJSONString(para));//请求参数
// logInterVo.setResult(JSON.toJSONString(responseResult));//返回参数
// logInterVo.setStatus(responseResult.getCode() == ResponseResultBuilder.SUCCESS ? 1 : 0);
// return logInterVo;
// }
//
// /**
// * 执行下一个函数,出现异常会继续执行
// *
// * @return 是否继续执行
// */
// @Override
// public boolean next() throws Exception {
// while (cache.size() > 0) {
// LogVo item = cache.poll();
// if (item != null) {
// if (logInterFeign == null) {
// logInterFeign = Config.Context.getBean(LogFeign.class);
// }
// logInterFeign.saveInterLogs(item);
// }
// }
// return true;
// }
//
// /**
// * 沉睡时间
// *
// * @return
// */
// @Override
// public int getNextTime() {
// return 1000;
// }
//}
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