Commit 216cf8e3 by guojuxing

service验证结构调整

parent 49e724e7
......@@ -35,6 +35,17 @@
<artifactId>gic-enterprise-base-api</artifactId>
<version>${gic-enterprise-base-api}</version>
</dependency>
<!--参数验证-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.1-b09</version>
</dependency>
</dependencies>
<build>
......
package com.gic.store.dto;
import com.gic.store.constant.StoreGroupConstant;
import com.gic.store.service.StoreStrategyApiService;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Date;
......@@ -10,34 +17,44 @@ import java.util.Date;
public class StoreStrategyDTO implements Serializable{
private static final long serialVersionUID = -4683081402308681202L;
public StoreStrategyDTO() {
}
/**
*
*/
@NotNull(message = "主键不能为空", groups = {StoreStrategyApiService.ModifyStoreStrategy.class})
private Integer strategyId;
/**
* 策略名称
*/
@NotBlank(message = "策略名称不能为空", groups = {StoreStrategyApiService.SaveStoreStrategy.class, StoreStrategyApiService.ModifyStoreStrategy.class})
private String strategyName;
/**
*
*/
@NotNull(message = "企业ID不能为空", groups = {StoreStrategyApiService.SaveStoreStrategy.class})
private Integer enterpriseId;
/**
* 门店域id
*/
@NotNull(message = "门店域不能为空", groups = {StoreStrategyApiService.SaveStoreStrategy.class, StoreStrategyApiService.ModifyStoreStrategy.class})
private Integer storeRegionId;
/**
* 门店分组条件,json数组
*/
@NotBlank(message = "门店属性条件配置不能为空", groups = {StoreStrategyApiService.SaveStoreStrategy.class, StoreStrategyApiService.ModifyStoreStrategy.class})
private String conditions;
/**
* 策略命中值;如果type为门店分组策略,对应分组id;否则为门店启用和不启用值
*/
@NotBlank(message = "策略命中值不能为空", groups = {StoreStrategyApiService.SaveStoreStrategy.class, StoreStrategyApiService.ModifyStoreStrategy.class})
private String targetValue;
/**
......@@ -58,6 +75,9 @@ public class StoreStrategyDTO implements Serializable{
/**
* 策略类型,1门店状态策略, 2门店分组策略
*/
@NotNull(message = "策略类型不能为空", groups = {StoreStrategyApiService.SaveStoreStrategy.class})
@Min(value = StoreGroupConstant.STORE_STRATEGY_TYPE, message = "最小值不能小于{value}", groups = {StoreStrategyApiService.SaveStoreStrategy.class})
@Max(value = StoreGroupConstant.STORE_GROUP_STRATEGY_TYPE, message = "最大值不能大于{value}", groups = {StoreStrategyApiService.SaveStoreStrategy.class})
private Integer strategyType;
/**
......
......@@ -35,7 +35,7 @@ public interface StoreFieldSelectApiService {
*/
ServiceResponse<Integer> setStoreFieldSelectSort(int storeFieldSelectId, int setValue);
ServiceResponse<Integer> delete(int storeFieldSelectId);
ServiceResponse<Integer> delete(String storeFieldSelectIds);
ServiceResponse<Integer> edit(StoreFieldSelectDTO storeFieldSelectDTO);
......
......@@ -4,6 +4,7 @@ import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.store.dto.StoreStrategyDTO;
import javax.validation.GroupSequence;
import java.util.List;
/**
......@@ -12,6 +13,7 @@ import java.util.List;
*/
public interface StoreStrategyApiService {
@interface SaveStoreStrategy{}
/**
* 新增 策略数据
* @param storeStrategyDTO
......@@ -27,6 +29,7 @@ public interface StoreStrategyApiService {
*/
ServiceResponse<Integer> deleteStoreStrategy(int strategyId);
@interface ModifyStoreStrategy{}
/**
* 修改策略
* @param storeStrategyDTO
......
package com.gic.store.utils.valid;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.enterprise.error.ErrorCode;
import org.hibernate.validator.HibernateValidator;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Iterator;
import java.util.Set;
/**
* @author guojx
* @date 2019/7/9 10:49 AM
*/
public class ValidUtil {
/**
* 开启快速结束模式 failFast (true)
*/
private static Validator failFastValidator = Validation.byProvider(HibernateValidator.class)
.configure()
.failFast(true)
.buildValidatorFactory().getValidator();
/**
* 全部校验
*/
private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
private ValidUtil() {
}
public static <T> ServiceResponse fastFailValidate(T obj, Class<?>... groups) {
Set<ConstraintViolation<T>> constraintViolations = failFastValidator.validate(obj, groups);
if (constraintViolations.size() > 0) {
String paramName = constraintViolations.iterator().next().getPropertyPath().toString();
String paramError = constraintViolations.iterator().next().getMessage();
return ServiceResponse.failure(ErrorCode.ERR_5.getCode(), getFailFastMsg(paramName, paramError));
}
return ServiceResponse.success();
}
public static <T> ServiceResponse allCheckValidate(T obj, Class<?>... groups) {
Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj, groups);
if (constraintViolations.size() > 0) {
StringBuilder errorMessages = new StringBuilder();
Iterator<ConstraintViolation<T>> iterator = constraintViolations.iterator();
while (iterator.hasNext()) {
ConstraintViolation<T> violation = iterator.next();
errorMessages.append(getFailFastMsg(violation.getPropertyPath().toString(), violation.getMessage()))
.append(",");
}
return ServiceResponse.failure(ErrorCode.ERR_5.getCode(), errorMessages.toString());
}
return ServiceResponse.success();
}
public static String getFailFastMsg(String paramName, String paramError) {
return String.format("%s:%s", paramName, paramError);
}
}
......@@ -14,6 +14,8 @@ public interface TabStoreFieldSelectMapper {
*/
int deleteByPrimaryKey(Integer storeFieldSelectId);
int deleteBatch(@Param("storeFieldSelectIdList") List<Integer> storeFieldSelectIdList);
/**
* 插入一条记录
*
......
......@@ -3,6 +3,9 @@ package com.gic.store.service;
import com.gic.store.dto.StoreFieldSelectDTO;
import com.gic.store.entity.TabStoreFieldSelect;
import com.github.pagehelper.Page;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author guojx
......@@ -57,6 +60,8 @@ public interface StoreFieldSelectService {
int delete(int storeFieldSelectId);
int deleteBatch(List<Integer> storeFieldSelectIdList);
int edit(int storeFieldSelectId, String storeFieldSelectName, String storeFieldSelectCode);
/**
......
......@@ -88,6 +88,11 @@ public class StoreFieldSelectServiceImpl implements StoreFieldSelectService{
}
@Override
public int deleteBatch(List<Integer> storeFieldSelectIdList) {
return tabStoreFieldSelectMapper.deleteBatch(storeFieldSelectIdList);
}
@Override
public int edit(int storeFieldSelectId, String storeFieldSelectName, String storeFieldSelectCode) {
TabStoreFieldSelect tabStoreFieldSelect = new TabStoreFieldSelect();
tabStoreFieldSelect.setStoreFieldSelectId(storeFieldSelectId);
......
......@@ -14,6 +14,7 @@ import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
......@@ -91,15 +92,13 @@ public class StoreFieldSelectApiServiceImpl implements StoreFieldSelectApiServic
}
@Override
public ServiceResponse<Integer> delete(int storeFieldSelectId) {
TabStoreFieldSelect tabStoreFieldSelect = storeFieldSelectService.getStoreFieldSelectById(storeFieldSelectId);
if (tabStoreFieldSelect == null) {
return ServiceResponse.failure(ErrorCode.ERR_5.getCode(), "主键错误,查询不到数据");
}
if (storeExtendService.storeExtendHasStoreFieldSelect(tabStoreFieldSelect.getStoreFieldId(), storeFieldSelectId)) {
return ServiceResponse.failure(ErrorCode.ERR_5.getCode(), "属性值 " + tabStoreFieldSelect.getStoreFieldSelectName() + "在使用中,不允许删除");
public ServiceResponse<Integer> delete(String storeFieldSelectIds) {
String[] storeFieldSelectArr = storeFieldSelectIds.split(",");
ServiceResponse validResult = validDelete(storeFieldSelectArr);
if (!validResult.isSuccess()) {
return validResult;
}
return ServiceResponse.success(storeFieldSelectService.delete(storeFieldSelectId));
return ServiceResponse.success(storeFieldSelectService.deleteBatch(transferStringToInteger(storeFieldSelectArr)));
}
@Override
......@@ -163,4 +162,26 @@ public class StoreFieldSelectApiServiceImpl implements StoreFieldSelectApiServic
return ServiceResponse.success();
}
private List<Integer> transferStringToInteger(String[] storeFieldSelectArr) {
List<Integer> list = new ArrayList<>(storeFieldSelectArr.length);
for (String str : storeFieldSelectArr) {
list.add(Integer.parseInt(str));
}
return list;
}
private ServiceResponse validDelete(String[] storeFieldSelectArr) {
for (String select : storeFieldSelectArr) {
TabStoreFieldSelect tabStoreFieldSelect = storeFieldSelectService.getStoreFieldSelectById(Integer.parseInt(select));
if (tabStoreFieldSelect == null) {
return ServiceResponse.failure(ErrorCode.ERR_5.getCode(), "主键错误,查询不到数据");
}
if (storeExtendService.storeExtendHasStoreFieldSelect(tabStoreFieldSelect.getStoreFieldId(), Integer.parseInt(select))) {
return ServiceResponse.failure(ErrorCode.ERR_5.getCode(), "属性值 " + tabStoreFieldSelect.getStoreFieldSelectName() + "在使用中,不允许删除");
}
}
return ServiceResponse.success();
}
}
......@@ -6,9 +6,11 @@ import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.PageHelperUtils;
import com.gic.store.dto.StoreRegionDTO;
import com.gic.store.dto.StoreStrategyDTO;
import com.gic.store.entity.TabStoreRegion;
import com.gic.store.service.StoreRegionApiService;
import com.gic.store.service.StoreRegionService;
import com.gic.store.service.StoreStrategyApiService;
import com.gic.store.utils.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
......@@ -25,6 +27,8 @@ public class StoreRegionApiServiceImpl implements StoreRegionApiService {
@Autowired
private StoreRegionService storeRegionService;
@Autowired
private StoreStrategyApiService storeStrategyApiService;
@Override
public ServiceResponse<Integer> saveOrUpdateStoreRegion(Integer enterpriseId, String regionCode, String regionName, Integer regionId) {
......@@ -59,8 +63,12 @@ public class StoreRegionApiServiceImpl implements StoreRegionApiService {
@Override
public ServiceResponse<List<StoreRegionDTO>> listStoreRegion(Integer enterpriseId, String search) {
List<TabStoreRegion> list = storeRegionService.listStoreRegion(enterpriseId, search);
return ServiceResponse.success(EntityUtil.changeEntityListByOrika(StoreRegionDTO.class, list));
StoreStrategyDTO dto = new StoreStrategyDTO();
dto.setTargetValue("2");
ServiceResponse test = storeStrategyApiService.saveStoreStrategy(dto);
return test;
// List<TabStoreRegion> list = storeRegionService.listStoreRegion(enterpriseId, search);
// return ServiceResponse.success(EntityUtil.changeEntityListByOrika(StoreRegionDTO.class, list));
}
@Override
......
......@@ -15,6 +15,7 @@ import com.gic.store.service.StoreService;
import com.gic.store.service.StoreStrategyApiService;
import com.gic.store.service.StoreStrategyService;
import com.gic.store.utils.ErrorCode;
import com.gic.store.utils.valid.ValidUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
......@@ -38,23 +39,9 @@ public class StoreStrategyApiServiceImpl implements StoreStrategyApiService{
@Override
public ServiceResponse<Integer> saveStoreStrategy(StoreStrategyDTO storeStrategyDTO) {
if (StringUtils.isBlank(storeStrategyDTO.getStrategyName())) {
return ServiceResponse.failure(ErrorCode.ERR_5.getCode(), "策略名称不能为空");
}
if (storeStrategyDTO.getStoreRegionId() == null) {
return ServiceResponse.failure(ErrorCode.ERR_5.getCode(), "门店域不能为空");
}
if (storeStrategyDTO.getEnterpriseId() == null) {
return ServiceResponse.failure(ErrorCode.ERR_5.getCode(), "企业ID不能为空");
}
if (StringUtils.isBlank(storeStrategyDTO.getTargetValue())) {
return ServiceResponse.failure(ErrorCode.ERR_5.getCode(), "策略命中值不能为空");
}
if (storeStrategyDTO.getStrategyType() == null) {
return ServiceResponse.failure(ErrorCode.ERR_5.getCode(), "策略类型不能为空");
}
if (StringUtils.isBlank(storeStrategyDTO.getConditions())) {
return ServiceResponse.failure(ErrorCode.ERR_5.getCode(), "门店属性条件配置不能为空");
ServiceResponse validParam = ValidUtil.allCheckValidate(storeStrategyDTO, SaveStoreStrategy.class);
if (!validParam.isSuccess()) {
return validParam;
}
if (storeStrategyDTO.getStrategyType() == StoreGroupConstant.STORE_STRATEGY_TYPE) {
......@@ -97,16 +84,14 @@ public class StoreStrategyApiServiceImpl implements StoreStrategyApiService{
@Override
public ServiceResponse<Integer> modifyStoreStrategy(StoreStrategyDTO storeStrategyDTO) {
ServiceResponse validParam = ValidUtil.allCheckValidate(storeStrategyDTO, SaveStoreStrategy.class);
if (!validParam.isSuccess()) {
return validParam;
}
TabStoreStrategy storeStrategy = storeStrategyService.getStoreStrategyById(storeStrategyDTO.getStrategyId());
if (storeStrategy == null) {
return ServiceResponse.failure(ErrorCode.ERR_5.getCode(), "策略主键ID错误,查询不到数据");
}
if (StringUtils.isBlank(storeStrategyDTO.getConditions())) {
return ServiceResponse.failure(ErrorCode.ERR_5.getCode(), "门店属性条件配置不能为空");
}
if (StringUtils.isBlank(storeStrategyDTO.getTargetValue())) {
return ServiceResponse.failure(ErrorCode.ERR_5.getCode(), "策略命中值不能为空");
}
String conditions = storeStrategyDTO.getConditions();
//验证conditions合法性
if (isConditionsSizeOver(conditions)) {
......
package com.gic.store.utils.custom;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.validation.Validation;
import org.apache.dubbo.validation.Validator;
/**
* @author guojx
* @date 2019/7/10 11:36 AM
*/
public class CustomValidation implements Validation{
@Override
public Validator getValidator(URL url) {
return new CustomValidator(url);
}
}
package com.gic.store.utils.custom;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.validation.Validator;
import org.apache.dubbo.validation.support.jvalidation.JValidator;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.Set;
/**
* @author guojx
* @date 2019/7/10 11:37 AM
*/
public class CustomValidator extends JValidator implements Validator{
private final Class<?> clazz;
public CustomValidator(URL url) {
super(url);
this.clazz = ReflectUtils.forName(url.getServiceInterface());
}
@Override
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception {
try{
super.validate(methodName,parameterTypes,arguments);
}catch (ConstraintViolationException e){
//防止客户端进行验证报错
//throw new ValidationException(constraintMessage(clazz.getName(),methodName,e.getConstraintViolations()));
}
}
private String constraintMessage(String className,String methodName,Set<ConstraintViolation<?>> violations){
JSONObject json = new JSONObject();
json.put("service",className);
json.put("method",methodName);
JSONArray details = new JSONArray();
for(ConstraintViolation violation : violations){
JSONObject detail = new JSONObject();
detail.put("bean",violation.getRootBean().getClass().getName());
detail.put("property",violation.getPropertyPath().toString());
detail.put("message",violation.getMessage());
details.add(detail);
}
json.put("details",details);
return json.toString();
}
}
custom=com.gic.store.utils.custom.CustomValidation
\ No newline at end of file
......@@ -33,7 +33,7 @@
<!--分组策略-->
<dubbo:service interface="com.gic.store.service.StoreStrategyApiService" ref="storeStrategyApiService" timeout="60000" />
<dubbo:service interface="com.gic.store.service.StoreStrategyApiService" ref="storeStrategyApiService" timeout="60000" validation="custom"/>
<!--门店导入-->
<dubbo:service interface="com.gic.store.service.StoreImportApiService" ref="storeImportApiService" timeout="60000" />
......
......@@ -201,4 +201,13 @@
and store_field_select_id &lt;&gt; #{storeFieldSelectId}
</if>
</select>
<delete id="deleteBatch" parameterType="java.lang.Integer">
delete from tab_store_field_select
where
store_field_select_id in
<foreach collection="storeFieldSelectIdList" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</delete>
</mapper>
\ No newline at end of file
......@@ -331,14 +331,11 @@ public class StoreFieldController {
@RequestMapping("/delete-store-field-select")
public RestResponse editStoreFieldSelect(String storeFieldSelectIds) {
if (StringUtils.isBlank(storeFieldSelectIds)) {
return RestResponse.failure(ErrorCode.ERR_5.getCode(), "主键不能为空");
return RestResponse.failure(ErrorCode.ERR_5.getCode(), "storeFieldSelectIds:不能为空");
}
String[] ids = storeFieldSelectIds.split(",");
for (String str : ids) {
ServiceResponse result = storeFieldSelectApiService.delete(Integer.parseInt(str));
if (!result.isSuccess()) {
return RestResponse.failure(result.getCode(), result.getMessage());
}
ServiceResponse result = storeFieldSelectApiService.delete(storeFieldSelectIds);
if (!result.isSuccess()) {
return RestResponse.failure(result.getCode(), result.getMessage());
}
return RestResponse.success();
}
......
......@@ -91,6 +91,21 @@ public class StoreStrategyController {
return RestResponse.success(result);
}
@RequestMapping("/save-store-strategy-test")
public RestResponse saveStoreStrategy() {
StoreStrategyDTO dto = new StoreStrategyDTO();
ServiceResponse result = storeStrategyApiService.saveStoreStrategy(dto);
return RestResponse.success(result);
}
@RequestMapping("/modify-store-strategy-test")
public RestResponse modifyStoreStrategy() {
StoreStrategyDTO dto = new StoreStrategyDTO();
dto.setStrategyId(12);
ServiceResponse result = storeStrategyApiService.modifyStoreStrategy(dto);
return RestResponse.success(result);
}
@RequestMapping("/save-store-strategy")
public RestResponse saveStoreStrategy(@Validated({StoreStrategyQO.SaveValidView.class, StoreStrategyQO.StoreStrategyTypeValidView.class})
StoreStrategyQO storeStrategyQO) {
......
......@@ -13,9 +13,12 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Set;
/**
* 全局异常处理类
......@@ -30,7 +33,7 @@ public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public RestResponse controllerException(HttpServletResponse response, Exception ex) {
logger.error("err", ex);
RestResponse failureResponse = getRestResponse(ErrorCode.ERR_9999.getCode(), StoreGroupErrorEnum.Error.getMessage());
RestResponse failureResponse = getRestResponse(ErrorCode.ERR_9999.getCode(), ErrorCode.ERR_9999.getMsg());
StringBuilder sb = new StringBuilder();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (PrintWriter printWriter = new PrintWriter(baos)) {
......@@ -67,6 +70,15 @@ public class GlobalExceptionHandler {
return getRestResponse(StoreGroupErrorEnum.Error.getCode(), errorMessage.toString());
}
@ResponseBody
@ExceptionHandler(ConstraintViolationException.class)
public RestResponse constraintViolationException(ConstraintViolationException e) {
Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
String paramName = constraintViolations.iterator().next().getPropertyPath().toString();
String paramError = constraintViolations.iterator().next().getMessage();
return getRestResponse(com.gic.enterprise.error.ErrorCode.ERR_5.getCode(), getFailFastMsg(paramName, paramError));
}
/**
* 自定义异常统一处理
* @param e
......@@ -83,4 +95,8 @@ public class GlobalExceptionHandler {
return RestResponse.failure(errorCode, message);
}
private static String getFailFastMsg(String paramName, String paramError) {
return String.format("%s:%s", paramName, paramError);
}
}
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