├── src ├── main │ ├── resources │ │ └── app.properties │ └── java │ │ └── hsim │ │ └── checkpoint │ │ ├── setting │ │ ├── session │ │ │ ├── ValidationLoginInfo.java │ │ │ ├── ValidationSessionInfo.java │ │ │ └── ValidationSessionComponent.java │ │ ├── service │ │ │ ├── MsgExcelService.java │ │ │ ├── MsgSettingService.java │ │ │ ├── MsgExcelServiceImpl.java │ │ │ └── MsgSettingServiceImpl.java │ │ └── controller │ │ │ └── MsgSettingController.java │ │ ├── core │ │ ├── annotation │ │ │ ├── ValidationBody.java │ │ │ ├── ValidationUrlMapping.java │ │ │ └── ValidationParam.java │ │ ├── component │ │ │ ├── validationRule │ │ │ │ ├── type │ │ │ │ │ ├── StandardValueType.java │ │ │ │ │ ├── BasicCheckRule.java │ │ │ │ │ └── BaseValidationCheck.java │ │ │ │ ├── callback │ │ │ │ │ └── ValidationInvalidCallback.java │ │ │ │ ├── sort │ │ │ │ │ └── RuleSorter.java │ │ │ │ ├── replace │ │ │ │ │ ├── ReplaceTrim.java │ │ │ │ │ ├── ReplaceDefaultValue.java │ │ │ │ │ └── ReplaceBase64.java │ │ │ │ ├── check │ │ │ │ │ ├── WhiteListCheck.java │ │ │ │ │ ├── BlackListCheck.java │ │ │ │ │ ├── MandatoryCheck.java │ │ │ │ │ ├── MaxSizeCheck.java │ │ │ │ │ ├── MinSizeCheck.java │ │ │ │ │ └── PatternCheck.java │ │ │ │ └── rule │ │ │ │ │ ├── AssistType.java │ │ │ │ │ └── ValidationRule.java │ │ │ ├── ComponentMap.java │ │ │ ├── DetailParam.java │ │ │ └── RequestAnnotation.java │ │ ├── repository │ │ │ └── index │ │ │ │ ├── idx │ │ │ │ ├── ValidationDataIndex.java │ │ │ │ ├── IdIndex.java │ │ │ │ └── MethodAndUrlIndex.java │ │ │ │ ├── util │ │ │ │ └── ValidationIndexUtil.java │ │ │ │ └── map │ │ │ │ └── ValidationDataIndexMap.java │ │ ├── store │ │ │ ├── ValidationDataGroup.java │ │ │ ├── ValidationStore.java │ │ │ └── ValidationRuleStore.java │ │ ├── domain │ │ │ ├── ReqUrl.java │ │ │ └── BasicCheckInfo.java │ │ └── msg │ │ │ ├── MethodSyncor.java │ │ │ ├── MsgChecker.java │ │ │ └── MsgSaver.java │ │ ├── util │ │ ├── AnnotationUtil.java │ │ ├── ValidationReqUrlUtil.java │ │ ├── ValidationHttpUtil.java │ │ ├── excel │ │ │ ├── PoiCellStyle.java │ │ │ ├── PoiWorkBook.java │ │ │ ├── TypeCheckUtil.java │ │ │ └── PoiWorkSheet.java │ │ ├── AnnotationScanner.java │ │ ├── ValidationFileUtil.java │ │ └── ParameterMapper.java │ │ ├── config │ │ ├── ValidationIntercepterConfig.java │ │ └── ValidationConfig.java │ │ ├── type │ │ └── ParamType.java │ │ ├── exception │ │ ├── resolver │ │ │ └── ValidationExceptionResolver.java │ │ └── ValidationLibException.java │ │ ├── init │ │ └── InitCheckPoint.java │ │ ├── interceptor │ │ └── ValidationResolver.java │ │ └── helper │ │ └── CheckPointHelper.java └── test │ └── java │ └── hsim │ └── checkpoint │ ├── model │ ├── user │ │ ├── type │ │ │ ├── Gender.java │ │ │ └── Membership.java │ │ └── UserModel.java │ ├── product │ │ ├── ProductType.java │ │ └── ProductModel.java │ ├── BaseModel.java │ └── order │ │ ├── OrderItemModel.java │ │ └── OrderModel.java │ ├── rule │ └── LoggingRule.java │ └── test │ ├── requrl │ └── ReqUrlTest.java │ ├── repoistory │ └── RepositoryTest.java │ ├── rule │ ├── replace │ │ ├── TrimRuleTest.java │ │ ├── DefaultValueRuleTest.java │ │ └── Base64RuleTest.java │ ├── RuleTestUtil.java │ └── check │ │ ├── MandatoryRuleTest.java │ │ ├── BlackListCheck.java │ │ ├── PatternRuleTest.java │ │ ├── MinSizeRuleTest.java │ │ ├── MaxSizeRuleTest.java │ │ └── WhiteListCheck.java │ └── helper │ └── HelperTest.java ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── .gitignore ├── pom.xml ├── mvnw.cmd ├── mvnw └── README.md /src/main/resources/app.properties: -------------------------------------------------------------------------------- 1 | app.version=1.0 2 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ckpoint/CheckPoint/HEAD/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip 2 | -------------------------------------------------------------------------------- /src/test/java/hsim/checkpoint/model/user/type/Gender.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.model.user.type; 2 | 3 | public enum Gender { 4 | MAN, WOMAN 5 | } 6 | -------------------------------------------------------------------------------- /src/test/java/hsim/checkpoint/model/product/ProductType.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.model.product; 2 | 3 | public enum ProductType { 4 | SHOES, TOPS, BOTTOMS, ACCESSORIES, ETC 5 | } 6 | -------------------------------------------------------------------------------- /src/test/java/hsim/checkpoint/model/user/type/Membership.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.model.user.type; 2 | 3 | public enum Membership { 4 | GOLD, SILVER, BRONZE, DORMANCY, BLACK 5 | } 6 | -------------------------------------------------------------------------------- /src/test/java/hsim/checkpoint/model/BaseModel.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.model; 2 | 3 | import lombok.Data; 4 | 5 | import java.util.Date; 6 | 7 | @Data 8 | public class BaseModel { 9 | private Long id; 10 | private Date createdAt; 11 | private Date updatedAt; 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/setting/session/ValidationLoginInfo.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.setting.session; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | /** 7 | * The type Validation login info. 8 | */ 9 | @Getter 10 | @Setter 11 | public class ValidationLoginInfo { 12 | private String userName; 13 | private String token; 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/hsim/checkpoint/model/order/OrderItemModel.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.model.order; 2 | 3 | import hsim.checkpoint.model.BaseModel; 4 | import hsim.checkpoint.model.product.ProductModel; 5 | import lombok.Data; 6 | 7 | @Data 8 | public class OrderItemModel extends BaseModel { 9 | 10 | private ProductModel product; 11 | private Integer orderUnit; 12 | 13 | } 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ 26 | checkpoint/validation.json 27 | -------------------------------------------------------------------------------- /src/test/java/hsim/checkpoint/model/product/ProductModel.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.model.product; 2 | 3 | import hsim.checkpoint.model.BaseModel; 4 | import lombok.Data; 5 | 6 | @Data 7 | public class ProductModel extends BaseModel { 8 | 9 | private String name; 10 | private ProductType type; 11 | private String description; 12 | private String photoUrl; 13 | private Long basePrice; 14 | private Double discountPercent; 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/annotation/ValidationBody.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.annotation; 2 | 3 | import java.lang.annotation.*; 4 | 5 | 6 | /** 7 | * The interface Validation body. 8 | */ 9 | @Target(ElementType.PARAMETER) 10 | @Retention(RetentionPolicy.RUNTIME) 11 | @Documented 12 | public @interface ValidationBody { 13 | 14 | /** 15 | * Required boolean. 16 | * 17 | * @return the boolean 18 | */ 19 | boolean required() default true; 20 | } -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/annotation/ValidationUrlMapping.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.annotation; 2 | 3 | import java.lang.annotation.*; 4 | 5 | 6 | /** 7 | * The interface Validation url mapping. 8 | */ 9 | @Target(ElementType.METHOD) 10 | @Retention(RetentionPolicy.RUNTIME) 11 | @Documented 12 | public @interface ValidationUrlMapping { 13 | 14 | /** 15 | * Required boolean. 16 | * 17 | * @return the boolean 18 | */ 19 | boolean required() default true; 20 | } -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/component/validationRule/type/StandardValueType.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.component.validationRule.type; 2 | 3 | /** 4 | * The enum Standard value type. 5 | */ 6 | public enum StandardValueType { 7 | /** 8 | * None standard value type. 9 | */ 10 | NONE, /** 11 | * Number standard value type. 12 | */ 13 | NUMBER, /** 14 | * String standard value type. 15 | */ 16 | STRING, /** 17 | * List standard value type. 18 | */ 19 | LIST 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/hsim/checkpoint/model/order/OrderModel.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.model.order; 2 | 3 | import hsim.checkpoint.model.BaseModel; 4 | import hsim.checkpoint.model.user.UserModel; 5 | import lombok.Data; 6 | 7 | import java.util.List; 8 | 9 | /** 10 | * The type Common req hsim.checkpoint.model. 11 | */ 12 | 13 | @Data 14 | public class OrderModel extends BaseModel { 15 | 16 | private UserModel user; 17 | private List orderItems; 18 | private Long totalPrice; 19 | private List commentList; 20 | } 21 | 22 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/setting/service/MsgExcelService.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.setting.service; 2 | 3 | import hsim.checkpoint.util.excel.PoiWorkBook; 4 | 5 | /** 6 | * The interface Msg excel service. 7 | */ 8 | public interface MsgExcelService { 9 | /** 10 | * Gets all excels. 11 | * 12 | * @return the all excels 13 | */ 14 | PoiWorkBook getAllExcels(); 15 | 16 | /** 17 | * Gets excel. 18 | * 19 | * @param method the method 20 | * @param url the url 21 | * @return the excel 22 | */ 23 | PoiWorkBook getExcel(String method, String url); 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/annotation/ValidationParam.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.annotation; 2 | 3 | import java.lang.annotation.*; 4 | 5 | 6 | /** 7 | * The interface Validation param. 8 | */ 9 | @Target(ElementType.PARAMETER) 10 | @Retention(RetentionPolicy.RUNTIME) 11 | @Documented 12 | public @interface ValidationParam { 13 | 14 | /** 15 | * Required boolean. 16 | * 17 | * @return the boolean 18 | */ 19 | boolean required() default true; 20 | 21 | /** 22 | * Charset string. 23 | * 24 | * @return the string 25 | */ 26 | String charset() default "UTF-8"; 27 | } -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/component/validationRule/callback/ValidationInvalidCallback.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.component.validationRule.callback; 2 | 3 | import hsim.checkpoint.core.domain.ValidationData; 4 | 5 | /** 6 | * The interface Validation invalid callback. 7 | */ 8 | public interface ValidationInvalidCallback { 9 | 10 | /** 11 | * Exception. 12 | * 13 | * @param param the param 14 | * @param inputValue the input value 15 | * @param standardValue the standard value 16 | */ 17 | void exception(ValidationData param, Object inputValue, Object standardValue); 18 | } 19 | -------------------------------------------------------------------------------- /src/test/java/hsim/checkpoint/model/user/UserModel.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.model.user; 2 | 3 | import hsim.checkpoint.model.BaseModel; 4 | import hsim.checkpoint.model.user.type.Gender; 5 | import hsim.checkpoint.model.user.type.Membership; 6 | import lombok.Data; 7 | 8 | @Data 9 | public class UserModel extends BaseModel { 10 | 11 | private String name; 12 | private String loginId; 13 | private String password; 14 | 15 | private Membership membership; 16 | private String nickName; 17 | private Gender gender; 18 | private String email; 19 | private String contactNumber; 20 | private String address; 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/util/AnnotationUtil.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.util; 2 | 3 | import java.lang.annotation.Annotation; 4 | import java.util.Arrays; 5 | 6 | /** 7 | * The type Annotation util. 8 | */ 9 | public class AnnotationUtil { 10 | 11 | /** 12 | * Gets annotation. 13 | * 14 | * @param annotations the annotations 15 | * @param annotationClass the annotation class 16 | * @return the annotation 17 | */ 18 | public static Annotation getAnnotation(Annotation[] annotations, Class annotationClass) { 19 | return Arrays.stream(annotations).filter(annotation -> annotation.annotationType().equals(annotationClass)).findFirst().orElse(null); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/config/ValidationIntercepterConfig.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.config; 2 | 3 | import hsim.checkpoint.interceptor.ValidationResolver; 4 | import org.springframework.web.method.support.HandlerMethodArgumentResolver; 5 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 6 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 7 | 8 | import java.util.List; 9 | 10 | /** 11 | * The type Validation intercepter config. 12 | */ 13 | public class ValidationIntercepterConfig extends WebMvcConfigurerAdapter { 14 | 15 | @Override 16 | public void addArgumentResolvers(List resolvers) { 17 | resolvers.add(new ValidationResolver()); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/setting/session/ValidationSessionInfo.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.setting.session; 2 | 3 | import lombok.Getter; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | import java.util.Date; 7 | 8 | /** 9 | * The type Validation session info. 10 | */ 11 | @Getter 12 | public class ValidationSessionInfo { 13 | 14 | private String token; 15 | private String ipAddress; 16 | private Date createDate; 17 | 18 | /** 19 | * Instantiates a new Validation session info. 20 | * 21 | * @param req the req 22 | * @param t the t 23 | */ 24 | public ValidationSessionInfo(HttpServletRequest req, String t) { 25 | this.token = t; 26 | this.createDate = new Date(); 27 | this.ipAddress = req.getRemoteAddr(); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/component/validationRule/sort/RuleSorter.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.component.validationRule.sort; 2 | 3 | import hsim.checkpoint.core.component.validationRule.rule.ValidationRule; 4 | 5 | import java.util.Comparator; 6 | 7 | /** 8 | * The type Rule sorter. 9 | */ 10 | public class RuleSorter implements Comparator { 11 | 12 | @Override 13 | public int compare(Object o1, Object o2) { 14 | ValidationRule rule1 = (ValidationRule) o1; 15 | ValidationRule rule2 = (ValidationRule) o2; 16 | 17 | int v1 = rule1.getOrderIdx(); 18 | int v2 = rule2.getOrderIdx(); 19 | 20 | if (v1 < v2) { 21 | return -1; 22 | } else if (v1 == v2) { 23 | return 0; 24 | } else { 25 | return 1; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/config/ValidationConfig.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.config; 2 | 3 | import lombok.Getter; 4 | import lombok.ToString; 5 | import org.springframework.beans.factory.annotation.Value; 6 | 7 | /** 8 | * The type Validation config. 9 | */ 10 | @ToString 11 | @Getter 12 | public class ValidationConfig { 13 | 14 | @Value("${ckpoint.save.url:true}") 15 | private boolean freshUrlSave; 16 | 17 | @Value("${ckpoint.max.deeplevel:5}") 18 | private int maxDeepLevel; 19 | 20 | @Value("${ckpoint.body.logging:true}") 21 | private boolean bodyLogging; 22 | 23 | @Value("${ckpoint.password:taeon}") 24 | private String authToken; 25 | 26 | @Value("${ckpoint.path.repository:checkpoint/validation.json}") 27 | private String repositoryPath = "/checkpoint/validation.json"; 28 | 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/repository/index/idx/ValidationDataIndex.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.repository.index.idx; 2 | 3 | import hsim.checkpoint.core.domain.ValidationData; 4 | 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | /** 9 | * The interface Validation data index. 10 | */ 11 | public interface ValidationDataIndex { 12 | 13 | /** 14 | * Refresh. 15 | */ 16 | void refresh(); 17 | 18 | /** 19 | * Get list. 20 | * 21 | * @param key the key 22 | * @return the list 23 | */ 24 | List get(String key); 25 | 26 | /** 27 | * Gets key. 28 | * 29 | * @param data the data 30 | * @return the key 31 | */ 32 | String getKey(ValidationData data); 33 | 34 | /** 35 | * Gets map. 36 | * 37 | * @return the map 38 | */ 39 | Map> getMap(); 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/component/validationRule/type/BasicCheckRule.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.component.validationRule.type; 2 | 3 | import lombok.Getter; 4 | 5 | /** 6 | * The enum Basic check rule. 7 | */ 8 | @Getter 9 | public enum BasicCheckRule { 10 | /** 11 | * Mandatory basic check rule. 12 | */ 13 | Mandatory, /** 14 | * Black list basic check rule. 15 | */ 16 | BlackList, /** 17 | * White list basic check rule. 18 | */ 19 | WhiteList, /** 20 | * Min size basic check rule. 21 | */ 22 | MinSize, /** 23 | * Max size basic check rule. 24 | */ 25 | MaxSize, /** 26 | * Default value basic check rule. 27 | */ 28 | DefaultValue, /** 29 | * Base 64 basic check rule. 30 | */ 31 | Base64, /** 32 | * Trim basic check rule. 33 | */ 34 | Trim, /** 35 | * Pattern basic check rule. 36 | */ 37 | Pattern 38 | } 39 | -------------------------------------------------------------------------------- /src/test/java/hsim/checkpoint/rule/LoggingRule.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.rule; 2 | 3 | import hsim.checkpoint.core.component.validationRule.type.BaseValidationCheck; 4 | import hsim.checkpoint.core.domain.ValidationData; 5 | import hsim.checkpoint.exception.ValidationLibException; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.http.HttpStatus; 8 | 9 | @Slf4j 10 | public class LoggingRule implements BaseValidationCheck { 11 | 12 | @Override 13 | public boolean check(Object value, Object standardValue) { 14 | log.info("input : " + value + ", standard : " + standardValue); 15 | return true; 16 | } 17 | 18 | @Override 19 | public Object replace(Object value, Object standardValue, ValidationData param) { 20 | return null; 21 | } 22 | 23 | @Override 24 | public void exception(ValidationData param, Object inputValue, Object standardValue) { 25 | throw new ValidationLibException("logging", HttpStatus.BAD_REQUEST); 26 | } 27 | 28 | } -------------------------------------------------------------------------------- /src/test/java/hsim/checkpoint/test/requrl/ReqUrlTest.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.test.requrl; 2 | 3 | import hsim.checkpoint.core.domain.ReqUrl; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.junit.Assert; 6 | import org.junit.FixMethodOrder; 7 | import org.junit.Test; 8 | import org.junit.runners.MethodSorters; 9 | import org.springframework.http.HttpMethod; 10 | 11 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 12 | @Slf4j 13 | public class ReqUrlTest { 14 | 15 | 16 | @Test 17 | public void test_ReqUrlReformat1(){ 18 | String url = "/api/order/filter/"; 19 | ReqUrl reqUrl = new ReqUrl(HttpMethod.GET.name(), url); 20 | 21 | Assert.assertEquals(reqUrl.getUrl(), "/api/order/filter" ); 22 | } 23 | 24 | @Test 25 | public void test_ReqUrlReformat2(){ 26 | String url = "/api/order/filter///"; 27 | ReqUrl reqUrl = new ReqUrl(HttpMethod.GET.name(), url); 28 | 29 | Assert.assertEquals(reqUrl.getUrl(), "/api/order/filter" ); 30 | } 31 | 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/component/validationRule/replace/ReplaceTrim.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.component.validationRule.replace; 2 | 3 | import hsim.checkpoint.core.component.validationRule.type.BaseValidationCheck; 4 | import hsim.checkpoint.core.domain.ValidationData; 5 | import lombok.NoArgsConstructor; 6 | 7 | /** 8 | * The type Replace trim. 9 | */ 10 | @NoArgsConstructor 11 | public class ReplaceTrim implements BaseValidationCheck { 12 | 13 | 14 | @Override 15 | public boolean check(Object inputValue, Object standardValue) { 16 | return true; 17 | } 18 | 19 | @Override 20 | public Object replace(Object value, Object standardValue, ValidationData param) { 21 | if (value != null && value instanceof String) { 22 | String str = (String) value; 23 | return str.trim(); 24 | } 25 | return null; 26 | } 27 | 28 | @Override 29 | public void exception(ValidationData param, Object inputValue, Object standardValue) { 30 | 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/util/ValidationReqUrlUtil.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.util; 2 | 3 | import hsim.checkpoint.core.domain.ReqUrl; 4 | import hsim.checkpoint.core.domain.ValidationData; 5 | 6 | import java.util.HashMap; 7 | import java.util.List; 8 | import java.util.Map; 9 | import java.util.stream.Collectors; 10 | 11 | /** 12 | * The type Validation req url util. 13 | */ 14 | public class ValidationReqUrlUtil { 15 | 16 | /** 17 | * Gets url list from validation datas. 18 | * 19 | * @param datas the datas 20 | * @return the url list from validation datas 21 | */ 22 | public static List getUrlListFromValidationDatas(List datas) { 23 | Map urlMap = new HashMap<>(); 24 | datas.stream().forEach(data -> { 25 | ReqUrl url = new ReqUrl(data); 26 | urlMap.put(url.getUniqueKey(), url); 27 | }); 28 | 29 | return urlMap.entrySet().stream().map(entry -> entry.getValue()).collect(Collectors.toList()); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/type/ParamType.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.type; 2 | 3 | import hsim.checkpoint.core.domain.ReqUrl; 4 | import lombok.Getter; 5 | 6 | /** 7 | * The enum Param type. 8 | */ 9 | public enum ParamType { 10 | /** 11 | * Body param type. 12 | */ 13 | BODY("@ValidationBody"), /** 14 | * Query param param type. 15 | */ 16 | QUERY_PARAM("@ValidationParam"); 17 | 18 | @Getter 19 | private String annotationName; 20 | 21 | ParamType(String aName) { 22 | this.annotationName = aName; 23 | } 24 | 25 | /** 26 | * Gets unique key. 27 | * 28 | * @param reqUrl the req url 29 | * @return the unique key 30 | */ 31 | public String getUniqueKey(ReqUrl reqUrl) { 32 | return this.getUniqueKey(reqUrl.getUniqueKey()); 33 | } 34 | 35 | /** 36 | * Gets unique key. 37 | * 38 | * @param id the id 39 | * @return the unique key 40 | */ 41 | public String getUniqueKey(String id) { 42 | return this.name() + ":" + id; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/component/ComponentMap.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.component; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | /** 9 | * The type Component map. 10 | */ 11 | @Slf4j 12 | public class ComponentMap { 13 | 14 | private static Map, Object> map = new HashMap(); 15 | 16 | /** 17 | * Get t. 18 | * 19 | * @param the type parameter 20 | * @param cType the c type 21 | * @return the t 22 | */ 23 | public synchronized static T get(Class cType) { 24 | 25 | if( map.get(cType) != null){ 26 | return cType.cast(map.get(cType)); 27 | } 28 | 29 | try { 30 | Object obj = cType.newInstance(); 31 | log.debug("[CREATE INSTANCE] : " + cType.getSimpleName()); 32 | map.put(cType, obj); 33 | return cType.cast(obj); 34 | } catch (InstantiationException | IllegalAccessException e) { 35 | log.debug(e.getMessage()); 36 | } 37 | return null; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/component/validationRule/replace/ReplaceDefaultValue.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.component.validationRule.replace; 2 | 3 | import hsim.checkpoint.core.component.validationRule.type.BaseValidationCheck; 4 | import hsim.checkpoint.core.domain.ValidationData; 5 | import lombok.NoArgsConstructor; 6 | 7 | /** 8 | * The type Replace default value. 9 | */ 10 | @NoArgsConstructor 11 | public class ReplaceDefaultValue implements BaseValidationCheck { 12 | 13 | 14 | private boolean isEmptyString(Object value) { 15 | return (value instanceof String && ((String) value).isEmpty()); 16 | } 17 | 18 | @Override 19 | public boolean check(Object inputValue, Object standardValue) { 20 | return true; 21 | } 22 | 23 | @Override 24 | public Object replace(Object value, Object standardValue, ValidationData param) { 25 | if (value != null && !this.isEmptyString(value)) { 26 | return null; 27 | } 28 | 29 | return standardValue; 30 | } 31 | 32 | @Override 33 | public void exception(ValidationData param, Object inputValue, Object standardValue) { 34 | 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/component/validationRule/type/BaseValidationCheck.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.component.validationRule.type; 2 | 3 | import hsim.checkpoint.core.domain.ValidationData; 4 | 5 | /** 6 | * The type Base validation check. 7 | */ 8 | public interface BaseValidationCheck { 9 | 10 | /** 11 | * Check boolean. 12 | * 13 | * @param inputValue the input value 14 | * @param standardValue the standard value 15 | * @return the boolean 16 | */ 17 | boolean check(Object inputValue, Object standardValue); 18 | 19 | /** 20 | * Replace object. 21 | * 22 | * @param value the value 23 | * @param standardValue the standard value 24 | * @param param the param 25 | * @return the object 26 | */ 27 | Object replace(Object value, Object standardValue, ValidationData param); 28 | 29 | /** 30 | * Exception. 31 | * 32 | * @param param the param 33 | * @param inputValue the input value 34 | * @param standardValue the standard value 35 | */ 36 | void exception(ValidationData param, Object inputValue, Object standardValue); 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/component/validationRule/check/WhiteListCheck.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.component.validationRule.check; 2 | 3 | import hsim.checkpoint.core.component.validationRule.type.BaseValidationCheck; 4 | import hsim.checkpoint.core.domain.ValidationData; 5 | import hsim.checkpoint.exception.ValidationLibException; 6 | import lombok.NoArgsConstructor; 7 | import org.springframework.http.HttpStatus; 8 | 9 | import java.util.List; 10 | 11 | /** 12 | * The type White list check. 13 | */ 14 | @NoArgsConstructor 15 | public class WhiteListCheck implements BaseValidationCheck { 16 | 17 | 18 | @Override 19 | public boolean check(Object value, Object standardValue) { 20 | List whiteList = (List) standardValue; 21 | 22 | return whiteList.contains(String.valueOf(value).trim()); 23 | } 24 | 25 | @Override 26 | public Object replace(Object value, Object standardValue, ValidationData param) { 27 | return null; 28 | } 29 | 30 | @Override 31 | public void exception(ValidationData param, Object inputValue, Object standardValue) { 32 | throw new ValidationLibException(inputValue + " is bad", HttpStatus.NOT_ACCEPTABLE); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/repository/index/idx/IdIndex.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.repository.index.idx; 2 | 3 | import hsim.checkpoint.core.domain.ValidationData; 4 | import hsim.checkpoint.core.repository.index.util.ValidationIndexUtil; 5 | 6 | import java.util.ArrayList; 7 | import java.util.HashMap; 8 | import java.util.List; 9 | import java.util.Map; 10 | 11 | /** 12 | * The type Id index. 13 | */ 14 | public class IdIndex implements ValidationDataIndex { 15 | 16 | /** 17 | * The Index map. 18 | */ 19 | Map> indexMap = new HashMap<>(); 20 | 21 | @Override 22 | public void refresh() { 23 | this.indexMap = new HashMap<>(); 24 | } 25 | 26 | 27 | @Override 28 | public List get(String key) { 29 | List datas = this.indexMap.get(key); 30 | return datas == null ? new ArrayList<>() : datas; 31 | } 32 | 33 | @Override 34 | public String getKey(ValidationData data) { 35 | return ValidationIndexUtil.makeKey(String.valueOf(data.getId())); 36 | } 37 | 38 | @Override 39 | public Map> getMap() { 40 | return this.indexMap; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/repository/index/idx/MethodAndUrlIndex.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.repository.index.idx; 2 | 3 | import hsim.checkpoint.core.domain.ValidationData; 4 | import hsim.checkpoint.core.repository.index.util.ValidationIndexUtil; 5 | 6 | import java.util.ArrayList; 7 | import java.util.HashMap; 8 | import java.util.List; 9 | import java.util.Map; 10 | 11 | /** 12 | * The type Method and url index. 13 | */ 14 | public class MethodAndUrlIndex implements ValidationDataIndex { 15 | 16 | /** 17 | * The Index map. 18 | */ 19 | Map> indexMap = new HashMap<>(); 20 | 21 | @Override 22 | public void refresh() { 23 | this.indexMap = new HashMap<>(); 24 | } 25 | 26 | 27 | @Override 28 | public List get(String key) { 29 | List datas = this.indexMap.get(key); 30 | return datas == null ? new ArrayList<>() : datas; 31 | } 32 | 33 | @Override 34 | public String getKey(ValidationData data) { 35 | return ValidationIndexUtil.makeKey(data.getMethod(), data.getUrl()); 36 | } 37 | 38 | @Override 39 | public Map> getMap() { 40 | return this.indexMap; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/component/validationRule/check/BlackListCheck.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.component.validationRule.check; 2 | 3 | import hsim.checkpoint.core.component.validationRule.type.BaseValidationCheck; 4 | import hsim.checkpoint.core.domain.ValidationData; 5 | import hsim.checkpoint.exception.ValidationLibException; 6 | import lombok.NoArgsConstructor; 7 | import org.springframework.http.HttpStatus; 8 | 9 | import java.util.List; 10 | 11 | /** 12 | * The type Black list check. 13 | */ 14 | @NoArgsConstructor 15 | public class BlackListCheck implements BaseValidationCheck { 16 | 17 | @Override 18 | public boolean check(Object value, Object standardValue) { 19 | if (value == null) { 20 | return true; 21 | } 22 | List blackList = (List) standardValue; 23 | return !blackList.contains(String.valueOf(value).trim()); 24 | } 25 | 26 | @Override 27 | public Object replace(Object value, Object standardValue, ValidationData param) { 28 | return null; 29 | } 30 | 31 | @Override 32 | public void exception(ValidationData param, Object inputValue, Object standardValue) { 33 | throw new ValidationLibException(inputValue + " is bad", HttpStatus.NOT_ACCEPTABLE); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/util/ValidationHttpUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package hsim.checkpoint.util; 5 | 6 | import lombok.extern.slf4j.Slf4j; 7 | 8 | import javax.servlet.http.HttpServletRequest; 9 | import java.io.BufferedReader; 10 | import java.io.IOException; 11 | import java.io.InputStreamReader; 12 | 13 | /** 14 | * Create by hsim on 2017. 12. 11. 15 | */ 16 | @Slf4j 17 | public class ValidationHttpUtil { 18 | 19 | /** 20 | * Read body string. 21 | * 22 | * @param request the request 23 | * @return the string 24 | */ 25 | public static String readBody(HttpServletRequest request) { 26 | 27 | BufferedReader input = null; 28 | try { 29 | input = new BufferedReader(new InputStreamReader(request.getInputStream())); 30 | StringBuilder builder = new StringBuilder(); 31 | String buffer; 32 | while ((buffer = input.readLine()) != null) { 33 | if (builder.length() > 0) { 34 | builder.append("\n"); 35 | } 36 | builder.append(buffer); 37 | } 38 | return builder.toString(); 39 | } catch (IOException e) { 40 | log.info("http io exception : " + e.getMessage()); 41 | } 42 | return null; 43 | } 44 | 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/component/validationRule/check/MandatoryCheck.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.component.validationRule.check; 2 | 3 | import hsim.checkpoint.core.component.validationRule.type.BaseValidationCheck; 4 | import hsim.checkpoint.core.domain.ValidationData; 5 | import hsim.checkpoint.exception.ValidationLibException; 6 | import lombok.NoArgsConstructor; 7 | import org.springframework.http.HttpStatus; 8 | 9 | /** 10 | * The type Mandatory check. 11 | */ 12 | @NoArgsConstructor 13 | public class MandatoryCheck implements BaseValidationCheck { 14 | 15 | 16 | @Override 17 | public boolean check(Object value, Object standardValue) { 18 | 19 | if (value == null) { 20 | return false; 21 | } 22 | 23 | if( value instanceof String) { 24 | String sv = String.valueOf(value); 25 | return !sv.isEmpty(); 26 | } 27 | 28 | return true; 29 | } 30 | 31 | @Override 32 | public Object replace(Object value, Object standardValue, ValidationData param) { 33 | return null; 34 | } 35 | 36 | @Override 37 | public void exception(ValidationData param, Object inputValue, Object standardValue) { 38 | throw new ValidationLibException("Mandatory field is null ( " + param.getName() + ") ", HttpStatus.BAD_REQUEST); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/component/validationRule/replace/ReplaceBase64.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.component.validationRule.replace; 2 | 3 | import hsim.checkpoint.core.component.validationRule.type.BaseValidationCheck; 4 | import hsim.checkpoint.core.domain.ValidationData; 5 | import lombok.NoArgsConstructor; 6 | import lombok.extern.slf4j.Slf4j; 7 | 8 | import java.io.UnsupportedEncodingException; 9 | import java.util.Base64; 10 | 11 | /** 12 | * The type Replace base 64. 13 | */ 14 | @Slf4j 15 | @NoArgsConstructor 16 | public class ReplaceBase64 implements BaseValidationCheck { 17 | 18 | 19 | @Override 20 | public boolean check(Object inputValue, Object standardValue) { 21 | return true; 22 | } 23 | 24 | @Override 25 | public Object replace(Object value, Object standardValue, ValidationData param) { 26 | if (value != null && value instanceof String) { 27 | try { 28 | return new String(Base64.getDecoder().decode((String) value), "UTF-8"); 29 | } catch (UnsupportedEncodingException | IllegalArgumentException e) { 30 | log.info("base64 decode fail ( " + param.getName() + " ) :" + value); 31 | return value; 32 | } 33 | } 34 | return null; 35 | } 36 | 37 | @Override 38 | public void exception(ValidationData param, Object inputValue, Object standardValue) { 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/component/validationRule/check/MaxSizeCheck.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.component.validationRule.check; 2 | 3 | import hsim.checkpoint.core.component.validationRule.type.BaseValidationCheck; 4 | import hsim.checkpoint.core.domain.ValidationData; 5 | import hsim.checkpoint.exception.ValidationLibException; 6 | import hsim.checkpoint.util.ValidationObjUtil; 7 | import lombok.NoArgsConstructor; 8 | import org.springframework.http.HttpStatus; 9 | 10 | /** 11 | * The type Max size check. 12 | */ 13 | @NoArgsConstructor 14 | public class MaxSizeCheck implements BaseValidationCheck { 15 | 16 | 17 | @Override 18 | public boolean check(Object value, Object standardValue) { 19 | 20 | Double v = ValidationObjUtil.getObjectSize(value); 21 | if (v == null) { 22 | return true; 23 | } 24 | 25 | Double doubleSValue = Double.valueOf(String.valueOf(standardValue)); 26 | 27 | if (doubleSValue < v) { 28 | return false; 29 | } 30 | 31 | return true; 32 | } 33 | 34 | @Override 35 | public Object replace(Object value, Object standardValue, ValidationData param) { 36 | return null; 37 | } 38 | 39 | @Override 40 | public void exception(ValidationData param, Object inputValue, Object standardValue) { 41 | throw new ValidationLibException("Parameter : " + param.getName() + " value is too big(maximum:" + standardValue + ")", HttpStatus.BAD_REQUEST); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/component/validationRule/check/MinSizeCheck.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.component.validationRule.check; 2 | 3 | import hsim.checkpoint.core.component.validationRule.type.BaseValidationCheck; 4 | import hsim.checkpoint.core.domain.ValidationData; 5 | import hsim.checkpoint.exception.ValidationLibException; 6 | import hsim.checkpoint.util.ValidationObjUtil; 7 | import lombok.NoArgsConstructor; 8 | import org.springframework.http.HttpStatus; 9 | 10 | /** 11 | * The type Min size check. 12 | */ 13 | @NoArgsConstructor 14 | public class MinSizeCheck implements BaseValidationCheck { 15 | 16 | 17 | @Override 18 | public boolean check(Object value, Object standardValue) { 19 | 20 | Double v = ValidationObjUtil.getObjectSize(value); 21 | if (v == null) { 22 | return true; 23 | } 24 | Double doubleSValue = Double.valueOf(String.valueOf(standardValue)); 25 | 26 | if (v < doubleSValue) { 27 | return false; 28 | } 29 | 30 | return true; 31 | } 32 | 33 | @Override 34 | public Object replace(Object value, Object standardValue, ValidationData param) { 35 | return null; 36 | } 37 | 38 | @Override 39 | public void exception(ValidationData param, Object inputValue, Object standardValue) { 40 | throw new ValidationLibException("Parameter : " + param.getName() + " value is too small(minimum :" + standardValue + ")", HttpStatus.BAD_REQUEST); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/component/validationRule/check/PatternCheck.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.component.validationRule.check; 2 | 3 | import hsim.checkpoint.core.component.validationRule.type.BaseValidationCheck; 4 | import hsim.checkpoint.core.domain.ValidationData; 5 | import hsim.checkpoint.exception.ValidationLibException; 6 | import lombok.NoArgsConstructor; 7 | import org.springframework.http.HttpStatus; 8 | 9 | import java.util.regex.Matcher; 10 | import java.util.regex.Pattern; 11 | 12 | /** 13 | * The type Pattern check. 14 | */ 15 | @NoArgsConstructor 16 | public class PatternCheck implements BaseValidationCheck { 17 | 18 | 19 | @Override 20 | public boolean check(Object value, Object standradValue) { 21 | 22 | if (value instanceof String) { 23 | Pattern pattern = Pattern.compile(String.valueOf(standradValue)); 24 | Matcher matcher = pattern.matcher(String.valueOf(value)); 25 | if (!matcher.matches()) { 26 | return false; 27 | } 28 | } 29 | return true; 30 | } 31 | 32 | @Override 33 | public Object replace(Object value, Object standardValue, ValidationData param) { 34 | return null; 35 | } 36 | 37 | @Override 38 | public void exception(ValidationData param, Object inputValue, Object standardValue) { 39 | throw new ValidationLibException("invalid pattern value : " + param.getName() + " - " + inputValue, HttpStatus.BAD_REQUEST); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/exception/resolver/ValidationExceptionResolver.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.exception.resolver; 2 | 3 | import hsim.checkpoint.exception.ValidationLibException; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.web.servlet.ModelAndView; 6 | import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver; 7 | 8 | import javax.servlet.http.HttpServletRequest; 9 | import javax.servlet.http.HttpServletResponse; 10 | import java.io.IOException; 11 | 12 | /** 13 | * The type Validation exception resolver. 14 | */ 15 | @Slf4j 16 | public class ValidationExceptionResolver extends AbstractHandlerExceptionResolver { 17 | 18 | @Override 19 | protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { 20 | if (ex instanceof ValidationLibException) { 21 | return this.sendErrorCode(response, (ValidationLibException) ex); 22 | } 23 | return null; 24 | } 25 | 26 | private ModelAndView sendErrorCode(HttpServletResponse res, ValidationLibException ex) { 27 | 28 | try { 29 | log.info("ex message : " + ex.getMessage()); 30 | res.setHeader("ERR_MSG", ex.getMessage()); 31 | res.sendError(ex.getStatusCode().value(), ex.getMessage()); 32 | } catch (IOException e) { 33 | log.error("response error send io exception "); 34 | } 35 | 36 | return new ModelAndView(); 37 | } 38 | } -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/init/InitCheckPoint.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.init; 2 | 3 | import hsim.checkpoint.core.component.ComponentMap; 4 | import hsim.checkpoint.core.msg.MethodSyncor; 5 | import hsim.checkpoint.core.repository.ValidationDataRepository; 6 | import hsim.checkpoint.core.store.ValidationStore; 7 | import hsim.checkpoint.util.AnnotationScanner; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.context.ApplicationListener; 10 | import org.springframework.context.event.ContextRefreshedEvent; 11 | 12 | /** 13 | * The type Init check point. 14 | */ 15 | public class InitCheckPoint implements ApplicationListener { 16 | 17 | @Autowired 18 | private Object[] beans; 19 | 20 | private MethodSyncor methodSyncor = ComponentMap.get(MethodSyncor.class); 21 | private ValidationDataRepository validationDataRepository = ComponentMap.get(ValidationDataRepository.class); 22 | private ValidationStore validationStore = ComponentMap.get(ValidationStore.class); 23 | private AnnotationScanner annotationScanner = ComponentMap.get(AnnotationScanner.class); 24 | 25 | @Override 26 | public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { 27 | 28 | this.annotationScanner.initBeans(this.beans); 29 | this.validationStore.refresh(); 30 | 31 | new Thread(() -> { 32 | this.validationDataRepository.refresh(); 33 | this.methodSyncor.updateMethodKeyAsync(); 34 | this.validationDataRepository.datasRuleSync(); 35 | }).start(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/store/ValidationDataGroup.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.store; 2 | 3 | import hsim.checkpoint.core.component.validationRule.rule.ValidationRule; 4 | import hsim.checkpoint.core.domain.ValidationData; 5 | import hsim.checkpoint.type.ParamType; 6 | import lombok.Getter; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | import java.util.stream.Collectors; 11 | 12 | /** 13 | * The type Validation data group. 14 | */ 15 | @Getter 16 | public class ValidationDataGroup { 17 | private ParamType paramType; 18 | private List rules = new ArrayList<>(); 19 | 20 | /** 21 | * Instantiates a new Validation data group. 22 | * 23 | * @param paramType the param type 24 | * @param validationDatas the validation datas 25 | */ 26 | public ValidationDataGroup(ParamType paramType, List validationDatas) { 27 | this.initDataGroup(paramType, validationDatas); 28 | } 29 | 30 | 31 | /** 32 | * Add rule. 33 | * 34 | * @param vd the vd 35 | */ 36 | public void addRule(ValidationData vd) { 37 | this.rules.addAll(vd.getValidationRules().stream().filter(vr -> vr.isUse()).collect(Collectors.toList())); 38 | } 39 | 40 | /** 41 | * Init data group. 42 | * 43 | * @param paramType the param type 44 | * @param lists the lists 45 | */ 46 | public void initDataGroup(ParamType paramType, List lists) { 47 | this.paramType = paramType; 48 | 49 | lists.forEach(vd -> { 50 | this.addRule(vd); 51 | }); 52 | 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/test/java/hsim/checkpoint/test/repoistory/RepositoryTest.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.test.repoistory; 2 | 3 | import hsim.checkpoint.core.component.ComponentMap; 4 | import hsim.checkpoint.core.domain.ValidationData; 5 | import hsim.checkpoint.core.repository.ValidationDataRepository; 6 | import hsim.checkpoint.type.ParamType; 7 | import org.junit.Assert; 8 | import org.junit.FixMethodOrder; 9 | import org.junit.Test; 10 | import org.junit.runners.MethodSorters; 11 | 12 | import java.util.List; 13 | 14 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 15 | public class RepositoryTest { 16 | 17 | private ValidationDataRepository validationDataRepository = ComponentMap.get(ValidationDataRepository.class); 18 | 19 | @Test 20 | public void test_order_0_init() { 21 | this.validationDataRepository.refresh(); 22 | } 23 | 24 | @Test 25 | public void test_order_1_saveTest() { 26 | ValidationData data = new ValidationData(); 27 | data.setParamType(ParamType.BODY); 28 | data.setUrl("/order/url"); 29 | data.setMethod("POST"); 30 | data.setName("order"); 31 | data.setTypeClass(String.class); 32 | data.setType("String"); 33 | data = this.validationDataRepository.save(data); 34 | Assert.assertNotNull(data.getId()); 35 | this.validationDataRepository.flush(); 36 | } 37 | 38 | @Test 39 | public void test_order_2_findTest() { 40 | List datas = this.validationDataRepository.findByParamTypeAndMethodAndUrlAndName(ParamType.BODY, "POST", "/order/url", "order"); 41 | Assert.assertNotNull(datas.get(0)); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/util/excel/PoiCellStyle.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.util.excel; 2 | 3 | import lombok.Getter; 4 | import org.apache.poi.hssf.usermodel.HSSFCellStyle; 5 | import org.apache.poi.hssf.usermodel.HSSFDataFormat; 6 | import org.apache.poi.hssf.usermodel.HSSFWorkbook; 7 | import org.apache.poi.ss.usermodel.BorderStyle; 8 | import org.apache.poi.ss.usermodel.HorizontalAlignment; 9 | import org.apache.poi.ss.usermodel.VerticalAlignment; 10 | 11 | /** 12 | * The type Poi cell style. 13 | */ 14 | @Getter 15 | public class PoiCellStyle { 16 | 17 | private static final short DATE_FORMAT_VALUE = 0xe; 18 | private HSSFCellStyle numberCs; 19 | private HSSFCellStyle stringCs; 20 | private HSSFCellStyle dateCs; 21 | 22 | /** 23 | * Instantiates a new Poi cell style. 24 | * 25 | * @param workBook the work book 26 | */ 27 | public PoiCellStyle(PoiWorkBook workBook) { 28 | 29 | this.stringCs = this.getDefaultExcelCellStyle(workBook); 30 | 31 | this.numberCs = this.getDefaultExcelCellStyle(workBook); 32 | this.numberCs.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0")); 33 | this.numberCs.setAlignment(HorizontalAlignment.RIGHT); 34 | 35 | this.dateCs = this.getDefaultExcelCellStyle(workBook); 36 | this.dateCs.setDataFormat(DATE_FORMAT_VALUE); 37 | } 38 | 39 | private HSSFCellStyle getDefaultExcelCellStyle(PoiWorkBook daouWorkBook) { 40 | 41 | HSSFWorkbook wb = daouWorkBook.getWorkBook(); 42 | 43 | HSSFCellStyle cs = wb.createCellStyle(); 44 | cs.setAlignment(HorizontalAlignment.CENTER); 45 | cs.setVerticalAlignment(VerticalAlignment.CENTER); 46 | cs.setBorderTop(BorderStyle.THIN); 47 | cs.setBorderRight(BorderStyle.THIN); 48 | cs.setBorderLeft(BorderStyle.THIN); 49 | cs.setBorderBottom(BorderStyle.THIN); 50 | 51 | return cs; 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/domain/ReqUrl.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.domain; 2 | 3 | import lombok.Getter; 4 | import lombok.NoArgsConstructor; 5 | import lombok.Setter; 6 | 7 | import javax.servlet.http.HttpServletRequest; 8 | 9 | /** 10 | * The type Req url. 11 | */ 12 | @Setter 13 | @Getter 14 | @NoArgsConstructor 15 | public class ReqUrl { 16 | private String url; 17 | private String method; 18 | private boolean urlMapping; 19 | 20 | /** 21 | * Instantiates a new Req url. 22 | * 23 | * @param method the method 24 | * @param url the url 25 | */ 26 | public ReqUrl(String method, String url) { 27 | while(url.endsWith("/")){ 28 | url = url.substring(0, url.length() -1); 29 | } 30 | this.method = method; 31 | this.url = url; 32 | } 33 | 34 | /** 35 | * Instantiates a new Req url. 36 | * 37 | * @param validationData the validation data 38 | */ 39 | public ReqUrl(ValidationData validationData) { 40 | this.method = validationData.getMethod(); 41 | this.url = validationData.getUrl(); 42 | this.urlMapping = validationData.isUrlMapping(); 43 | } 44 | 45 | /** 46 | * Instantiates a new Req url. 47 | * 48 | * @param req the req 49 | */ 50 | public ReqUrl(HttpServletRequest req) { 51 | this.method = req.getMethod(); 52 | this.url = req.getRequestURI(); 53 | } 54 | 55 | /** 56 | * Gets unique key. 57 | * 58 | * @return the unique key 59 | */ 60 | public String getUniqueKey() { 61 | return method + ":" + url; 62 | } 63 | 64 | /** 65 | * Gets sheet name. 66 | * 67 | * @param idx the idx 68 | * @return the sheet name 69 | */ 70 | public String getSheetName(int idx) { 71 | String name = method + "|" + url.replace("/", "|"); 72 | if (name.length() > 30) { 73 | return name.substring(0, 29) + idx; 74 | } 75 | return name; 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/repository/index/util/ValidationIndexUtil.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.repository.index.util; 2 | 3 | import hsim.checkpoint.core.domain.ValidationData; 4 | import hsim.checkpoint.core.repository.index.idx.ValidationDataIndex; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | import java.util.stream.Collectors; 9 | 10 | /** 11 | * The type Validation index util. 12 | */ 13 | public class ValidationIndexUtil { 14 | 15 | /** 16 | * Add index data. 17 | * 18 | * @param data the data 19 | * @param index the index 20 | */ 21 | public static void addIndexData(ValidationData data, ValidationDataIndex index) { 22 | String key = index.getKey(data); 23 | List datas = index.get(key); 24 | if (datas == null) { 25 | datas = new ArrayList<>(); 26 | } 27 | datas.add(data); 28 | index.getMap().put(key, datas); 29 | } 30 | 31 | /** 32 | * Remove index data. 33 | * 34 | * @param data the data 35 | * @param index the index 36 | */ 37 | public static void removeIndexData(ValidationData data, ValidationDataIndex index) { 38 | 39 | String key = index.getKey(data); 40 | List datas = index.get(key); 41 | 42 | if (!datas.isEmpty()) { 43 | datas = datas.stream().filter(d -> !d.getId().equals(data.getId())).collect(Collectors.toList()); 44 | } 45 | if (datas.isEmpty()) { 46 | index.getMap().remove(key); 47 | } else { 48 | index.getMap().put(key, datas); 49 | } 50 | } 51 | 52 | /** 53 | * Make key string. 54 | * 55 | * @param keys the keys 56 | * @return the string 57 | */ 58 | public static String makeKey(String... keys) { 59 | StringBuffer keyBuffer = new StringBuffer(); 60 | for (String s : keys) { 61 | keyBuffer.append(s); 62 | keyBuffer.append(":"); 63 | } 64 | return keyBuffer.toString(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/setting/service/MsgSettingService.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.setting.service; 2 | 3 | import hsim.checkpoint.core.domain.ReqUrl; 4 | import hsim.checkpoint.core.domain.ValidationData; 5 | import hsim.checkpoint.type.ParamType; 6 | import org.springframework.web.multipart.MultipartHttpServletRequest; 7 | 8 | import java.util.List; 9 | 10 | 11 | /** 12 | * The interface Msg setting service. 13 | */ 14 | public interface MsgSettingService { 15 | /** 16 | * Gets all url list. 17 | * 18 | * @return the all url list 19 | */ 20 | List getAllUrlList(); 21 | 22 | /** 23 | * Gets validation data. 24 | * 25 | * @param method the method 26 | * @param url the url 27 | * @return the validation data 28 | */ 29 | List getValidationData(String method, String url); 30 | 31 | /** 32 | * Gets all validation data. 33 | * 34 | * @return the all validation data 35 | */ 36 | List getAllValidationData(); 37 | 38 | /** 39 | * Gets validation data. 40 | * 41 | * @param paramType the param type 42 | * @param method the method 43 | * @param url the url 44 | * @return the validation data 45 | */ 46 | List getValidationData(ParamType paramType, String method, String url); 47 | 48 | /** 49 | * Update validation data. 50 | * 51 | * @param models the models 52 | */ 53 | void updateValidationData(List models); 54 | 55 | /** 56 | * Update validation data. 57 | * 58 | * @param req the req 59 | */ 60 | void updateValidationData(MultipartHttpServletRequest req); 61 | 62 | /** 63 | * Delete validation data. 64 | * 65 | * @param models the models 66 | */ 67 | void deleteValidationData(List models); 68 | 69 | /** 70 | * Delete all. 71 | */ 72 | void deleteAll(); 73 | 74 | /** 75 | * Delete validation data. 76 | * 77 | * @param url the url 78 | */ 79 | void deleteValidationData(ReqUrl url); 80 | 81 | } 82 | -------------------------------------------------------------------------------- /src/test/java/hsim/checkpoint/test/rule/replace/TrimRuleTest.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.test.rule.replace; 2 | 3 | import hsim.checkpoint.core.component.validationRule.rule.ValidationRule; 4 | import hsim.checkpoint.core.component.validationRule.type.BasicCheckRule; 5 | import hsim.checkpoint.core.domain.ValidationData; 6 | import hsim.checkpoint.model.user.UserModel; 7 | import hsim.checkpoint.test.rule.RuleTestUtil; 8 | import org.junit.Assert; 9 | import org.junit.FixMethodOrder; 10 | import org.junit.Test; 11 | import org.junit.runners.MethodSorters; 12 | 13 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 14 | public class TrimRuleTest { 15 | 16 | private RuleTestUtil ruleTestUtil = new RuleTestUtil(); 17 | private UserModel obj = new UserModel(); 18 | private ValidationData data = ruleTestUtil.getDefaultValidationData(); 19 | private BasicCheckRule checkType = BasicCheckRule.Trim; 20 | 21 | public TrimRuleTest() { 22 | this.data.setName("name"); 23 | this.data.setTypeClass(String.class); 24 | 25 | ValidationRule rule = data.getValidationRules().stream().filter(r -> r.getRuleName().equals(checkType.name())).findAny().get(); 26 | rule.setUse(true); 27 | } 28 | 29 | @Test 30 | public void test_fail_1() { 31 | obj.setName("taeon"); 32 | ruleTestUtil.getMsgChecker().checkDataInnerRules(this.data, this.obj); 33 | Assert.assertEquals(obj.getName(), "taeon"); 34 | } 35 | 36 | @Test 37 | public void test_fail_2() { 38 | obj.setName(null); 39 | ruleTestUtil.getMsgChecker().checkDataInnerRules(this.data, this.obj); 40 | Assert.assertEquals(obj.getName(), null); 41 | } 42 | 43 | @Test 44 | public void test_success_1() { 45 | obj.setName("hsim "); 46 | ruleTestUtil.getMsgChecker().checkDataInnerRules(this.data, this.obj); 47 | Assert.assertEquals(obj.getName(), "hsim"); 48 | } 49 | 50 | @Test 51 | public void test_success_2() { 52 | obj.setName(" taeon "); 53 | ruleTestUtil.getMsgChecker().checkDataInnerRules(this.data, this.obj); 54 | Assert.assertEquals(obj.getName(), "taeon"); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/test/java/hsim/checkpoint/test/rule/RuleTestUtil.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.test.rule; 2 | 3 | import hsim.checkpoint.core.component.ComponentMap; 4 | import hsim.checkpoint.core.component.validationRule.rule.ValidationRule; 5 | import hsim.checkpoint.core.component.validationRule.type.BasicCheckRule; 6 | import hsim.checkpoint.core.domain.ValidationData; 7 | import hsim.checkpoint.core.msg.MsgChecker; 8 | import hsim.checkpoint.core.store.ValidationRuleStore; 9 | import hsim.checkpoint.exception.ValidationLibException; 10 | import lombok.Getter; 11 | import org.junit.Assert; 12 | import org.springframework.http.HttpStatus; 13 | 14 | public class RuleTestUtil { 15 | 16 | @Getter 17 | private MsgChecker msgChecker = ComponentMap.get(MsgChecker.class); 18 | 19 | public ValidationData getDefaultValidationData() { 20 | ValidationData data = new ValidationData(); 21 | data.setValidationRules(ComponentMap.get(ValidationRuleStore.class).getRules()); 22 | data.getValidationRules().stream().forEach(r -> r.setUse(false)); 23 | return data; 24 | } 25 | 26 | public void checkRule(ValidationData data, Object obj, BasicCheckRule checkRule, Object inputValue, boolean success) { 27 | this.checkRule(data, obj, checkRule, inputValue, success, null); 28 | } 29 | 30 | public void checkRule(ValidationData data, Object obj, BasicCheckRule checkRule, Object inputValue, boolean success, HttpStatus failStatus) { 31 | try { 32 | msgChecker.checkDataInnerRules(data, obj); 33 | } catch (ValidationLibException e) { 34 | if (success) { 35 | Assert.fail(checkRule.name() + " FAIL - " + e.getMessage()); 36 | } 37 | if(failStatus != null){ 38 | Assert.assertEquals(e.getStatusCode(), failStatus); 39 | } 40 | return; 41 | } 42 | if (!success) { 43 | ValidationRule rule = data.getValidationRules().stream().filter(r -> r.getRuleName().equals(checkRule.name())).findAny().get(); 44 | Assert.fail(rule.getRuleName() + " is passed - standardValue : " + rule.getStandardValue() + " input value : " + inputValue); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/util/excel/PoiWorkBook.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.util.excel; 2 | 3 | import hsim.checkpoint.exception.ValidationLibException; 4 | import hsim.checkpoint.util.ValidationFileUtil; 5 | import lombok.Getter; 6 | import org.apache.poi.hssf.usermodel.HSSFWorkbook; 7 | import org.springframework.http.HttpStatus; 8 | 9 | import javax.servlet.http.HttpServletResponse; 10 | import java.io.IOException; 11 | 12 | /** 13 | * The type Poi work book. 14 | */ 15 | @Getter 16 | public class PoiWorkBook { 17 | 18 | private HSSFWorkbook workBook; 19 | 20 | /** 21 | * Instantiates a new Poi work book. 22 | */ 23 | public PoiWorkBook() { 24 | this.checkDependency(); 25 | this.workBook = new HSSFWorkbook(); 26 | } 27 | 28 | private void checkDependency() { 29 | try { 30 | Class.forName("org.apache.poi.hssf.usermodel.HSSFWorkbook"); 31 | } catch (ClassNotFoundException e) { 32 | throw new ValidationLibException("Not found apache POI library, must import poi to your maven or gradle dependency", HttpStatus.FAILED_DEPENDENCY); 33 | } 34 | } 35 | 36 | 37 | /** 38 | * Create sheet poi work sheet. 39 | * 40 | * @return the poi work sheet 41 | */ 42 | public PoiWorkSheet createSheet() { 43 | return new PoiWorkSheet(this, null); 44 | } 45 | 46 | /** 47 | * Create sheet poi work sheet. 48 | * 49 | * @param sheetName the sheet name 50 | * @return the poi work sheet 51 | */ 52 | public PoiWorkSheet createSheet(String sheetName) { 53 | return new PoiWorkSheet(this, sheetName); 54 | } 55 | 56 | /** 57 | * Write file. 58 | * 59 | * @param fn the fn 60 | * @param res the res 61 | */ 62 | public void writeFile(String fn, HttpServletResponse res) { 63 | 64 | ValidationFileUtil.initFileSendHeader(res, ValidationFileUtil.getEncodingFileName(fn + ".xls"), null); 65 | 66 | try { 67 | this.workBook.write(res.getOutputStream()); 68 | } catch (IOException e) { 69 | throw new ValidationLibException("workbook write error : " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR, e); 70 | } 71 | } 72 | 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/component/validationRule/rule/AssistType.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.component.validationRule.rule; 2 | 3 | import lombok.Getter; 4 | import lombok.NoArgsConstructor; 5 | 6 | /** 7 | * The type Assist type. 8 | */ 9 | @Getter 10 | @NoArgsConstructor 11 | public class AssistType { 12 | private boolean nullable; 13 | private boolean string; 14 | private boolean number; 15 | private boolean enumType; 16 | private boolean list; 17 | private boolean obj; 18 | 19 | /** 20 | * All assist type. 21 | * 22 | * @return the assist type 23 | */ 24 | public static AssistType all() { 25 | AssistType assistType = new AssistType(); 26 | assistType.nullable = true; 27 | assistType.string = true; 28 | assistType.number = true; 29 | assistType.enumType = true; 30 | assistType.list = true; 31 | assistType.obj = true; 32 | return assistType; 33 | } 34 | 35 | /** 36 | * Nullable assist type. 37 | * 38 | * @return the assist type 39 | */ 40 | public AssistType nullable() { 41 | this.nullable = true; 42 | return this; 43 | } 44 | 45 | /** 46 | * String assist type. 47 | * 48 | * @return the assist type 49 | */ 50 | public AssistType string() { 51 | this.string = true; 52 | return this; 53 | } 54 | 55 | /** 56 | * Number assist type. 57 | * 58 | * @return the assist type 59 | */ 60 | public AssistType number() { 61 | this.number = true; 62 | return this; 63 | } 64 | 65 | /** 66 | * Enum type assist type. 67 | * 68 | * @return the assist type 69 | */ 70 | public AssistType enumType() { 71 | this.enumType = true; 72 | return this; 73 | } 74 | 75 | /** 76 | * List assist type. 77 | * 78 | * @return the assist type 79 | */ 80 | public AssistType list() { 81 | this.list = true; 82 | return this; 83 | } 84 | 85 | /** 86 | * Obj assist type. 87 | * 88 | * @return the assist type 89 | */ 90 | public AssistType obj() { 91 | this.obj = true; 92 | return this; 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/test/java/hsim/checkpoint/test/rule/replace/DefaultValueRuleTest.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.test.rule.replace; 2 | 3 | import hsim.checkpoint.core.component.validationRule.rule.ValidationRule; 4 | import hsim.checkpoint.core.component.validationRule.type.BasicCheckRule; 5 | import hsim.checkpoint.core.domain.ValidationData; 6 | import hsim.checkpoint.model.user.UserModel; 7 | import hsim.checkpoint.test.rule.RuleTestUtil; 8 | import org.junit.Assert; 9 | import org.junit.FixMethodOrder; 10 | import org.junit.Test; 11 | import org.junit.runners.MethodSorters; 12 | 13 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 14 | public class DefaultValueRuleTest { 15 | 16 | private RuleTestUtil ruleTestUtil = new RuleTestUtil(); 17 | private UserModel obj = new UserModel(); 18 | private ValidationData data = ruleTestUtil.getDefaultValidationData(); 19 | private BasicCheckRule checkType = BasicCheckRule.DefaultValue; 20 | 21 | public DefaultValueRuleTest() { 22 | this.data.setName("nickName"); 23 | this.data.setTypeClass(String.class); 24 | 25 | ValidationRule rule = data.getValidationRules().stream().filter(r -> r.getRuleName().equals(checkType.name())).findAny().get(); 26 | 27 | rule.setUse(true); 28 | rule.setStandardValue("guest"); 29 | } 30 | 31 | @Test 32 | public void test_fail_1() { 33 | obj.setNickName(""); 34 | ruleTestUtil.getMsgChecker().checkDataInnerRules(this.data, this.obj); 35 | Assert.assertEquals(obj.getNickName(), "guest"); 36 | } 37 | 38 | @Test 39 | public void test_fail_2() { 40 | obj.setNickName(null); 41 | ruleTestUtil.getMsgChecker().checkDataInnerRules(this.data, this.obj); 42 | Assert.assertEquals(obj.getNickName(), "guest"); 43 | } 44 | 45 | @Test 46 | public void test_success_1() { 47 | obj.setNickName("hsim"); 48 | ruleTestUtil.getMsgChecker().checkDataInnerRules(this.data, this.obj); 49 | Assert.assertEquals(obj.getNickName(), "hsim"); 50 | } 51 | 52 | @Test 53 | public void test_success_2() { 54 | obj.setNickName("taeon"); 55 | ruleTestUtil.getMsgChecker().checkDataInnerRules(this.data, this.obj); 56 | Assert.assertEquals(obj.getNickName(), "taeon"); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/test/java/hsim/checkpoint/test/rule/replace/Base64RuleTest.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.test.rule.replace; 2 | 3 | import hsim.checkpoint.core.component.validationRule.rule.ValidationRule; 4 | import hsim.checkpoint.core.component.validationRule.type.BasicCheckRule; 5 | import hsim.checkpoint.core.domain.ValidationData; 6 | import hsim.checkpoint.model.user.UserModel; 7 | import hsim.checkpoint.test.rule.RuleTestUtil; 8 | import org.junit.Assert; 9 | import org.junit.FixMethodOrder; 10 | import org.junit.Test; 11 | import org.junit.runners.MethodSorters; 12 | 13 | import java.util.Base64; 14 | 15 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 16 | public class Base64RuleTest { 17 | 18 | private RuleTestUtil ruleTestUtil = new RuleTestUtil(); 19 | private UserModel obj = new UserModel(); 20 | private ValidationData data = ruleTestUtil.getDefaultValidationData(); 21 | private BasicCheckRule checkType = BasicCheckRule.Base64; 22 | 23 | public Base64RuleTest() { 24 | this.data.setName("email"); 25 | this.data.setTypeClass(String.class); 26 | 27 | ValidationRule rule = data.getValidationRules().stream().filter(r -> r.getRuleName().equals(checkType.name())).findAny().get(); 28 | rule.setUse(true); 29 | } 30 | 31 | @Test 32 | public void test_fail_1() { 33 | String plainText = "hsim@checkpoint.com"; 34 | obj.setEmail(plainText); 35 | ruleTestUtil.getMsgChecker().checkDataInnerRules(this.data, this.obj); 36 | Assert.assertEquals(obj.getEmail(), plainText); 37 | } 38 | 39 | @Test 40 | public void test_fail_2() { 41 | String plainText = "hsim@checkpoint.com"; 42 | String base64Text = Base64.getEncoder().encodeToString(plainText.getBytes()) + "##"; 43 | obj.setEmail(base64Text); 44 | ruleTestUtil.getMsgChecker().checkDataInnerRules(this.data, this.obj); 45 | Assert.assertEquals(obj.getEmail(), base64Text); 46 | } 47 | 48 | @Test 49 | public void test_success_1() { 50 | String plainText = "hsim@checkpoint.com"; 51 | String base64Text = Base64.getEncoder().encodeToString(plainText.getBytes()); 52 | obj.setEmail(base64Text); 53 | ruleTestUtil.getMsgChecker().checkDataInnerRules(this.data, this.obj); 54 | Assert.assertEquals(obj.getEmail(), plainText); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/test/java/hsim/checkpoint/test/helper/HelperTest.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.test.helper; 2 | 3 | import hsim.checkpoint.core.component.ComponentMap; 4 | import hsim.checkpoint.core.component.validationRule.type.BaseValidationCheck; 5 | import hsim.checkpoint.core.component.validationRule.rule.AssistType; 6 | import hsim.checkpoint.core.component.validationRule.rule.ValidationRule; 7 | import hsim.checkpoint.core.component.validationRule.type.BasicCheckRule; 8 | import hsim.checkpoint.core.component.validationRule.type.StandardValueType; 9 | import hsim.checkpoint.core.domain.ValidationData; 10 | import hsim.checkpoint.core.repository.ValidationDataRepository; 11 | import hsim.checkpoint.core.store.ValidationRuleStore; 12 | import hsim.checkpoint.exception.ValidationLibException; 13 | import hsim.checkpoint.helper.CheckPointHelper; 14 | import hsim.checkpoint.test.rule.check.MandatoryRuleTest; 15 | import org.junit.Assert; 16 | import org.junit.Test; 17 | import org.springframework.http.HttpStatus; 18 | 19 | public class HelperTest { 20 | 21 | private ValidationDataRepository validationDataRepository = ComponentMap.get(ValidationDataRepository.class); 22 | 23 | @Test 24 | public void test_addrule() { 25 | 26 | this.validationDataRepository.refresh(); 27 | 28 | CheckPointHelper checkPointHelper = new CheckPointHelper(); 29 | checkPointHelper.addValidationRule("ruleTest", StandardValueType.NUMBER, new TestRule(), new AssistType().string()).flush(); 30 | checkPointHelper.replaceExceptionCallback(BasicCheckRule.Mandatory, new MandatoryRuleTest.MandatoryCallback()); 31 | 32 | ValidationRuleStore ruleStore = ComponentMap.get(ValidationRuleStore.class); 33 | ValidationRule rule = ruleStore.getRules().stream().filter(r -> r.getRuleName().equals("ruleTest")).findAny().orElse(null); 34 | Assert.assertNotNull(rule); 35 | } 36 | 37 | static class TestRule implements BaseValidationCheck { 38 | 39 | 40 | @Override 41 | public boolean check(Object value, Object standardValue) { 42 | return true; 43 | } 44 | 45 | @Override 46 | public Object replace(Object value, Object standardValue, ValidationData param) { 47 | return null; 48 | } 49 | 50 | @Override 51 | public void exception(ValidationData param, Object inputValue, Object standardValue) { 52 | throw new ValidationLibException("testrule", HttpStatus.BAD_REQUEST); 53 | } 54 | 55 | } 56 | } 57 | 58 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/msg/MethodSyncor.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.msg; 2 | 3 | import hsim.checkpoint.config.ValidationConfig; 4 | import hsim.checkpoint.core.annotation.ValidationBody; 5 | import hsim.checkpoint.core.annotation.ValidationParam; 6 | import hsim.checkpoint.core.component.ComponentMap; 7 | import hsim.checkpoint.core.component.DetailParam; 8 | import hsim.checkpoint.core.domain.ReqUrl; 9 | import hsim.checkpoint.core.domain.ValidationData; 10 | import hsim.checkpoint.core.repository.ValidationDataRepository; 11 | import hsim.checkpoint.core.store.ValidationStore; 12 | import hsim.checkpoint.type.ParamType; 13 | import hsim.checkpoint.util.AnnotationScanner; 14 | import lombok.extern.slf4j.Slf4j; 15 | 16 | import java.util.Arrays; 17 | import java.util.List; 18 | import java.util.stream.Collectors; 19 | 20 | /** 21 | * The type Method syncor. 22 | */ 23 | @Slf4j 24 | public class MethodSyncor { 25 | 26 | private ValidationDataRepository validationDataRepository = ComponentMap.get(ValidationDataRepository.class); 27 | private ValidationStore validationStore = ComponentMap.get(ValidationStore.class); 28 | private AnnotationScanner annotationScanner = ComponentMap.get(AnnotationScanner.class); 29 | 30 | /** 31 | * Instantiates a new Method syncor. 32 | */ 33 | public MethodSyncor() { 34 | } 35 | 36 | /** 37 | * Update method key async. 38 | */ 39 | public void updateMethodKeyAsync() { 40 | new Thread(this::updateMethodKey).start(); 41 | } 42 | 43 | /** 44 | * Update method key. 45 | */ 46 | public void updateMethodKey() { 47 | Arrays.stream(ParamType.values()).forEach(paramType -> this.syncMethodKey(paramType)); 48 | 49 | this.validationDataRepository.flush(); 50 | this.validationStore.refresh(); 51 | log.info("[METHOD_KEY_SYNC] Complete"); 52 | } 53 | 54 | private void syncMethodKey(ParamType paramType) { 55 | 56 | List params = this.annotationScanner.getParameterWithAnnotation(paramType.equals(ParamType.BODY) ? ValidationBody.class : ValidationParam.class); 57 | 58 | params.forEach(param -> { 59 | List urls = param.getReqUrls(); 60 | urls.forEach(url -> { 61 | List datas = this.validationDataRepository.findByParamTypeAndMethodAndUrl(paramType, url.getMethod(), url.getUrl()); 62 | if (!datas.isEmpty() && !datas.get(0).diffKey(param)) { 63 | this.validationDataRepository.saveAll(datas.stream().map(data -> data.updateKey(param)).collect(Collectors.toList())); 64 | } 65 | }); 66 | }); 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/test/java/hsim/checkpoint/test/rule/check/MandatoryRuleTest.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.test.rule.check; 2 | 3 | import hsim.checkpoint.core.component.validationRule.callback.ValidationInvalidCallback; 4 | import hsim.checkpoint.core.component.validationRule.rule.ValidationRule; 5 | import hsim.checkpoint.core.component.validationRule.type.BasicCheckRule; 6 | import hsim.checkpoint.core.domain.ValidationData; 7 | import hsim.checkpoint.exception.ValidationLibException; 8 | import hsim.checkpoint.helper.CheckPointHelper; 9 | import hsim.checkpoint.model.user.UserModel; 10 | import hsim.checkpoint.test.rule.RuleTestUtil; 11 | import org.junit.FixMethodOrder; 12 | import org.junit.Test; 13 | import org.junit.runners.MethodSorters; 14 | import org.springframework.http.HttpStatus; 15 | 16 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 17 | public class MandatoryRuleTest { 18 | 19 | private RuleTestUtil ruleTestUtil = new RuleTestUtil(); 20 | private UserModel obj = new UserModel(); 21 | private ValidationData data = ruleTestUtil.getDefaultValidationData(); 22 | private BasicCheckRule checkType = BasicCheckRule.Mandatory; 23 | 24 | public MandatoryRuleTest() { 25 | this.data.setName("loginId"); 26 | 27 | ValidationRule rule = data.getValidationRules().stream().filter(r -> r.getRuleName().equals(checkType.name())).findAny().get(); 28 | rule.setUse(true); 29 | } 30 | 31 | @Test 32 | public void test_fail_1() { 33 | obj.setLoginId(null); 34 | ruleTestUtil.checkRule(data, obj, checkType, obj.getLoginId(), false); 35 | } 36 | 37 | @Test 38 | public void test_fail_2() { 39 | obj.setLoginId(""); 40 | ruleTestUtil.checkRule(data, obj, checkType, obj.getLoginId(), false); 41 | } 42 | 43 | @Test 44 | public void test_success_1() { 45 | obj.setLoginId("hsim"); 46 | ruleTestUtil.checkRule(data, obj, checkType, obj.getLoginId(), true); 47 | } 48 | 49 | @Test 50 | public void test_success_2() { 51 | obj.setLoginId("lhs1553"); 52 | ruleTestUtil.checkRule(data, obj, checkType, obj.getLoginId(), true); 53 | } 54 | 55 | @Test 56 | public void test_callback_change() { 57 | CheckPointHelper helper = new CheckPointHelper(); 58 | helper.replaceExceptionCallback(this.checkType, new MandatoryCallback()); 59 | 60 | obj.setLoginId(null); 61 | ruleTestUtil.checkRule(data, obj, checkType, obj.getLoginId(), false, HttpStatus.NO_CONTENT); 62 | } 63 | 64 | public static class MandatoryCallback implements ValidationInvalidCallback { 65 | @Override 66 | public void exception(ValidationData param, Object inputValue, Object standardValue) { 67 | throw new ValidationLibException(param.getName() + " order exception", HttpStatus.NO_CONTENT); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/domain/BasicCheckInfo.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.domain; 2 | 3 | import hsim.checkpoint.core.annotation.ValidationBody; 4 | import hsim.checkpoint.core.component.DetailParam; 5 | import hsim.checkpoint.type.ParamType; 6 | import hsim.checkpoint.util.ValidationHttpUtil; 7 | import lombok.Getter; 8 | import lombok.ToString; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.springframework.core.MethodParameter; 11 | 12 | import javax.servlet.http.HttpServletRequest; 13 | 14 | /** 15 | * The type Basic check info. 16 | */ 17 | @ToString 18 | @Getter 19 | @Slf4j 20 | public class BasicCheckInfo { 21 | 22 | private ParamType paramType; 23 | private ReqUrl reqUrl; 24 | private DetailParam detailParam; 25 | private HttpServletRequest req; 26 | private MethodParameter parameter; 27 | private String body; 28 | 29 | /** 30 | * Instantiates a new Basic check info. 31 | * 32 | * @param httpReq the http req 33 | * @param param the param 34 | * @param log the log 35 | */ 36 | public BasicCheckInfo(HttpServletRequest httpReq, MethodParameter param, boolean log) { 37 | this.req = httpReq; 38 | this.parameter = param; 39 | 40 | this.paramType = this.parameter.getParameterAnnotation(ValidationBody.class) != null ? ParamType.BODY : ParamType.QUERY_PARAM; 41 | 42 | this.detailParam = new DetailParam(parameter.getParameterType(), parameter.getMethod(), null); 43 | this.reqUrl = new ReqUrl(this.req); 44 | 45 | if (this.paramType.equals(ParamType.BODY)) { 46 | this.body = ValidationHttpUtil.readBody(this.req); 47 | 48 | if (log) { 49 | this.logging(); 50 | } 51 | } 52 | } 53 | 54 | /** 55 | * Is url mapping boolean. 56 | * 57 | * @return the boolean 58 | */ 59 | public boolean isUrlMapping() { 60 | if (this.detailParam == null) { 61 | return false; 62 | } 63 | return this.detailParam.isUrlMapping(); 64 | } 65 | 66 | /** 67 | * Is list body boolean. 68 | * 69 | * @return the boolean 70 | */ 71 | public boolean isListBody() { 72 | return (this.parameter.getParameterType().equals(java.util.List.class)); 73 | } 74 | 75 | /** 76 | * Logging. 77 | */ 78 | public void logging() { 79 | if (this.body == null) { 80 | return; 81 | } 82 | 83 | log.info("[" + this.reqUrl.getMethod() + "]::[" + this.reqUrl.getUrl() + "] ::"); 84 | log.info(this.body); 85 | } 86 | 87 | /** 88 | * Gets unique key. 89 | * 90 | * @return the unique key 91 | */ 92 | public String getUniqueKey() { 93 | return this.isUrlMapping() ? this.reqUrl.getUniqueKey() : this.detailParam.getMethodKey(); 94 | } 95 | 96 | } 97 | -------------------------------------------------------------------------------- /src/test/java/hsim/checkpoint/test/rule/check/BlackListCheck.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.test.rule.check; 2 | 3 | import hsim.checkpoint.core.component.validationRule.callback.ValidationInvalidCallback; 4 | import hsim.checkpoint.core.component.validationRule.rule.ValidationRule; 5 | import hsim.checkpoint.core.component.validationRule.type.BasicCheckRule; 6 | import hsim.checkpoint.core.domain.ValidationData; 7 | import hsim.checkpoint.exception.ValidationLibException; 8 | import hsim.checkpoint.helper.CheckPointHelper; 9 | import hsim.checkpoint.model.user.UserModel; 10 | import hsim.checkpoint.test.rule.RuleTestUtil; 11 | import org.junit.FixMethodOrder; 12 | import org.junit.Test; 13 | import org.junit.runners.MethodSorters; 14 | import org.springframework.http.HttpStatus; 15 | 16 | import java.util.Arrays; 17 | 18 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 19 | public class BlackListCheck { 20 | 21 | private RuleTestUtil ruleTestUtil = new RuleTestUtil(); 22 | private UserModel obj = new UserModel(); 23 | private ValidationData data = ruleTestUtil.getDefaultValidationData(); 24 | private BasicCheckRule checkType = BasicCheckRule.BlackList; 25 | 26 | public BlackListCheck() { 27 | this.data.setName("name"); 28 | 29 | ValidationRule rule = data.getValidationRules().stream().filter(r -> r.getRuleName().equals(checkType.name())).findAny().get(); 30 | rule.setUse(true); 31 | rule.setStandardValue(Arrays.asList(new String[]{"-", "~", "_"})); 32 | } 33 | 34 | @Test 35 | public void test_fail_1() { 36 | obj.setName("~"); 37 | ruleTestUtil.checkRule(data, obj, checkType, obj.getName(), false); 38 | } 39 | 40 | @Test 41 | public void test_fail_2() { 42 | obj.setName("_"); 43 | ruleTestUtil.checkRule(data, obj, checkType, obj.getName(), false); 44 | } 45 | 46 | @Test 47 | public void test_success_1() { 48 | obj.setName("--"); 49 | ruleTestUtil.checkRule(data, obj, checkType, obj.getName(), true); 50 | } 51 | 52 | @Test 53 | public void test_success_2() { 54 | obj.setName("__"); 55 | ruleTestUtil.checkRule(data, obj, checkType, obj.getName(), true); 56 | } 57 | 58 | @Test 59 | public void test_callback_change() { 60 | CheckPointHelper helper = new CheckPointHelper(); 61 | helper.replaceExceptionCallback(this.checkType, new WhiteListCallback()); 62 | 63 | obj.setName("~"); 64 | ruleTestUtil.checkRule(data, obj, checkType, obj.getName(), false, HttpStatus.NOT_ACCEPTABLE); 65 | } 66 | 67 | public static class WhiteListCallback implements ValidationInvalidCallback { 68 | @Override 69 | public void exception(ValidationData param, Object inputValue, Object standardValue) { 70 | throw new ValidationLibException(param.getName() + " order exception", HttpStatus.NOT_ACCEPTABLE); 71 | } 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/test/java/hsim/checkpoint/test/rule/check/PatternRuleTest.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.test.rule.check; 2 | 3 | import hsim.checkpoint.core.component.validationRule.callback.ValidationInvalidCallback; 4 | import hsim.checkpoint.core.component.validationRule.rule.ValidationRule; 5 | import hsim.checkpoint.core.component.validationRule.type.BasicCheckRule; 6 | import hsim.checkpoint.core.domain.ValidationData; 7 | import hsim.checkpoint.exception.ValidationLibException; 8 | import hsim.checkpoint.helper.CheckPointHelper; 9 | import hsim.checkpoint.model.user.UserModel; 10 | import hsim.checkpoint.test.rule.RuleTestUtil; 11 | import org.junit.FixMethodOrder; 12 | import org.junit.Test; 13 | import org.junit.runners.MethodSorters; 14 | import org.springframework.http.HttpStatus; 15 | 16 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 17 | public class PatternRuleTest { 18 | 19 | private RuleTestUtil ruleTestUtil = new RuleTestUtil(); 20 | private UserModel obj = new UserModel(); 21 | private ValidationData data = ruleTestUtil.getDefaultValidationData(); 22 | private BasicCheckRule checkType = BasicCheckRule.Pattern; 23 | 24 | public PatternRuleTest() { 25 | this.data.setName("email"); 26 | 27 | ValidationRule rule = data.getValidationRules().stream().filter(r -> r.getRuleName().equals(checkType.name())).findAny().get(); 28 | rule.setUse(true); 29 | rule.setStandardValue("(\\w+\\.)*\\w+@(\\w+\\.)+[A-Za-z]+"); 30 | } 31 | 32 | @Test 33 | public void test_fail_1() { 34 | obj.setEmail("hsim@checkpoint.com."); 35 | ruleTestUtil.checkRule(data, obj, checkType, obj.getEmail(), false); 36 | } 37 | 38 | @Test 39 | public void test_fail_2() { 40 | obj.setEmail("taeon@checkpoint."); 41 | ruleTestUtil.checkRule(data, obj, checkType, obj.getEmail(), false); 42 | } 43 | 44 | @Test 45 | public void test_success_1() { 46 | obj.setEmail("hsim@checkpoint.com"); 47 | ruleTestUtil.checkRule(data, obj, checkType, obj.getEmail(), true); 48 | } 49 | 50 | @Test 51 | public void test_success_2() { 52 | obj.setEmail("taeon@checkpoint.com"); 53 | ruleTestUtil.checkRule(data, obj, checkType, obj.getEmail(), true); 54 | } 55 | 56 | @Test 57 | public void test_callback_change() { 58 | CheckPointHelper helper = new CheckPointHelper(); 59 | helper.replaceExceptionCallback(this.checkType, new PatternCallback()); 60 | 61 | obj.setEmail("taeon"); 62 | ruleTestUtil.checkRule(data, obj, checkType, obj.getEmail(), false, HttpStatus.NOT_ACCEPTABLE); 63 | } 64 | 65 | public static class PatternCallback implements ValidationInvalidCallback { 66 | @Override 67 | public void exception(ValidationData param, Object inputValue, Object standardValue) { 68 | throw new ValidationLibException(param.getName() + " order exception", HttpStatus.NOT_ACCEPTABLE); 69 | } 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/test/java/hsim/checkpoint/test/rule/check/MinSizeRuleTest.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.test.rule.check; 2 | 3 | import hsim.checkpoint.core.component.validationRule.callback.ValidationInvalidCallback; 4 | import hsim.checkpoint.core.component.validationRule.rule.ValidationRule; 5 | import hsim.checkpoint.core.component.validationRule.type.BasicCheckRule; 6 | import hsim.checkpoint.core.domain.ValidationData; 7 | import hsim.checkpoint.exception.ValidationLibException; 8 | import hsim.checkpoint.helper.CheckPointHelper; 9 | import hsim.checkpoint.model.product.ProductModel; 10 | import hsim.checkpoint.test.rule.RuleTestUtil; 11 | import org.junit.FixMethodOrder; 12 | import org.junit.Test; 13 | import org.junit.runners.MethodSorters; 14 | import org.springframework.http.HttpStatus; 15 | 16 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 17 | public class MinSizeRuleTest { 18 | 19 | private RuleTestUtil ruleTestUtil = new RuleTestUtil(); 20 | private ProductModel obj = new ProductModel(); 21 | private ValidationData data = ruleTestUtil.getDefaultValidationData(); 22 | private BasicCheckRule checkType = BasicCheckRule.MinSize; 23 | 24 | public MinSizeRuleTest() { 25 | this.data.setName("discountPercent"); 26 | 27 | ValidationRule rule = data.getValidationRules().stream().filter(r -> r.getRuleName().equals(checkType.name())).findAny().get(); 28 | rule.setUse(true); 29 | rule.setStandardValue(0); 30 | } 31 | 32 | @Test 33 | public void test_fail_1() { 34 | obj.setDiscountPercent(-1.0); 35 | ruleTestUtil.checkRule(data, obj, checkType, obj.getDiscountPercent(), false); 36 | } 37 | 38 | @Test 39 | public void test_fail_2() { 40 | obj.setDiscountPercent(-0.1); 41 | ruleTestUtil.checkRule(data, obj, checkType, obj.getDiscountPercent(), false); 42 | } 43 | 44 | @Test 45 | public void test_success_1() { 46 | obj.setDiscountPercent(10.0); 47 | ruleTestUtil.checkRule(data, obj, checkType, obj.getDiscountPercent(), true); 48 | } 49 | 50 | @Test 51 | public void test_success_2() { 52 | obj.setDiscountPercent(100.0); 53 | ruleTestUtil.checkRule(data, obj, checkType, obj.getDiscountPercent(), true); 54 | } 55 | 56 | @Test 57 | public void test_callback_change() { 58 | CheckPointHelper helper = new CheckPointHelper(); 59 | helper.replaceExceptionCallback(this.checkType, new MinSizeCallback()); 60 | 61 | obj.setDiscountPercent(-100.0); 62 | ruleTestUtil.checkRule(data, obj, checkType, obj.getDiscountPercent(), false, HttpStatus.NOT_ACCEPTABLE); 63 | } 64 | 65 | public static class MinSizeCallback implements ValidationInvalidCallback { 66 | @Override 67 | public void exception(ValidationData param, Object inputValue, Object standardValue) { 68 | throw new ValidationLibException(param.getName() + " order exception", HttpStatus.NOT_ACCEPTABLE); 69 | } 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/test/java/hsim/checkpoint/test/rule/check/MaxSizeRuleTest.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.test.rule.check; 2 | 3 | import hsim.checkpoint.core.component.validationRule.callback.ValidationInvalidCallback; 4 | import hsim.checkpoint.core.component.validationRule.rule.ValidationRule; 5 | import hsim.checkpoint.core.component.validationRule.type.BasicCheckRule; 6 | import hsim.checkpoint.core.domain.ValidationData; 7 | import hsim.checkpoint.exception.ValidationLibException; 8 | import hsim.checkpoint.helper.CheckPointHelper; 9 | import hsim.checkpoint.model.product.ProductModel; 10 | import hsim.checkpoint.test.rule.RuleTestUtil; 11 | import org.junit.FixMethodOrder; 12 | import org.junit.Test; 13 | import org.junit.runners.MethodSorters; 14 | import org.springframework.http.HttpStatus; 15 | 16 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 17 | public class MaxSizeRuleTest { 18 | 19 | private RuleTestUtil ruleTestUtil = new RuleTestUtil(); 20 | private ProductModel obj = new ProductModel(); 21 | private ValidationData data = ruleTestUtil.getDefaultValidationData(); 22 | private BasicCheckRule checkType = BasicCheckRule.MaxSize; 23 | 24 | public MaxSizeRuleTest() { 25 | this.data.setName("discountPercent"); 26 | 27 | ValidationRule rule = data.getValidationRules().stream().filter(r -> r.getRuleName().equals(checkType.name())).findAny().get(); 28 | rule.setUse(true); 29 | rule.setStandardValue(100.0); 30 | } 31 | 32 | @Test 33 | public void test_fail_1() { 34 | obj.setDiscountPercent(101.0); 35 | ruleTestUtil.checkRule(data, obj, checkType, obj.getDiscountPercent(), false); 36 | } 37 | 38 | @Test 39 | public void test_fail_2() { 40 | obj.setDiscountPercent(100.1); 41 | ruleTestUtil.checkRule(data, obj, checkType, obj.getDiscountPercent(), false); 42 | } 43 | 44 | @Test 45 | public void test_success_1() { 46 | obj.setDiscountPercent(-100.0); 47 | ruleTestUtil.checkRule(data, obj, checkType, obj.getDiscountPercent(), true); 48 | } 49 | 50 | @Test 51 | public void test_success_2() { 52 | obj.setDiscountPercent(99.9); 53 | ruleTestUtil.checkRule(data, obj, checkType, obj.getDiscountPercent(), true); 54 | } 55 | 56 | @Test 57 | public void test_callback_change() { 58 | CheckPointHelper helper = new CheckPointHelper(); 59 | helper.replaceExceptionCallback(this.checkType, new MaxDiscountPercentCallback()); 60 | 61 | obj.setDiscountPercent(100.1); 62 | ruleTestUtil.checkRule(data, obj, checkType, obj.getDiscountPercent(), false, HttpStatus.NOT_ACCEPTABLE); 63 | } 64 | 65 | public static class MaxDiscountPercentCallback implements ValidationInvalidCallback { 66 | @Override 67 | public void exception(ValidationData param, Object inputValue, Object standardValue) { 68 | throw new ValidationLibException(param.getName() + " order exception", HttpStatus.NOT_ACCEPTABLE); 69 | } 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/exception/ValidationLibException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package hsim.checkpoint.exception; 5 | 6 | import lombok.Getter; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.web.client.HttpClientErrorException; 9 | 10 | /** 11 | * Create by hsim on 2018. 1. 25. 12 | */ 13 | @Getter 14 | public class ValidationLibException extends RuntimeException { 15 | 16 | private static final long serialVersionUID = 1L; 17 | 18 | private HttpStatus statusCode; 19 | 20 | /** 21 | * Instantiates a new Validation lib exception. 22 | * 23 | * @param statusCode the status code 24 | */ 25 | public ValidationLibException(HttpStatus statusCode) { 26 | super(); 27 | this.statusCode = statusCode; 28 | } 29 | 30 | /** 31 | * Instantiates a new Validation lib exception. 32 | * 33 | * @param message the message 34 | */ 35 | public ValidationLibException(String message) { 36 | super(message); 37 | } 38 | 39 | /** 40 | * Instantiates a new Validation lib exception. 41 | * 42 | * @param throwable the throwable 43 | */ 44 | public ValidationLibException(Throwable throwable) { 45 | super(throwable); 46 | } 47 | 48 | /** 49 | * Instantiates a new Validation lib exception. 50 | * 51 | * @param message the message 52 | * @param throwable the throwable 53 | */ 54 | public ValidationLibException(String message, Throwable throwable) { 55 | super(message, throwable); 56 | } 57 | 58 | /** 59 | * Instantiates a new Validation lib exception. 60 | * 61 | * @param statusCode the status code 62 | * @param throwable the throwable 63 | */ 64 | public ValidationLibException(HttpStatus statusCode, Throwable throwable) { 65 | super(throwable); 66 | this.statusCode = statusCode; 67 | } 68 | 69 | /** 70 | * Instantiates a new Validation lib exception. 71 | * 72 | * @param message the message 73 | * @param statusCode the status code 74 | */ 75 | public ValidationLibException(String message, HttpStatus statusCode) { 76 | super(message); 77 | this.statusCode = statusCode; 78 | } 79 | 80 | /** 81 | * Instantiates a new Validation lib exception. 82 | * 83 | * @param e the e 84 | */ 85 | public ValidationLibException(HttpClientErrorException e) { 86 | super(e.getMessage()); 87 | this.statusCode = e.getStatusCode(); 88 | } 89 | 90 | /** 91 | * Instantiates a new Validation lib exception. 92 | * 93 | * @param message the message 94 | * @param statusCode the status code 95 | * @param throwable the throwable 96 | */ 97 | public ValidationLibException(String message, HttpStatus statusCode, Throwable throwable) { 98 | super(message, throwable); 99 | this.statusCode = statusCode; 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/repository/index/map/ValidationDataIndexMap.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.repository.index.map; 2 | 3 | import hsim.checkpoint.core.component.ComponentMap; 4 | import hsim.checkpoint.core.domain.ReqUrl; 5 | import hsim.checkpoint.core.domain.ValidationData; 6 | import hsim.checkpoint.core.repository.index.idx.IdIndex; 7 | import hsim.checkpoint.core.repository.index.idx.MethodAndUrlIndex; 8 | import hsim.checkpoint.core.repository.index.idx.ValidationDataIndex; 9 | import hsim.checkpoint.core.repository.index.util.ValidationIndexUtil; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | /** 15 | * The type Validation data index map. 16 | */ 17 | public class ValidationDataIndexMap { 18 | 19 | private ValidationDataIndex methodAndUrlIndex = ComponentMap.get(MethodAndUrlIndex.class); 20 | private ValidationDataIndex idIndex = ComponentMap.get(IdIndex.class); 21 | 22 | private ValidationDataIndex[] idxs = {this.methodAndUrlIndex, this.idIndex}; 23 | 24 | /** 25 | * Gets url list. 26 | * 27 | * @return the url list 28 | */ 29 | public List getUrlList() { 30 | List reqUrls = new ArrayList<>(); 31 | for (String key : this.methodAndUrlIndex.getMap().keySet()) { 32 | List datas = this.methodAndUrlIndex.getMap().get(key); 33 | if (!datas.isEmpty()) { 34 | reqUrls.add(new ReqUrl(datas.get(0).getMethod(), datas.get(0).getUrl())); 35 | } 36 | } 37 | return reqUrls; 38 | } 39 | 40 | /** 41 | * Find by id validation data. 42 | * 43 | * @param id the id 44 | * @return the validation data 45 | */ 46 | public ValidationData findById(Long id) { 47 | List datas = this.idIndex.get(ValidationIndexUtil.makeKey(String.valueOf(id))); 48 | if (datas.isEmpty()) { 49 | return null; 50 | } 51 | return datas.get(0); 52 | } 53 | 54 | /** 55 | * Find by method and url list. 56 | * 57 | * @param method the method 58 | * @param url the url 59 | * @return the list 60 | */ 61 | public List findByMethodAndUrl(String method, String url) { 62 | return this.methodAndUrlIndex.get(ValidationIndexUtil.makeKey(method, url)); 63 | } 64 | 65 | /** 66 | * Add index. 67 | * 68 | * @param data the data 69 | */ 70 | public void addIndex(ValidationData data) { 71 | for (ValidationDataIndex idx : this.idxs) { 72 | ValidationIndexUtil.addIndexData(data, idx); 73 | } 74 | } 75 | 76 | /** 77 | * Remove index. 78 | * 79 | * @param data the data 80 | */ 81 | public void removeIndex(ValidationData data) { 82 | for (ValidationDataIndex idx : this.idxs) { 83 | ValidationIndexUtil.removeIndexData(data, idx); 84 | } 85 | } 86 | 87 | /** 88 | * Refresh. 89 | */ 90 | public void refresh() { 91 | for (ValidationDataIndex idx : this.idxs) { 92 | idx.refresh(); 93 | } 94 | } 95 | 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/component/DetailParam.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.component; 2 | 3 | import hsim.checkpoint.core.annotation.ValidationUrlMapping; 4 | import hsim.checkpoint.core.domain.ReqUrl; 5 | import hsim.checkpoint.util.AnnotationUtil; 6 | import lombok.Getter; 7 | import lombok.ToString; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RequestMethod; 10 | 11 | import java.lang.reflect.Method; 12 | import java.util.ArrayList; 13 | import java.util.List; 14 | 15 | /** 16 | * The type Detail param. 17 | */ 18 | @Getter 19 | @ToString 20 | public class DetailParam { 21 | 22 | private Class parameterType; 23 | private Method parentMethod; 24 | private Class parentClass; 25 | 26 | /** 27 | * Instantiates a new Detail param. 28 | * 29 | * @param paramType the param class 30 | * @param method the method 31 | * @param parentClass the parent class 32 | */ 33 | public DetailParam(Class paramType, Method method, Class parentClass) { 34 | this.parameterType = paramType; 35 | this.parentMethod = method; 36 | this.parentClass = parentClass; 37 | } 38 | 39 | /** 40 | * Is url mapping boolean. 41 | * 42 | * @return the boolean 43 | */ 44 | public boolean isUrlMapping() { 45 | if (parentMethod == null) { 46 | return false; 47 | } 48 | return this.parentMethod.getAnnotation(ValidationUrlMapping.class) != null; 49 | } 50 | 51 | private String getRequestMappingUrl(String[] value) { 52 | if (value == null) { 53 | return ""; 54 | } 55 | 56 | String url = ""; 57 | for (String s : value) { 58 | url += s; 59 | } 60 | return url; 61 | } 62 | 63 | private String getClassMappingUrl(Class parentClass) { 64 | String url = ""; 65 | 66 | RequestMapping requestMapping = (RequestMapping) AnnotationUtil.getAnnotation(parentClass.getAnnotations(), RequestMapping.class); 67 | if (requestMapping != null) { 68 | url += this.getRequestMappingUrl(requestMapping.value()); 69 | } 70 | return url; 71 | } 72 | 73 | /** 74 | * Gets req urls. 75 | * 76 | * @return the req urls 77 | */ 78 | public List getReqUrls() { 79 | 80 | String url = this.getClassMappingUrl(this.getParentClass()); 81 | RequestAnnotation requestAnnotation = new RequestAnnotation(this.getParentMethod()); 82 | 83 | url += this.getRequestMappingUrl(requestAnnotation.getValue()); 84 | 85 | List list = new ArrayList<>(); 86 | 87 | for (RequestMethod requestMethod : requestAnnotation.getMethod()) { 88 | list.add(new ReqUrl(requestMethod.name(), url)); 89 | } 90 | return list; 91 | } 92 | 93 | /** 94 | * Gets method key. 95 | * 96 | * @return the method key 97 | */ 98 | public String getMethodKey() { 99 | return String.valueOf(this.parentMethod.hashCode()); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/component/RequestAnnotation.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.component; 2 | 3 | import hsim.checkpoint.util.AnnotationUtil; 4 | import org.springframework.web.bind.annotation.*; 5 | 6 | import java.lang.reflect.Method; 7 | 8 | /** 9 | * The type Request annotation. 10 | */ 11 | public class RequestAnnotation { 12 | 13 | private RequestMapping requestMapping; 14 | private PostMapping postMapping; 15 | private PutMapping putMapping; 16 | private DeleteMapping deleteMapping; 17 | private GetMapping getMapping; 18 | private PatchMapping patchMapping; 19 | 20 | /** 21 | * Instantiates a new Request annotation. 22 | * 23 | * @param method the method 24 | */ 25 | public RequestAnnotation(Method method) { 26 | this.requestMapping = (RequestMapping) AnnotationUtil.getAnnotation(method.getAnnotations(), RequestMapping.class); 27 | this.postMapping = (PostMapping) AnnotationUtil.getAnnotation(method.getAnnotations(), PostMapping.class); 28 | this.putMapping = (PutMapping) AnnotationUtil.getAnnotation(method.getAnnotations(), PutMapping.class); 29 | this.deleteMapping = (DeleteMapping) AnnotationUtil.getAnnotation(method.getAnnotations(), DeleteMapping.class); 30 | this.getMapping = (GetMapping) AnnotationUtil.getAnnotation(method.getAnnotations(), GetMapping.class); 31 | this.patchMapping= (PatchMapping) AnnotationUtil.getAnnotation(method.getAnnotations(), PatchMapping.class); 32 | 33 | } 34 | 35 | /** 36 | * Get method request method [ ]. 37 | * 38 | * @return the request method [ ] 39 | */ 40 | public RequestMethod[] getMethod() { 41 | if (this.requestMapping != null) { 42 | return this.requestMapping.method(); 43 | } 44 | if (this.postMapping != null) { 45 | return new RequestMethod[]{(RequestMethod.POST)}; 46 | } 47 | if (this.putMapping != null) { 48 | return new RequestMethod[]{(RequestMethod.PUT)}; 49 | } 50 | if (this.deleteMapping != null) { 51 | return new RequestMethod[]{(RequestMethod.DELETE)}; 52 | } 53 | if (this.getMapping != null) { 54 | return new RequestMethod[]{(RequestMethod.GET)}; 55 | } 56 | if (this.patchMapping!= null) { 57 | return new RequestMethod[]{(RequestMethod.PATCH)}; 58 | } 59 | return null; 60 | } 61 | 62 | /** 63 | * Get value string [ ]. 64 | * 65 | * @return the string [ ] 66 | */ 67 | public String[] getValue() { 68 | if (this.requestMapping != null) { 69 | return this.requestMapping.value(); 70 | } 71 | if (this.postMapping != null) { 72 | return this.postMapping.value(); 73 | } 74 | if (this.putMapping != null) { 75 | return this.putMapping.value(); 76 | } 77 | if (this.deleteMapping != null) { 78 | return this.deleteMapping.value(); 79 | } 80 | if (this.getMapping != null) { 81 | return this.getMapping.value(); 82 | } 83 | if (this.patchMapping!= null) { 84 | return this.patchMapping.value(); 85 | } 86 | return null; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/test/java/hsim/checkpoint/test/rule/check/WhiteListCheck.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.test.rule.check; 2 | 3 | import hsim.checkpoint.core.component.validationRule.callback.ValidationInvalidCallback; 4 | import hsim.checkpoint.core.component.validationRule.rule.ValidationRule; 5 | import hsim.checkpoint.core.component.validationRule.type.BasicCheckRule; 6 | import hsim.checkpoint.core.domain.ValidationData; 7 | import hsim.checkpoint.exception.ValidationLibException; 8 | import hsim.checkpoint.helper.CheckPointHelper; 9 | import hsim.checkpoint.model.user.UserModel; 10 | import hsim.checkpoint.model.user.type.Membership; 11 | import hsim.checkpoint.test.rule.RuleTestUtil; 12 | import org.junit.FixMethodOrder; 13 | import org.junit.Test; 14 | import org.junit.runners.MethodSorters; 15 | import org.springframework.http.HttpStatus; 16 | 17 | import java.util.Arrays; 18 | 19 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 20 | public class WhiteListCheck { 21 | 22 | private RuleTestUtil ruleTestUtil = new RuleTestUtil(); 23 | private UserModel obj = new UserModel(); 24 | private ValidationData data = ruleTestUtil.getDefaultValidationData(); 25 | private BasicCheckRule checkType = BasicCheckRule.WhiteList; 26 | 27 | public WhiteListCheck() { 28 | this.data.setName("membership"); 29 | 30 | ValidationRule rule = data.getValidationRules().stream().filter(r -> r.getRuleName().equals(checkType.name())).findAny().get(); 31 | rule.setUse(true); 32 | rule.setStandardValue(Arrays.asList(new String[]{"GOLD", "SILVER", "BRONZE"})); 33 | } 34 | 35 | @Test 36 | public void test_fail_1() { 37 | obj.setMembership(Membership.BLACK); 38 | ruleTestUtil.checkRule(data, obj, checkType, obj.getMembership(), false); 39 | } 40 | 41 | @Test 42 | public void test_fail_2() { 43 | obj.setMembership(Membership.DORMANCY); 44 | ruleTestUtil.checkRule(data, obj, checkType, obj.getMembership(), false); 45 | } 46 | 47 | @Test 48 | public void test_success_1() { 49 | obj.setMembership(Membership.GOLD); 50 | ruleTestUtil.checkRule(data, obj, checkType, obj.getMembership(), true); 51 | } 52 | 53 | @Test 54 | public void test_success_2() { 55 | obj.setMembership(Membership.SILVER); 56 | ruleTestUtil.checkRule(data, obj, checkType, obj.getMembership(), true); 57 | } 58 | 59 | @Test 60 | public void test_success_3() { 61 | obj.setMembership(Membership.BRONZE); 62 | ruleTestUtil.checkRule(data, obj, checkType, obj.getMembership(), true); 63 | } 64 | 65 | @Test 66 | public void test_callback_change() { 67 | CheckPointHelper helper = new CheckPointHelper(); 68 | helper.replaceExceptionCallback(this.checkType, new WhiteListCallback()); 69 | 70 | obj.setMembership(Membership.BLACK); 71 | ruleTestUtil.checkRule(data, obj, checkType, obj.getMembership(), false, HttpStatus.NOT_ACCEPTABLE); 72 | } 73 | 74 | public static class WhiteListCallback implements ValidationInvalidCallback { 75 | @Override 76 | public void exception(ValidationData param, Object inputValue, Object standardValue) { 77 | throw new ValidationLibException(param.getName() + " order exception", HttpStatus.NOT_ACCEPTABLE); 78 | } 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/store/ValidationStore.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.store; 2 | 3 | import hsim.checkpoint.core.component.ComponentMap; 4 | import hsim.checkpoint.core.domain.ReqUrl; 5 | import hsim.checkpoint.core.domain.ValidationData; 6 | import hsim.checkpoint.core.repository.ValidationDataRepository; 7 | import hsim.checkpoint.exception.ValidationLibException; 8 | import hsim.checkpoint.type.ParamType; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.springframework.http.HttpStatus; 11 | 12 | import java.util.HashMap; 13 | import java.util.List; 14 | import java.util.Map; 15 | import java.util.stream.Collectors; 16 | 17 | /** 18 | * The type Validation store. 19 | */ 20 | @Slf4j 21 | public class ValidationStore { 22 | 23 | private List allList; 24 | private Map urlMap; 25 | private Map> validationDataRuleListMap; 26 | 27 | private ValidationDataRepository repository = ComponentMap.get(ValidationDataRepository.class); 28 | 29 | /** 30 | * Instantiates a new Validation store. 31 | */ 32 | public ValidationStore() { 33 | } 34 | 35 | private void instanceInit() { 36 | urlMap = new HashMap<>(); 37 | validationDataRuleListMap = new HashMap<>(); 38 | } 39 | 40 | private List getMatchedValidaitonRule(ParamType paramType, ReqUrl reqUrl) { 41 | return allList.stream().filter(d -> d.getParamType().equals(paramType) && d.equalUrl(reqUrl)).collect(Collectors.toList()); 42 | } 43 | 44 | private void validationDataInit() { 45 | 46 | allList = this.repository.findAll(false); 47 | 48 | allList.stream().forEach(data -> { 49 | ReqUrl url = new ReqUrl(data); 50 | if (url.isUrlMapping()) { 51 | urlMap.put(url.getUniqueKey(), url); 52 | } else { 53 | urlMap.put(data.getMethodKey(), url); 54 | } 55 | }); 56 | 57 | allList = allList.stream().filter(vd -> !vd.getValidationRules().isEmpty()).collect(Collectors.toList()); 58 | 59 | urlMap.entrySet().stream().forEach(entry -> { 60 | ReqUrl reqUrl = entry.getValue(); 61 | 62 | validationDataRuleListMap.put(ParamType.BODY.getUniqueKey(reqUrl), this.getMatchedValidaitonRule(ParamType.BODY, reqUrl)); 63 | validationDataRuleListMap.put(ParamType.QUERY_PARAM.getUniqueKey(reqUrl), this.getMatchedValidaitonRule(ParamType.QUERY_PARAM, reqUrl)); 64 | }); 65 | 66 | } 67 | 68 | /** 69 | * Refresh. 70 | */ 71 | public void refresh() { 72 | this.instanceInit(); 73 | this.validationDataInit(); 74 | } 75 | 76 | /** 77 | * Gets validation datas. 78 | * 79 | * @param paramType the param type 80 | * @param key the key 81 | * @return the validation datas 82 | */ 83 | public List getValidationDatas(ParamType paramType, String key) { 84 | if (this.urlMap == null || this.validationDataRuleListMap == null) { 85 | log.info("url map is empty :: " + key ); 86 | return null; 87 | } 88 | 89 | if (key == null || paramType == null) { 90 | throw new ValidationLibException("any parameter is null", HttpStatus.INTERNAL_SERVER_ERROR); 91 | } 92 | 93 | ReqUrl reqUrl = urlMap.get(key); 94 | if (reqUrl == null) { 95 | log.info("reqUrl is null :" + key); 96 | return null; 97 | } 98 | 99 | return validationDataRuleListMap.get(paramType.getUniqueKey(reqUrl.getUniqueKey())); 100 | } 101 | 102 | 103 | } 104 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/util/AnnotationScanner.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.util; 2 | 3 | import hsim.checkpoint.core.component.DetailParam; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.stereotype.Controller; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | import java.lang.annotation.Annotation; 9 | import java.lang.reflect.Method; 10 | import java.lang.reflect.Parameter; 11 | import java.util.ArrayList; 12 | import java.util.Arrays; 13 | import java.util.List; 14 | import java.util.stream.Collectors; 15 | 16 | /** 17 | * The type Annotation scanner. 18 | */ 19 | @Slf4j 20 | public class AnnotationScanner { 21 | 22 | private List controllers = null; 23 | 24 | private boolean isControllerClass(Class type) { 25 | return type.getAnnotation(RestController.class) != null || type.getAnnotation(Controller.class) != null; 26 | } 27 | 28 | private Class getController(Object bean) { 29 | 30 | if (this.isControllerClass(bean.getClass())) { 31 | return bean.getClass(); 32 | } else if (bean.getClass().getSuperclass() != null && !bean.getClass().getSuperclass().equals(Object.class) && this.isControllerClass(bean.getClass().getSuperclass())) { 33 | return bean.getClass().getSuperclass(); 34 | } 35 | 36 | return null; 37 | } 38 | 39 | /** 40 | * Init beans. 41 | * 42 | * @param beans the beans 43 | */ 44 | public void initBeans(Object[] beans) { 45 | this.controllers = Arrays.stream(beans).filter(bean -> this.getController(bean) != null).map(bean -> this.getController(bean)).collect(Collectors.toList()); 46 | } 47 | 48 | /** 49 | * Gets parameter from method with annotation. 50 | * 51 | * @param parentClass the parent class 52 | * @param method the method 53 | * @param annotationClass the annotation class 54 | * @return the parameter from method with annotation 55 | */ 56 | public List getParameterFromMethodWithAnnotation(Class parentClass, Method method, Class annotationClass) { 57 | List params = new ArrayList<>(); 58 | if (method.getParameterCount() < 1) { 59 | return params; 60 | } 61 | 62 | for (Parameter param : method.getParameters()) { 63 | 64 | Annotation[] annotations = param.getAnnotations(); 65 | 66 | for (Annotation annotation : annotations) { 67 | if (annotation.annotationType().equals(annotationClass)) { 68 | params.add(new DetailParam(param.getType(), method, parentClass)); 69 | break; 70 | } 71 | } 72 | } 73 | return params; 74 | } 75 | 76 | /** 77 | * Gets parameter from class with annotation. 78 | * 79 | * @param baseClass the base class 80 | * @param annotationClass the annotation class 81 | * @return the parameter from class with annotation 82 | */ 83 | public List getParameterFromClassWithAnnotation(Class baseClass, Class annotationClass) { 84 | List params = new ArrayList<>(); 85 | Arrays.stream(baseClass.getDeclaredMethods()).forEach(method -> params.addAll(this.getParameterFromMethodWithAnnotation(baseClass, method, annotationClass))); 86 | return params; 87 | } 88 | 89 | /** 90 | * Gets parameter with annotation. 91 | * 92 | * @param annotation the annotation 93 | * @return the parameter with annotation 94 | */ 95 | public List getParameterWithAnnotation(Class annotation) { 96 | List params = new ArrayList<>(); 97 | this.controllers.stream().forEach(cla -> params.addAll(this.getParameterFromClassWithAnnotation(cla, annotation))); 98 | return params; 99 | 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/interceptor/ValidationResolver.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.interceptor; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import hsim.checkpoint.config.ValidationConfig; 5 | import hsim.checkpoint.core.annotation.ValidationBody; 6 | import hsim.checkpoint.core.annotation.ValidationParam; 7 | import hsim.checkpoint.core.component.ComponentMap; 8 | import hsim.checkpoint.core.domain.BasicCheckInfo; 9 | import hsim.checkpoint.core.msg.MsgChecker; 10 | import hsim.checkpoint.core.msg.MsgSaver; 11 | import hsim.checkpoint.type.ParamType; 12 | import hsim.checkpoint.util.ParameterMapper; 13 | import hsim.checkpoint.util.ValidationObjUtil; 14 | import lombok.Getter; 15 | import lombok.extern.slf4j.Slf4j; 16 | import org.springframework.core.MethodParameter; 17 | import org.springframework.web.bind.support.WebDataBinderFactory; 18 | import org.springframework.web.context.request.NativeWebRequest; 19 | import org.springframework.web.method.support.HandlerMethodArgumentResolver; 20 | import org.springframework.web.method.support.ModelAndViewContainer; 21 | 22 | import javax.servlet.http.HttpServletRequest; 23 | import java.lang.reflect.ParameterizedType; 24 | import java.util.List; 25 | 26 | /** 27 | * The type Validation resolver. 28 | */ 29 | @Slf4j 30 | public class ValidationResolver implements HandlerMethodArgumentResolver { 31 | 32 | private MsgSaver msgSaver = ComponentMap.get(MsgSaver.class); 33 | private ObjectMapper objectMapper; 34 | 35 | @Getter 36 | private MsgChecker msgChecker = ComponentMap.get(MsgChecker.class); 37 | 38 | private ValidationConfig validationConfig = ComponentMap.get(ValidationConfig.class); 39 | 40 | /** 41 | * Instantiates a new Validation resolver. 42 | */ 43 | public ValidationResolver() { 44 | super(); 45 | this.objectMapper = ValidationObjUtil.getDefaultObjectMapper(); 46 | } 47 | 48 | /** 49 | * Replace object mapper. 50 | * 51 | * @param objectMapper the object mapper 52 | */ 53 | public void replaceObjectMapper(ObjectMapper objectMapper) { 54 | this.objectMapper = objectMapper; 55 | } 56 | 57 | @Override 58 | public boolean supportsParameter(MethodParameter parameter) { 59 | return parameter.getParameterAnnotation(ValidationBody.class) != null 60 | || parameter.getParameterAnnotation(ValidationParam.class) != null; 61 | } 62 | 63 | @Override 64 | public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, 65 | NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { 66 | 67 | Object reqBody = null; 68 | BasicCheckInfo basicCheckInfo = new BasicCheckInfo((HttpServletRequest) webRequest.getNativeRequest(), parameter, this.validationConfig.isBodyLogging()); 69 | 70 | this.msgSaver.urlCheckAndSave(basicCheckInfo, basicCheckInfo.getParamType(), basicCheckInfo.getReqUrl(), parameter.getParameterType()); 71 | 72 | if (basicCheckInfo.getParamType().equals(ParamType.BODY) && basicCheckInfo.isListBody()) { 73 | Class paramClass = ValidationObjUtil.getListInnerClassFromGenericType(parameter.getGenericParameterType()); 74 | return this.objectMapper.readValue(basicCheckInfo.getBody(), this.objectMapper.getTypeFactory().constructCollectionType(List.class, paramClass)); 75 | //TOO 76 | } else if (basicCheckInfo.getParamType().equals(ParamType.BODY)) { 77 | reqBody = this.objectMapper.readValue(basicCheckInfo.getBody(), parameter.getParameterType()); 78 | } else if (basicCheckInfo.getParamType().equals(ParamType.QUERY_PARAM)) { 79 | reqBody = ParameterMapper.requestParamaterToObject(basicCheckInfo.getReq(), parameter.getParameterType(), parameter.getParameterAnnotation(ValidationParam.class).charset()); 80 | } 81 | 82 | this.msgChecker.checkRequest(basicCheckInfo, reqBody); 83 | 84 | return reqBody; 85 | } 86 | } -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/helper/CheckPointHelper.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.helper; 2 | 3 | 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import hsim.checkpoint.config.ValidationConfig; 6 | import hsim.checkpoint.core.component.ComponentMap; 7 | import hsim.checkpoint.core.component.validationRule.callback.ValidationInvalidCallback; 8 | import hsim.checkpoint.core.component.validationRule.rule.AssistType; 9 | import hsim.checkpoint.core.component.validationRule.rule.ValidationRule; 10 | import hsim.checkpoint.core.component.validationRule.type.BaseValidationCheck; 11 | import hsim.checkpoint.core.component.validationRule.type.BasicCheckRule; 12 | import hsim.checkpoint.core.component.validationRule.type.StandardValueType; 13 | import hsim.checkpoint.core.msg.MsgChecker; 14 | import hsim.checkpoint.core.repository.ValidationDataRepository; 15 | import hsim.checkpoint.core.store.ValidationRuleStore; 16 | import hsim.checkpoint.core.store.ValidationStore; 17 | import hsim.checkpoint.interceptor.ValidationResolver; 18 | 19 | /** 20 | * The type Check point helper. 21 | */ 22 | public class CheckPointHelper { 23 | 24 | private ValidationResolver validationResolver = ComponentMap.get(ValidationResolver.class); 25 | private ValidationRuleStore validationRuleStore = ComponentMap.get(ValidationRuleStore.class); 26 | private ValidationDataRepository validationDataRepository = ComponentMap.get(ValidationDataRepository.class); 27 | private ValidationStore validationStore = ComponentMap.get(ValidationStore.class); 28 | private ValidationConfig validationConfig = ComponentMap.get(ValidationConfig.class); 29 | private MsgChecker msgChecker = ComponentMap.get(MsgChecker.class); 30 | 31 | /** 32 | * Replace the mapper to be used for message parsing. 33 | * 34 | * @param objectMapper jackson objectmapper 35 | * @return CheckPointHelper check point helper 36 | */ 37 | public CheckPointHelper replaceObjectMapper(ObjectMapper objectMapper) { 38 | this.validationResolver.replaceObjectMapper(objectMapper); 39 | return this; 40 | } 41 | 42 | /** 43 | * Replace the callback to be used basic exception. 44 | * 45 | * @param checkRule basic rule type ex,, BasicCheckRule.Mandatory 46 | * @param cb callback class with implement ValidationInvalidCallback 47 | * @return CheckPointHeler check point helper 48 | */ 49 | public CheckPointHelper replaceExceptionCallback(BasicCheckRule checkRule, ValidationInvalidCallback cb) { 50 | this.msgChecker.replaceCallback(checkRule, cb); 51 | return this; 52 | } 53 | 54 | /** 55 | * Add the fresh user rule 56 | * 57 | * @param ruleName use rule name - must uniqueue 58 | * @param standardValueType rule check standardvalue type 59 | * @param validationCheck rule check class with extends BaseValidationCheck and overide replace or check method and exception method 60 | * @param assistType input field type 61 | * @return CheckPointHelper check point helper 62 | */ 63 | public CheckPointHelper addValidationRule(String ruleName, StandardValueType standardValueType, BaseValidationCheck validationCheck, AssistType assistType) { 64 | ValidationRule rule = new ValidationRule(ruleName, standardValueType, validationCheck); 65 | if (assistType == null) { 66 | assistType = AssistType.all(); 67 | } 68 | rule.setAssistType(assistType); 69 | this.validationRuleStore.addRule(rule); 70 | return this; 71 | } 72 | 73 | /** 74 | * Flush check point helper. 75 | * 76 | * @return the check point helper 77 | */ 78 | public CheckPointHelper flush() { 79 | this.validationDataRepository.datasRuleSync(); 80 | this.validationDataRepository.flush(); 81 | this.validationStore.refresh(); 82 | return this; 83 | } 84 | 85 | /** 86 | * Gets config. 87 | * 88 | * @return the config 89 | */ 90 | public ValidationConfig getConfig() { 91 | return this.validationConfig; 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/util/excel/TypeCheckUtil.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.util.excel; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | 5 | import java.lang.reflect.Field; 6 | import java.lang.reflect.InvocationTargetException; 7 | import java.lang.reflect.Method; 8 | import java.util.Arrays; 9 | import java.util.List; 10 | import java.util.stream.Collectors; 11 | 12 | /** 13 | * The type Type check util. 14 | */ 15 | @Slf4j 16 | public class TypeCheckUtil { 17 | 18 | private static Class[] PRIMITIVE_CLASS_TYPE = { 19 | Double.class, Float.class, Long.class, Integer.class, Byte.class, String.class, Short.class, Character.class, List.class, 20 | }; 21 | 22 | private static Class[] NUMBER_CLASS_TYPE = { 23 | Double.class, Float.class, Long.class, Integer.class, Byte.class, Short.class, 24 | double.class, float.class, long.class, int.class, byte.class, short.class 25 | }; 26 | 27 | private static String[] BASIC_PACKAGE_PREFIX = {"java", "sun", "org"}; 28 | 29 | private static List> PRIMITIVE_CLASS_LIST = Arrays.stream(PRIMITIVE_CLASS_TYPE).collect(Collectors.toList()); 30 | 31 | private static List> NUMBER_CLASS_LIST = Arrays.stream(NUMBER_CLASS_TYPE).collect(Collectors.toList()); 32 | private static List BASIC_PACKAGE_PREFIX_LIST = Arrays.stream(BASIC_PACKAGE_PREFIX).collect(Collectors.toList()); 33 | 34 | /** 35 | * Is obj class boolean. 36 | * 37 | * @param field the field 38 | * @return the boolean 39 | */ 40 | public static boolean isObjClass(Field field) { 41 | return isObjClass(field.getType()); 42 | } 43 | 44 | /** 45 | * Is list class boolean. 46 | * 47 | * @param field the field 48 | * @return the boolean 49 | */ 50 | public static boolean isListClass(Field field) { 51 | return isListClass(field.getType()); 52 | } 53 | 54 | /** 55 | * Is number class boolean. 56 | * 57 | * @param field the field 58 | * @return the boolean 59 | */ 60 | public static boolean isNumberClass(Field field) { 61 | return isNumberClass(field.getType()); 62 | } 63 | 64 | /** 65 | * Is not scan class boolean. 66 | * 67 | * @param className the class name 68 | * @return the boolean 69 | */ 70 | public static boolean isNotScanClass(String className) { 71 | String block = BASIC_PACKAGE_PREFIX_LIST.stream().filter(prefix -> className.startsWith(prefix)).findAny().orElse(null); 72 | return block != null; 73 | } 74 | 75 | /** 76 | * Is obj class boolean. 77 | * 78 | * @param type the type 79 | * @return the boolean 80 | */ 81 | public static boolean isObjClass(Class type) { 82 | if (type.isPrimitive() || type.isEnum() || type.isArray()) { 83 | return false; 84 | } 85 | 86 | String block = BASIC_PACKAGE_PREFIX_LIST.stream().filter(prefix -> type.getName().startsWith(prefix)).findAny().orElse(null); 87 | if (block != null) { 88 | return false; 89 | } 90 | 91 | return !PRIMITIVE_CLASS_LIST.contains(type); 92 | } 93 | 94 | /** 95 | * Is list class boolean. 96 | * 97 | * @param type the type 98 | * @return the boolean 99 | */ 100 | public static boolean isListClass(Class type) { 101 | if (type.isPrimitive() || type.isEnum()) { 102 | return false; 103 | } 104 | return type.equals(List.class); 105 | } 106 | 107 | /** 108 | * Is number class boolean. 109 | * 110 | * @param type the type 111 | * @return the boolean 112 | */ 113 | public static boolean isNumberClass(Class type) { 114 | return NUMBER_CLASS_LIST.contains(type); 115 | } 116 | 117 | 118 | /** 119 | * Get default white list string [ ]. 120 | * 121 | * @param field the field 122 | * @return the string [ ] 123 | */ 124 | public static String[] getDefaultWhiteList(Field field) { 125 | Method values = null; 126 | 127 | if (!field.getType().isEnum()) { 128 | try { 129 | values = field.getType().getMethod("values"); 130 | } catch (NoSuchMethodException e) { 131 | log.info("field : " + field.getName() + " values method not found "); 132 | } 133 | 134 | try { 135 | Object[] objs = (Object[]) values.invoke(field.getType()); 136 | return (String[]) Arrays.stream(objs).map(obj -> String.valueOf(obj)).toArray(); 137 | } catch (IllegalAccessException | InvocationTargetException e) { 138 | log.info("values invoke error : " + e.getMessage()); 139 | } 140 | } 141 | return null; 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/store/ValidationRuleStore.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.store; 2 | 3 | import hsim.checkpoint.core.component.validationRule.check.*; 4 | import hsim.checkpoint.core.component.validationRule.replace.ReplaceBase64; 5 | import hsim.checkpoint.core.component.validationRule.replace.ReplaceDefaultValue; 6 | import hsim.checkpoint.core.component.validationRule.replace.ReplaceTrim; 7 | import hsim.checkpoint.core.component.validationRule.rule.AssistType; 8 | import hsim.checkpoint.core.component.validationRule.rule.ValidationRule; 9 | import hsim.checkpoint.core.component.validationRule.type.BaseValidationCheck; 10 | import hsim.checkpoint.core.component.validationRule.type.BasicCheckRule; 11 | import hsim.checkpoint.core.component.validationRule.type.StandardValueType; 12 | import hsim.checkpoint.exception.ValidationLibException; 13 | import lombok.Getter; 14 | import org.springframework.http.HttpStatus; 15 | 16 | import java.util.ArrayList; 17 | import java.util.HashMap; 18 | import java.util.List; 19 | import java.util.Map; 20 | 21 | /** 22 | * The type Validation rule store. 23 | */ 24 | public class ValidationRuleStore { 25 | 26 | @Getter 27 | private List rules; 28 | private Map checkHashMap; 29 | 30 | /** 31 | * Instantiates a new Validation rule store. 32 | */ 33 | public ValidationRuleStore() { 34 | super(); 35 | 36 | this.rules = new ArrayList<>(); 37 | this.checkHashMap = new HashMap<>(); 38 | 39 | this.addRule(new ValidationRule(BasicCheckRule.Mandatory, StandardValueType.NONE, new MandatoryCheck()).parentDependency().overlapBanRule(BasicCheckRule.DefaultValue).assistType(AssistType.all())); 40 | this.addRule(new ValidationRule(BasicCheckRule.BlackList, StandardValueType.LIST, new BlackListCheck()).overlapBanRule(BasicCheckRule.WhiteList).assistType(new AssistType().string().enumType())); 41 | this.addRule(new ValidationRule(BasicCheckRule.WhiteList, StandardValueType.LIST, new WhiteListCheck()).overlapBanRule(BasicCheckRule.BlackList).assistType(new AssistType().string().enumType())); 42 | 43 | this.addRule(new ValidationRule(BasicCheckRule.MinSize, StandardValueType.NUMBER, new MinSizeCheck()).assistType(new AssistType().string().list().number())); 44 | this.addRule(new ValidationRule(BasicCheckRule.MaxSize, StandardValueType.NUMBER, new MaxSizeCheck()).assistType(new AssistType().string().list().number())); 45 | 46 | this.addRule(new ValidationRule(BasicCheckRule.DefaultValue, StandardValueType.STRING, new ReplaceDefaultValue()).overlapBanRule(BasicCheckRule.Mandatory).assistType(new AssistType().number().string().enumType().nullable())); 47 | this.addRule(new ValidationRule(BasicCheckRule.Base64, StandardValueType.NONE, new ReplaceBase64()).assistType(new AssistType().string())); 48 | this.addRule(new ValidationRule(BasicCheckRule.Trim, StandardValueType.NONE, new ReplaceTrim()).assistType(new AssistType().string())); 49 | this.addRule(new ValidationRule(BasicCheckRule.Pattern, StandardValueType.STRING, new PatternCheck()).assistType(new AssistType().string())); 50 | } 51 | 52 | /** 53 | * Gets validation checker. 54 | * 55 | * @param rule the rule 56 | * @return the validation checker 57 | */ 58 | public BaseValidationCheck getValidationChecker(ValidationRule rule) { 59 | ValidationRule existRule = this.rules.stream().filter(r -> r.getRuleName().equals(rule.getRuleName())).findFirst().orElse(null); 60 | if (existRule == null) { 61 | throw new ValidationLibException("rulename : " + rule.getRuleName() + "checker is notfound ", HttpStatus.INTERNAL_SERVER_ERROR); 62 | } 63 | return existRule.getValidationCheck(); 64 | } 65 | 66 | /** 67 | * Add rule validation rule store. 68 | * 69 | * @param rules the rules 70 | * @return the validation rule store 71 | */ 72 | public ValidationRuleStore addRule(ValidationRule... rules) { 73 | for (ValidationRule rule : rules) { 74 | this.addRule(rule); 75 | } 76 | return this; 77 | } 78 | 79 | /** 80 | * Add rule validation rule store. 81 | * 82 | * @param rule the rule 83 | * @return the validation rule store 84 | */ 85 | public synchronized ValidationRuleStore addRule(ValidationRule rule) { 86 | rule.setOrderIdx(this.rules.size()); 87 | this.rules.add(rule); 88 | this.checkHashMap.put(rule.getRuleName(), rule.getValidationCheck()); 89 | return this; 90 | } 91 | 92 | /** 93 | * Gets checker. 94 | * 95 | * @param rule the rule 96 | * @return the checker 97 | */ 98 | public BaseValidationCheck getChecker(ValidationRule rule) { 99 | return this.checkHashMap.get(rule.getRuleName()); 100 | } 101 | 102 | 103 | } 104 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/msg/MsgChecker.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.msg; 2 | 3 | import hsim.checkpoint.core.component.ComponentMap; 4 | import hsim.checkpoint.core.component.validationRule.callback.ValidationInvalidCallback; 5 | import hsim.checkpoint.core.component.validationRule.rule.ValidationRule; 6 | import hsim.checkpoint.core.component.validationRule.type.BaseValidationCheck; 7 | import hsim.checkpoint.core.component.validationRule.type.BasicCheckRule; 8 | import hsim.checkpoint.core.domain.BasicCheckInfo; 9 | import hsim.checkpoint.core.domain.ValidationData; 10 | import hsim.checkpoint.core.store.ValidationRuleStore; 11 | import hsim.checkpoint.core.store.ValidationStore; 12 | import lombok.extern.slf4j.Slf4j; 13 | 14 | import java.util.HashMap; 15 | import java.util.List; 16 | import java.util.Map; 17 | 18 | /** 19 | * The type Msg checker. 20 | */ 21 | @Slf4j 22 | public class MsgChecker { 23 | 24 | private ValidationStore validationStore = ComponentMap.get(ValidationStore.class); 25 | private ValidationRuleStore validationRuleStore = ComponentMap.get(ValidationRuleStore.class); 26 | 27 | private Map callbackMap = new HashMap<>(); 28 | 29 | /** 30 | * Replace callback msg checker. 31 | * 32 | * @param type the type 33 | * @param cb the cb 34 | * @return the msg checker 35 | */ 36 | public MsgChecker replaceCallback(BasicCheckRule type, ValidationInvalidCallback cb) { 37 | this.callbackMap.put(type.name(), cb); 38 | return this; 39 | } 40 | 41 | 42 | private void callExcpetion(ValidationData param, ValidationRule rule, Object value, Object standardValue) { 43 | ValidationInvalidCallback cb = this.callbackMap.get(rule.getRuleName()); 44 | if (cb != null) { 45 | cb.exception(param, value, standardValue); 46 | } else { 47 | this.validationRuleStore.getValidationChecker(rule).exception(param, value, standardValue); 48 | } 49 | } 50 | 51 | /** 52 | * Check point. 53 | * 54 | * @param param the param 55 | * @param rule the rule 56 | * @param bodyObj the body obj 57 | * @param standardValue the standard value 58 | */ 59 | public void checkPoint(ValidationData param, ValidationRule rule, Object bodyObj, Object standardValue) { 60 | //check 61 | Object value = param.getValue(bodyObj); 62 | BaseValidationCheck checker = this.validationRuleStore.getValidationChecker(rule); 63 | if ((value != null && standardValue != null) || rule.getAssistType().isNullable()) { 64 | boolean valid = checker.check(value, standardValue); 65 | 66 | if (!valid) { 67 | this.callExcpetion(param, rule, value, standardValue); 68 | } 69 | 70 | } 71 | //replace value 72 | Object replaceValue = checker.replace(value, standardValue, param); 73 | if (replaceValue != null && replaceValue != value) { 74 | param.replaceValue(bodyObj, replaceValue); 75 | } 76 | } 77 | 78 | /** 79 | * Check point list child. 80 | * 81 | * @param param the param 82 | * @param rule the rule 83 | * @param bodyObj the body obj 84 | * @param standardValue the standard value 85 | */ 86 | public void checkPointListChild(ValidationData param, ValidationRule rule, Object bodyObj, Object standardValue) { 87 | ValidationData listParent = param.findListParent(); 88 | List list = (List) listParent.getValue(bodyObj); 89 | if (list == null || list.isEmpty()) { 90 | return; 91 | } 92 | 93 | list.stream().forEach(item -> { 94 | this.checkPoint(param, rule, item, standardValue); 95 | }); 96 | 97 | } 98 | 99 | /** 100 | * Check data inner rules. 101 | * 102 | * @param data the data 103 | * @param bodyObj the body obj 104 | */ 105 | public void checkDataInnerRules(ValidationData data, Object bodyObj) { 106 | data.getValidationRules().stream().filter(vr -> vr.isUse()).forEach(rule -> { 107 | if (data.isListChild()) { 108 | this.checkPointListChild(data, rule, bodyObj, rule.getStandardValue()); 109 | } else { 110 | this.checkPoint(data, rule, bodyObj, rule.getStandardValue()); 111 | } 112 | }); 113 | } 114 | 115 | /** 116 | * Check request. 117 | * 118 | * @param basicCheckInfo the basic check info 119 | * @param bodyObj the body obj 120 | */ 121 | public void checkRequest(BasicCheckInfo basicCheckInfo, Object bodyObj) { 122 | String key = basicCheckInfo.getUniqueKey(); 123 | 124 | List checkData = this.validationStore.getValidationDatas(basicCheckInfo.getParamType(), key); 125 | 126 | if (checkData == null || checkData.isEmpty()) { 127 | return; 128 | } 129 | checkData.stream().forEach(data -> { 130 | this.checkDataInnerRules(data, bodyObj); 131 | }); 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/setting/service/MsgExcelServiceImpl.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.setting.service; 2 | 3 | import hsim.checkpoint.core.component.ComponentMap; 4 | import hsim.checkpoint.core.component.validationRule.rule.ValidationRule; 5 | import hsim.checkpoint.core.component.validationRule.type.StandardValueType; 6 | import hsim.checkpoint.core.domain.ReqUrl; 7 | import hsim.checkpoint.core.domain.ValidationData; 8 | import hsim.checkpoint.core.repository.ValidationDataRepository; 9 | import hsim.checkpoint.type.ParamType; 10 | import hsim.checkpoint.util.excel.PoiWorkBook; 11 | import hsim.checkpoint.util.excel.PoiWorkSheet; 12 | import hsim.checkpoint.util.excel.TypeCheckUtil; 13 | import lombok.extern.slf4j.Slf4j; 14 | 15 | import java.util.Comparator; 16 | import java.util.List; 17 | 18 | /** 19 | * The type Msg excel service. 20 | */ 21 | @Slf4j 22 | public class MsgExcelServiceImpl implements MsgExcelService { 23 | 24 | private ValidationDataRepository validationDataRepository = ComponentMap.get(ValidationDataRepository.class); 25 | 26 | 27 | private int createTitleCell(PoiWorkSheet sheet, int maxDeepLevel) { 28 | sheet.createTitleCell("Name", 1); 29 | for (int i = 0; i < maxDeepLevel; i++) { 30 | sheet.createTitleCells("Child" + (i + 1)); 31 | } 32 | return maxDeepLevel + 1; 33 | } 34 | 35 | private void createNameValueCell(PoiWorkSheet sheet, ValidationData data, int nameCellCnt) { 36 | String[] names = new String[nameCellCnt]; 37 | for (int i = 0; i < names.length; i++) { 38 | names[i] = ""; 39 | } 40 | 41 | for (int i = 0; i < names.length; i++) { 42 | names[i] = i == data.getDeepLevel() ? data.getName() : i < data.getDeepLevel() ? "L" : ""; 43 | } 44 | 45 | sheet.createValueCells(names); 46 | } 47 | 48 | private Object getValidationStr(ValidationRule rule) { 49 | 50 | if (rule.getStandardValueType().equals(StandardValueType.NONE)) { 51 | return rule.isUse() ? "O" : "X"; 52 | } 53 | 54 | return rule.isUse() ? rule.getStandardValue() : ""; 55 | } 56 | 57 | private void createValidationDataRow(PoiWorkSheet sheet, ValidationData data, int nameCellCnt) { 58 | sheet.nextRow(); 59 | this.createNameValueCell(sheet, data, nameCellCnt); 60 | sheet.createValueCells(data.getType(), data.getTypeClass().getName()); 61 | 62 | data.getValidationRules().forEach(rule -> { 63 | sheet.createValueCells(this.getValidationStr(rule)); 64 | }); 65 | 66 | if (TypeCheckUtil.isObjClass(data.getTypeClass())) { 67 | List childs = this.validationDataRepository.findByParentId(data.getId()); 68 | for (ValidationData child : childs) { 69 | this.createValidationDataRow(sheet, child, nameCellCnt); 70 | } 71 | } 72 | } 73 | 74 | private boolean createParamSheet(PoiWorkSheet sheet, ParamType paramType, ReqUrl reqUrl) { 75 | List datas = this.validationDataRepository.findByParamTypeAndMethodAndUrl(paramType, reqUrl.getMethod(), reqUrl.getUrl()); 76 | if (datas.isEmpty()) { 77 | return false; 78 | } 79 | 80 | sheet.createTitleCells(1.5, paramType.getAnnotationName()); 81 | sheet.nextRow(); 82 | 83 | int maxDeppLevel = datas.stream().map(data -> data.getDeepLevel()).max(Comparator.comparing(Integer::valueOf)).get(); 84 | int nameCellCnt = this.createTitleCell(sheet, maxDeppLevel); 85 | sheet.createTitleCells(1.5, "Type", "TypeClass"); 86 | 87 | datas.get(0).getValidationRules().forEach(rule -> { 88 | sheet.createTitleCells(1.5, rule.getRuleName()); 89 | }); 90 | 91 | datas.stream().filter(d -> d.getDeepLevel() < 1).forEach(d -> this.createValidationDataRow(sheet, d, nameCellCnt)); 92 | sheet.nextRow(4); 93 | return true; 94 | } 95 | 96 | private void createReqUrlSheet(PoiWorkBook workBook, ReqUrl reqUrl) { 97 | PoiWorkSheet sheet = workBook.createSheet(reqUrl.getSheetName(workBook.getWorkBook().getNumberOfSheets())); 98 | 99 | sheet.nextRow(); 100 | sheet.createTitleCells(1.5, reqUrl.getMethod(), reqUrl.getUrl()); 101 | sheet.nextRow(2); 102 | 103 | for (ParamType paramType : ParamType.values()) { 104 | if (this.createParamSheet(sheet, paramType, reqUrl)) { 105 | sheet.nextRow(3); 106 | } 107 | } 108 | } 109 | 110 | 111 | @Override 112 | public PoiWorkBook getAllExcels() { 113 | PoiWorkBook workBook = new PoiWorkBook(); 114 | 115 | List reqUrls = this.validationDataRepository.findAllUrl(); 116 | for (ReqUrl reqUrl : reqUrls) { 117 | this.createReqUrlSheet(workBook, reqUrl); 118 | } 119 | return workBook; 120 | } 121 | 122 | @Override 123 | public PoiWorkBook getExcel(String method, String url) { 124 | PoiWorkBook workBook = new PoiWorkBook(); 125 | this.createReqUrlSheet(workBook, new ReqUrl(method, url)); 126 | return workBook; 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.github.ckpoint 7 | check-point 8 | 0.1.2 9 | jar 10 | 11 | CheckPoint 12 | Http request auto validation library for spring framework 13 | https://github.com/ckpoint/CheckPoint 14 | 15 | 16 | 17 | apache-2.0 18 | https://opensource.org/licenses/Apache-2.0 19 | repo 20 | 21 | 22 | 23 | 24 | https://github.com/ckpoint/CheckPoint 25 | scm:git:git@github.com:ckpoint/CheckPoint.git 26 | scm:git:git@github.com:ckpoint/CheckPoint.git 27 | 28 | 29 | 30 | 31 | ossrh 32 | https://oss.sonatype.org/content/repositories/snapshots 33 | 34 | 35 | ossrh 36 | ossrh 37 | https://oss.sonatype.org/service/local/staging/deploy/maven2 38 | default 39 | 40 | 41 | 42 | 43 | 44 | lhs1553@gmail.com 45 | HeeSeob Lim 46 | https://github.com/ckpoint 47 | ckpoint 48 | 49 | 50 | 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-starter-parent 55 | 1.5.10.RELEASE 56 | 57 | 58 | 59 | 60 | 1.8 61 | UTF-8 62 | UTF-8 63 | 1.8 64 | 65 | 66 | 67 | 68 | org.apache.maven.plugins 69 | maven-compiler-plugin 70 | 3.1 71 | 72 | ${java.version} 73 | ${java.version} 74 | UTF-8 75 | 76 | 77 | 78 | org.apache.maven.plugins 79 | maven-release-plugin 80 | 2.5 81 | 82 | true 83 | false 84 | release 85 | deploy 86 | 87 | 88 | 89 | org.sonatype.plugins 90 | nexus-staging-maven-plugin 91 | 1.6.3 92 | true 93 | 94 | ossrh 95 | https://oss.sonatype.org/ 96 | true 97 | 98 | 99 | 100 | maven-source-plugin 101 | 2.3 102 | 103 | 104 | attach-sources 105 | verify 106 | 107 | jar 108 | 109 | 110 | 111 | 112 | 113 | maven-javadoc-plugin 114 | 2.9.1 115 | 116 | 117 | attach-javadocs 118 | verify 119 | 120 | jar 121 | 122 | 123 | 124 | 125 | 126 | org.apache.maven.plugins 127 | maven-gpg-plugin 128 | 1.5 129 | 130 | 131 | sign-artifacts 132 | verify 133 | 134 | sign 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | org.springframework.boot 145 | spring-boot-starter-web 146 | 147 | 148 | 149 | org.projectlombok 150 | lombok 151 | true 152 | 153 | 154 | 155 | org.springframework.boot 156 | spring-boot-starter-test 157 | test 158 | 159 | 160 | 161 | org.apache.poi 162 | poi 163 | 3.17 164 | 165 | 166 | 167 | junit 168 | junit 169 | 4.12 170 | test 171 | 172 | 173 | 174 | 175 | 176 | 177 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/msg/MsgSaver.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.msg; 2 | 3 | import hsim.checkpoint.config.ValidationConfig; 4 | import hsim.checkpoint.core.annotation.ValidationBody; 5 | import hsim.checkpoint.core.annotation.ValidationParam; 6 | import hsim.checkpoint.core.component.ComponentMap; 7 | import hsim.checkpoint.core.component.DetailParam; 8 | import hsim.checkpoint.core.domain.BasicCheckInfo; 9 | import hsim.checkpoint.core.domain.ReqUrl; 10 | import hsim.checkpoint.core.domain.ValidationData; 11 | import hsim.checkpoint.core.repository.ValidationDataRepository; 12 | import hsim.checkpoint.core.store.ValidationStore; 13 | import hsim.checkpoint.type.ParamType; 14 | import hsim.checkpoint.util.AnnotationScanner; 15 | import hsim.checkpoint.util.excel.TypeCheckUtil; 16 | import lombok.extern.slf4j.Slf4j; 17 | 18 | import java.lang.reflect.Field; 19 | import java.util.Arrays; 20 | import java.util.List; 21 | 22 | /** 23 | * The type Msg saver. 24 | */ 25 | @Slf4j 26 | public class MsgSaver { 27 | 28 | private ValidationDataRepository validationDataRepository = ComponentMap.get(ValidationDataRepository.class); 29 | private ValidationStore validationStore = ComponentMap.get(ValidationStore.class); 30 | private ValidationConfig validationConfig = ComponentMap.get(ValidationConfig.class); 31 | private AnnotationScanner annotationScanner = ComponentMap.get(AnnotationScanner.class); 32 | 33 | /** 34 | * Instantiates a new Msg saver. 35 | */ 36 | public MsgSaver() { 37 | } 38 | 39 | 40 | /** 41 | * Annotation scan. 42 | * 43 | * @param maxDeepLeel the max deep leel 44 | */ 45 | public void annotationScan(final int maxDeepLeel) { 46 | 47 | Arrays.stream(ParamType.values()).forEach(paramType -> this.initDetailParams(paramType, maxDeepLeel)); 48 | 49 | this.validationDataRepository.flush(); 50 | this.validationStore.refresh(); 51 | log.info("[ANNOTATION_SCAN] Complete"); 52 | } 53 | 54 | private void initDetailParams(ParamType paramType, final int maxDeepLevel) { 55 | 56 | List params = this.annotationScanner.getParameterWithAnnotation(paramType.equals(ParamType.BODY) ? ValidationBody.class : ValidationParam.class); 57 | 58 | params.forEach(param -> { 59 | List urls = param.getReqUrls(); 60 | urls.forEach(url -> { 61 | this.saveParameter(param, paramType, url, null, param.getParameterType(), 0, maxDeepLevel); 62 | }); 63 | }); 64 | } 65 | 66 | /** 67 | * Url check and save. 68 | * 69 | * @param basicCheckInfo the basic check info 70 | * @param paramType the param type 71 | * @param reqUrl the req url 72 | * @param type the type 73 | */ 74 | public void urlCheckAndSave(BasicCheckInfo basicCheckInfo, ParamType paramType, ReqUrl reqUrl, Class type) { 75 | if (!this.validationConfig.isFreshUrlSave() || !basicCheckInfo.isUrlMapping()) { 76 | return; 77 | } 78 | 79 | List datas = this.validationDataRepository.findByParamTypeAndMethodAndUrl(paramType, reqUrl.getMethod(), reqUrl.getUrl()); 80 | if (datas.isEmpty()) { 81 | this.saveParameter(basicCheckInfo.getDetailParam(), paramType, reqUrl, null, type, 0, this.validationConfig.getMaxDeepLevel()); 82 | this.validationDataRepository.flush(); 83 | this.validationStore.refresh(); 84 | } 85 | } 86 | 87 | private ValidationData saveParam(DetailParam detailParam, ParamType paramType, ReqUrl reqUrl, ValidationData parent, Field field, int deepLevel) { 88 | ValidationData param = this.validationDataRepository.findByParamTypeAndMethodAndUrlAndNameAndParentId(paramType, reqUrl.getMethod(), reqUrl.getUrl(), field.getName(), parent == null ? null : parent.getId()); 89 | if (param == null) { 90 | param = new ValidationData(detailParam, paramType, reqUrl, parent, field, deepLevel); 91 | } else { 92 | param.updateKey(detailParam); 93 | } 94 | 95 | return this.validationDataRepository.save(param); 96 | } 97 | 98 | private void saveParameter(DetailParam detailParam, ParamType paramType, ReqUrl reqUrl, ValidationData parent, Class type, int deepLevel, final int maxDeepLevel) { 99 | 100 | if (type != null && type.getSuperclass() != null && !type.getSuperclass().equals(Object.class)) { 101 | this.saveParameter(detailParam, paramType, reqUrl, parent, type.getSuperclass(), deepLevel, maxDeepLevel); 102 | } 103 | 104 | if (deepLevel > maxDeepLevel) { 105 | log.debug(detailParam.getParameterType().getName() + "deep level " + deepLevel + " param : " + type.getName()); 106 | return; 107 | } 108 | 109 | for (Field field : type.getDeclaredFields()) { 110 | 111 | ValidationData param = this.saveParam(detailParam, paramType, reqUrl, parent, field, deepLevel); 112 | 113 | if (param.isObj()) { 114 | this.saveParameter(detailParam, paramType, reqUrl, param, param.getTypeClass(), deepLevel + 1, maxDeepLevel); 115 | } else if (param.isList() && !param.isListChild() && TypeCheckUtil.isObjClass(param.getInnerClass())) { 116 | this.saveParameter(detailParam, paramType, reqUrl, param, param.getInnerClass(), deepLevel + 1, maxDeepLevel); 117 | } 118 | } 119 | } 120 | 121 | 122 | } 123 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/core/component/validationRule/rule/ValidationRule.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.core.component.validationRule.rule; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import hsim.checkpoint.core.component.validationRule.type.BaseValidationCheck; 5 | import hsim.checkpoint.core.component.validationRule.type.BasicCheckRule; 6 | import hsim.checkpoint.core.component.validationRule.type.StandardValueType; 7 | import hsim.checkpoint.core.domain.ValidationData; 8 | import lombok.Getter; 9 | import lombok.NoArgsConstructor; 10 | import lombok.Setter; 11 | 12 | import java.util.List; 13 | import java.util.stream.Collectors; 14 | 15 | /** 16 | * The type Validation rule. 17 | */ 18 | @Getter 19 | @Setter 20 | @NoArgsConstructor 21 | public class ValidationRule { 22 | private int orderIdx; 23 | private String ruleName; 24 | private boolean use; 25 | private boolean parentDependency; 26 | private String overlapBanRuleName; 27 | private Object standardValue; 28 | private StandardValueType standardValueType; 29 | 30 | @JsonIgnore 31 | private BaseValidationCheck validationCheck; 32 | 33 | private AssistType assistType; 34 | 35 | /** 36 | * Instantiates a new Validation rule. 37 | * 38 | * @param rule the rule 39 | * @param standardValueType the standard value type 40 | * @param checker the checker 41 | */ 42 | public ValidationRule(BasicCheckRule rule, StandardValueType standardValueType, BaseValidationCheck checker) { 43 | this.ruleName = rule.name(); 44 | this.standardValueType = standardValueType; 45 | this.validationCheck = checker; 46 | } 47 | 48 | /** 49 | * Instantiates a new Validation rule. 50 | * 51 | * @param rName the r name 52 | * @param standardValueType the standard value type 53 | * @param checker the checker 54 | */ 55 | public ValidationRule(String rName, StandardValueType standardValueType, BaseValidationCheck checker) { 56 | this.ruleName = rName; 57 | this.standardValueType = standardValueType; 58 | this.validationCheck = checker; 59 | } 60 | 61 | /** 62 | * Update rule basic info. 63 | * 64 | * @param rule the rule 65 | */ 66 | public void updateRuleBasicInfo(ValidationRule rule) { 67 | this.orderIdx = rule.orderIdx; 68 | this.parentDependency = rule.parentDependency; 69 | this.standardValueType = rule.standardValueType; 70 | this.validationCheck = rule.validationCheck; 71 | this.overlapBanRuleName = rule.overlapBanRuleName; 72 | this.assistType = rule.assistType; 73 | } 74 | 75 | /** 76 | * Is use boolean. 77 | * 78 | * @return the boolean 79 | */ 80 | public boolean isUse() { 81 | if (!this.use) { 82 | return this.use; 83 | } 84 | 85 | return !(this.standardValueType != null && !this.standardValueType.equals(StandardValueType.NONE) && this.standardValue == null); 86 | } 87 | 88 | /** 89 | * Assist type validation rule. 90 | * 91 | * @param assistType1 the assist type 1 92 | * @return the validation rule 93 | */ 94 | public ValidationRule assistType(AssistType assistType1) { 95 | this.assistType = assistType1; 96 | return this; 97 | } 98 | 99 | /** 100 | * Overlap ban rule validation rule. 101 | * 102 | * @param rule the rule 103 | * @return the validation rule 104 | */ 105 | public ValidationRule overlapBanRule(BasicCheckRule rule) { 106 | this.overlapBanRuleName = rule.name(); 107 | return this; 108 | } 109 | 110 | /** 111 | * Overlap ban rule validation rule. 112 | * 113 | * @param ruleName the rule name 114 | * @return the validation rule 115 | */ 116 | public ValidationRule overlapBanRule(String ruleName) { 117 | this.overlapBanRuleName = ruleName; 118 | return this; 119 | } 120 | 121 | 122 | /** 123 | * Overlap ban rule validation rule. 124 | * 125 | * @param banRule the ban rule 126 | * @return the validation rule 127 | */ 128 | public ValidationRule overlapBanRule(ValidationRule banRule) { 129 | if (banRule != null) { 130 | this.overlapBanRuleName = banRule.getRuleName(); 131 | } 132 | return this; 133 | } 134 | 135 | /** 136 | * Parent dependency validation rule. 137 | * 138 | * @return the validation rule 139 | */ 140 | public ValidationRule parentDependency() { 141 | this.parentDependency = true; 142 | return this; 143 | } 144 | 145 | 146 | /** 147 | * Is used my rule boolean. 148 | * 149 | * @param item the item 150 | * @return the boolean 151 | */ 152 | public boolean isUsedMyRule(ValidationData item) { 153 | List usedRules = item.getValidationRules(); 154 | if (usedRules == null || usedRules.isEmpty()) { 155 | return false; 156 | } 157 | return usedRules.stream().filter(ur -> ur.getRuleName().equals(this.ruleName) && ur.isUse()).findAny().orElse(null) != null; 158 | } 159 | 160 | /** 161 | * Filter list. 162 | * 163 | * @param allList the all list 164 | * @return the list 165 | */ 166 | public List filter(List allList) { 167 | return allList.stream().filter(vd -> this.isUsedMyRule(vd)).collect(Collectors.toList()); 168 | } 169 | 170 | } 171 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/setting/session/ValidationSessionComponent.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.setting.session; 2 | 3 | import hsim.checkpoint.config.ValidationConfig; 4 | import hsim.checkpoint.core.component.ComponentMap; 5 | import hsim.checkpoint.exception.ValidationLibException; 6 | import org.springframework.http.HttpStatus; 7 | 8 | import javax.servlet.http.Cookie; 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | import java.util.Arrays; 12 | import java.util.HashMap; 13 | import java.util.Map; 14 | import java.util.Random; 15 | 16 | /** 17 | * The type Validation session idx. 18 | */ 19 | public class ValidationSessionComponent { 20 | 21 | private static final String SESSION_KEY_MAP = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 22 | private static final int SESSION_KEY_LENGTH = 50; 23 | private static final long VALID_SESSION_MSECOND = 1000 * 60 * 60 * 24; 24 | private ValidationConfig validationConfig = ComponentMap.get(ValidationConfig.class); 25 | private Map sessionMap = new HashMap<>(); 26 | 27 | private boolean validationSessionCheck(String token) { 28 | ValidationSessionInfo info = this.sessionMap.get(token); 29 | if (info == null) { 30 | return false; 31 | } 32 | 33 | long validationTime = info.getCreateDate().getTime() + VALID_SESSION_MSECOND; 34 | if (validationTime < System.currentTimeMillis()) { 35 | return false; 36 | } 37 | return true; 38 | } 39 | 40 | private boolean validaitonSessionCheckAndRemake(String token) { 41 | if (this.validationSessionCheck(token)) { 42 | this.sessionMap.remove(token); 43 | return true; 44 | } 45 | return false; 46 | } 47 | 48 | /** 49 | * Session check. 50 | * 51 | * @param req the req 52 | */ 53 | public void sessionCheck(HttpServletRequest req) { 54 | String authHeader = req.getHeader("Authorization"); 55 | if (authHeader != null && this.validationSessionCheck(authHeader)) { 56 | return; 57 | } 58 | 59 | if (req.getCookies() != null) { 60 | Cookie cookie = Arrays.stream(req.getCookies()).filter(ck -> ck.getName().equals("AuthToken")).findFirst().orElse(null); 61 | if (cookie != null && this.validationSessionCheck(cookie.getValue())) { 62 | return; 63 | } 64 | } 65 | 66 | if ( req.getParameter("token") != null){ 67 | String token = req.getParameter("token"); 68 | if(this.validationSessionCheck(token)){ 69 | return; 70 | } 71 | } 72 | 73 | throw new ValidationLibException("UnAuthorization", HttpStatus.UNAUTHORIZED); 74 | } 75 | 76 | /** 77 | * Check auth validation session info. 78 | * 79 | * @param info the info 80 | * @param req the req 81 | * @param res the res 82 | * @return the validation session info 83 | */ 84 | public ValidationSessionInfo checkAuth(ValidationLoginInfo info, HttpServletRequest req, HttpServletResponse res) { 85 | 86 | if (info.getToken() == null || info.getToken().isEmpty()) { 87 | throw new ValidationLibException("UnAuthorization", HttpStatus.UNAUTHORIZED); 88 | } 89 | if (this.validationConfig.getAuthToken() == null) { 90 | throw new ValidationLibException("Sever authkey is not helper ", HttpStatus.INTERNAL_SERVER_ERROR); 91 | } 92 | 93 | if (validaitonSessionCheckAndRemake(info.getToken())) { 94 | return this.createSession(req, res); 95 | } 96 | 97 | if (!this.validationConfig.getAuthToken().equals(info.getToken())) { 98 | throw new ValidationLibException("UnAuthorization", HttpStatus.UNAUTHORIZED); 99 | } 100 | req.getSession(); 101 | 102 | return this.createSession(req, res); 103 | } 104 | 105 | private String getSessionKey() { 106 | Random random = new Random(System.currentTimeMillis()); 107 | StringBuffer key = new StringBuffer(); 108 | for (int i = 0; i < SESSION_KEY_LENGTH; i++) { 109 | int idx = random.nextInt(SESSION_KEY_MAP.length()); 110 | key.append(SESSION_KEY_MAP.substring(idx, idx + 1)); 111 | } 112 | return key.toString(); 113 | } 114 | 115 | /** 116 | * Create session validation session info. 117 | * 118 | * @param req the req 119 | * @param res the res 120 | * @return the validation session info 121 | */ 122 | public ValidationSessionInfo createSession(HttpServletRequest req, HttpServletResponse res) { 123 | String key = this.getSessionKey(); 124 | ValidationSessionInfo sessionInfo = new ValidationSessionInfo(req, key); 125 | this.sessionMap.put(key, sessionInfo); 126 | res.addCookie(new Cookie("AuthToken", key)); 127 | return sessionInfo; 128 | } 129 | 130 | /** 131 | * Gets session. 132 | * 133 | * @param req the req 134 | * @return the session 135 | */ 136 | public Object getSession(HttpServletRequest req) { 137 | if (req.getCookies() == null) { 138 | return null; 139 | } 140 | 141 | Cookie cookie = Arrays.stream(req.getCookies()).filter(c -> c.getName().equalsIgnoreCase("ValidationSession")).findFirst().orElse(null); 142 | 143 | if (cookie == null) { 144 | return null; 145 | } 146 | return this.sessionMap.get(cookie.getValue()); 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/util/ValidationFileUtil.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.util; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import hsim.checkpoint.exception.ValidationLibException; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.springframework.http.HttpStatus; 7 | 8 | import javax.servlet.http.HttpServletResponse; 9 | import java.io.*; 10 | import java.net.URLEncoder; 11 | import java.nio.charset.Charset; 12 | import java.nio.file.Files; 13 | import java.nio.file.StandardOpenOption; 14 | 15 | /** 16 | * The type Validation file util. 17 | */ 18 | @Slf4j 19 | public class ValidationFileUtil { 20 | 21 | 22 | private static BufferedReader getBufferReader(final File file, final Charset charset) throws IOException { 23 | if (!file.exists() || file.isDirectory() || !file.canRead()) { 24 | throw new IOException("file status not normal : " + file.getName()); 25 | } 26 | return Files.newBufferedReader(file.toPath(), charset); 27 | } 28 | 29 | /** 30 | * Read file to string string. 31 | * 32 | * @param file the file 33 | * @param charset the charset 34 | * @return the string 35 | * @throws IOException the io exception 36 | */ 37 | public static String readFileToString(File file, final Charset charset) throws IOException { 38 | String line = null; 39 | BufferedReader reader = getBufferReader(file, charset); 40 | StringBuffer strBuffer = new StringBuffer(); 41 | 42 | while ((line = reader.readLine()) != null) { 43 | strBuffer.append(line); 44 | } 45 | return strBuffer.toString(); 46 | } 47 | 48 | 49 | private static OutputStream getOutputStream(final File file) throws IOException { 50 | if(!file.getParentFile().exists()) { 51 | Files.createDirectory(file.getParentFile().toPath()); 52 | } 53 | return Files.newOutputStream(file.toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE); 54 | } 55 | 56 | /** 57 | * Write string to file. 58 | * 59 | * @param file the file 60 | * @param content the content 61 | * @throws IOException the io exception 62 | */ 63 | public static void writeStringToFile(File file, String content) throws IOException { 64 | OutputStream outputStream = getOutputStream(file); 65 | outputStream.write(content.getBytes()); 66 | } 67 | 68 | /** 69 | * Gets encoding file name. 70 | * 71 | * @param fn the fn 72 | * @return the encoding file name 73 | */ 74 | public static String getEncodingFileName(String fn) { 75 | try { 76 | return URLEncoder.encode(fn, "UTF-8"); 77 | } catch (UnsupportedEncodingException e) { 78 | throw new ValidationLibException("unSupported fiel encoding : " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); 79 | } 80 | } 81 | 82 | /** 83 | * Init file send header. 84 | * 85 | * @param res the res 86 | * @param filename the filename 87 | * @param contentType the content type 88 | */ 89 | public static void initFileSendHeader(HttpServletResponse res, String filename, String contentType) { 90 | 91 | filename = getEncodingFileName(filename); 92 | if (contentType != null) { 93 | res.setContentType(contentType); 94 | } else { 95 | res.setContentType("applicaiton/download;charset=utf-8"); 96 | } 97 | res.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\";"); 98 | res.setHeader("Content-Transfer-Encoding", "binary"); 99 | res.setHeader("file-name", filename); 100 | 101 | } 102 | 103 | /** 104 | * Send file to http service response. 105 | * 106 | * @param file the file 107 | * @param res the res 108 | * @param contentType the content type 109 | */ 110 | public static void sendFileToHttpServiceResponse(File file, HttpServletResponse res, String contentType) { 111 | 112 | if (file == null || res == null) { 113 | return; 114 | } 115 | String filename = getEncodingFileName(file.getName()); 116 | initFileSendHeader(res, filename, contentType); 117 | 118 | res.setContentLength((int) file.length()); 119 | try { 120 | res.getOutputStream().write(Files.readAllBytes(file.toPath())); 121 | } catch (IOException e) { 122 | throw new ValidationLibException("file io error :" + e.getMessage()); 123 | } 124 | } 125 | 126 | /** 127 | * Send file to http service response. 128 | * 129 | * @param fileName the file name 130 | * @param bodyObj the body obj 131 | * @param res the res 132 | */ 133 | public static void sendFileToHttpServiceResponse(String fileName, Object bodyObj, HttpServletResponse res) { 134 | 135 | if (fileName == null || bodyObj == null) { 136 | return; 137 | } 138 | 139 | String body = null; 140 | try { 141 | body = ValidationObjUtil.getDefaultObjectMapper().writeValueAsString(bodyObj); 142 | } catch (JsonProcessingException e) { 143 | log.info(e.getMessage()); 144 | } 145 | 146 | String filename = getEncodingFileName(fileName); 147 | initFileSendHeader(res, filename, null); 148 | 149 | byte[] bytes = body.getBytes(); 150 | res.setContentLength(bytes.length); 151 | try { 152 | res.getOutputStream().write(bytes); 153 | } catch (IOException e) { 154 | throw new ValidationLibException("file io error :" + e.getMessage()); 155 | } 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/setting/service/MsgSettingServiceImpl.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.setting.service; 2 | 3 | 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import hsim.checkpoint.core.component.ComponentMap; 6 | import hsim.checkpoint.core.domain.ReqUrl; 7 | import hsim.checkpoint.core.domain.ValidationData; 8 | import hsim.checkpoint.core.repository.ValidationDataRepository; 9 | import hsim.checkpoint.core.store.ValidationStore; 10 | import hsim.checkpoint.type.ParamType; 11 | import hsim.checkpoint.util.ValidationObjUtil; 12 | import hsim.checkpoint.util.ValidationReqUrlUtil; 13 | import lombok.extern.slf4j.Slf4j; 14 | import org.springframework.web.multipart.MultipartFile; 15 | import org.springframework.web.multipart.MultipartHttpServletRequest; 16 | 17 | import java.io.IOException; 18 | import java.util.ArrayList; 19 | import java.util.HashMap; 20 | import java.util.List; 21 | import java.util.Map; 22 | import java.util.stream.Collectors; 23 | 24 | /** 25 | * The type Msg setting service. 26 | */ 27 | @Slf4j 28 | public class MsgSettingServiceImpl implements MsgSettingService { 29 | 30 | private ValidationDataRepository validationDataRepository = ComponentMap.get(ValidationDataRepository.class); 31 | private ValidationStore validationStore = ComponentMap.get(ValidationStore.class); 32 | 33 | public List getAllUrlList() { 34 | return this.validationDataRepository.findAllUrl(); 35 | } 36 | 37 | @Override 38 | public List getValidationData(String method, String url) { 39 | return this.validationDataRepository.findByMethodAndUrl(method, url); 40 | } 41 | 42 | @Override 43 | public List getAllValidationData() { 44 | return this.validationDataRepository.findAll(); 45 | } 46 | 47 | @Override 48 | public List getValidationData(ParamType paramType, String method, String url) { 49 | return this.validationDataRepository.findByParamTypeAndMethodAndUrl(paramType, method, url); 50 | } 51 | 52 | @Override 53 | public void updateValidationData(List models) { 54 | 55 | List origins = this.validationDataRepository.findByIds(models.stream().map(model -> model.getId()).collect(Collectors.toList())); 56 | 57 | this.validationDataRepository.saveAll( 58 | origins.stream().map(origin -> origin.updateUserData( 59 | models.stream().filter(model -> model.getId().equals(origin.getId())).findFirst().orElse(null)) 60 | ).collect(Collectors.toList())); 61 | 62 | this.validationDataRepository.saveAll(models.stream().filter(model -> model.getId() == null).collect(Collectors.toList())); 63 | 64 | this.validationDataRepository.flush(); 65 | this.validationStore.refresh(); 66 | } 67 | 68 | /** 69 | * Update from file. 70 | * 71 | * @param file the file 72 | */ 73 | public void updateFromFile(MultipartFile file) { 74 | ObjectMapper objectMapper = ValidationObjUtil.getDefaultObjectMapper(); 75 | 76 | try { 77 | String jsonStr = new String(file.getBytes(), "UTF-8"); 78 | List list = objectMapper.readValue(jsonStr, objectMapper.getTypeFactory().constructCollectionType(List.class, ValidationData.class)); 79 | List reqUrls = ValidationReqUrlUtil.getUrlListFromValidationDatas(list); 80 | reqUrls.forEach(reqUrl -> { 81 | this.deleteValidationData(reqUrl); 82 | }); 83 | Map idsMap = new HashMap<>(); 84 | List saveList = new ArrayList<>(); 85 | 86 | list.forEach(data -> { 87 | long oldId = data.getId(); 88 | data.setId(null); 89 | data = this.validationDataRepository.save(data); 90 | idsMap.put(oldId, data.getId()); 91 | saveList.add(data); 92 | }); 93 | 94 | saveList.forEach(data -> { 95 | if (data.getParentId() != null) { 96 | data.setParentId(idsMap.get(data.getParentId())); 97 | this.validationDataRepository.save(data); 98 | } 99 | }); 100 | 101 | } catch (IOException e) { 102 | log.info("file io exception : " + e.getMessage()); 103 | } 104 | } 105 | 106 | /** 107 | * Update from files. 108 | * 109 | * @param files the files 110 | */ 111 | public void updateFromFiles(List files) { 112 | for (MultipartFile file : files) { 113 | this.updateFromFile(file); 114 | } 115 | } 116 | 117 | @Override 118 | public void updateValidationData(MultipartHttpServletRequest req) { 119 | req.getMultiFileMap().entrySet().forEach(entry -> { 120 | List files = entry.getValue(); 121 | this.updateFromFiles(files); 122 | }); 123 | 124 | this.validationDataRepository.flush(); 125 | this.validationStore.refresh(); 126 | } 127 | 128 | @Override 129 | public void deleteValidationData(List models) { 130 | if (models == null || models.isEmpty()) { 131 | return; 132 | } 133 | 134 | this.validationDataRepository.deleteAll(models); 135 | this.validationDataRepository.flush(); 136 | this.validationStore.refresh(); 137 | } 138 | 139 | @Override 140 | public void deleteAll() { 141 | this.validationDataRepository.truncate(); 142 | this.validationDataRepository.flush(); 143 | this.validationStore.refresh(); 144 | } 145 | 146 | @Override 147 | public void deleteValidationData(ReqUrl url) { 148 | this.validationDataRepository.deleteAll(this.validationDataRepository.findByMethodAndUrl(url.getMethod(), url.getUrl())); 149 | 150 | this.validationDataRepository.flush(); 151 | this.validationStore.refresh(); 152 | 153 | } 154 | 155 | 156 | } 157 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/util/ParameterMapper.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.util; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.web.context.request.NativeWebRequest; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | import java.io.UnsupportedEncodingException; 8 | import java.lang.reflect.InvocationTargetException; 9 | import java.lang.reflect.Method; 10 | import java.lang.reflect.ParameterizedType; 11 | import java.net.URLDecoder; 12 | import java.util.ArrayList; 13 | import java.util.HashMap; 14 | import java.util.List; 15 | import java.util.Map; 16 | 17 | /** 18 | * The type Parameter mapper. 19 | */ 20 | @Slf4j 21 | public class ParameterMapper { 22 | 23 | private static final int QUERY_PARAM_SPLIT_SIZE = 2; 24 | 25 | private static String getSetMethodName(String name) { 26 | return "set" + name.substring(0, 1).toUpperCase() + name.substring(1); 27 | } 28 | 29 | /** 30 | * Request paramater to object t. 31 | * 32 | * @param the type parameter 33 | * @param req the req 34 | * @param c the c 35 | * @return the t 36 | */ 37 | public static T requestParamaterToObject(NativeWebRequest req, Class c) { 38 | return requestParamaterToObject((HttpServletRequest) req.getNativeRequest(), c, "UTF-8"); 39 | } 40 | 41 | /** 42 | * Request paramater to object t. 43 | * 44 | * @param the type parameter 45 | * @param request the request 46 | * @param c the c 47 | * @param charset the charset 48 | * @return the t 49 | */ 50 | public static T requestParamaterToObject(HttpServletRequest request, Class c, String charset) { 51 | 52 | Map map = new HashMap<>(); 53 | 54 | String query = request.getQueryString(); 55 | 56 | if (query != null) { 57 | String[] params = query.split("&"); 58 | 59 | for (String param : params) { 60 | if (param == null || param.indexOf('=') < 0) { 61 | continue; 62 | } 63 | String pv[] = param.split("="); 64 | if (pv.length != QUERY_PARAM_SPLIT_SIZE) { 65 | continue; 66 | } 67 | 68 | String value = pv[1]; 69 | 70 | try { 71 | value = URLDecoder.decode(pv[1], charset); 72 | } catch (UnsupportedEncodingException e) { 73 | log.info("unsupport encoding : " + pv[1]); 74 | value = pv[1]; 75 | } 76 | 77 | map.put(pv[0], value); 78 | } 79 | } 80 | 81 | return c.cast(mapToObject(map, c)); 82 | 83 | } 84 | 85 | /** 86 | * Find method method. 87 | * 88 | * @param c the c 89 | * @param methodName the method name 90 | * @return the method 91 | */ 92 | public static Method findMethod(Class c, String methodName) { 93 | for (Method m : c.getMethods()) { 94 | if (!m.getName().equalsIgnoreCase(methodName)) { 95 | continue; 96 | } 97 | if (m.getParameterCount() != 1) { 98 | continue; 99 | } 100 | return m; 101 | } 102 | 103 | return null; 104 | } 105 | 106 | /** 107 | * Cast value object. 108 | * 109 | * @param m the m 110 | * @param castType the cast type 111 | * @param value the value 112 | * @return the object 113 | */ 114 | @SuppressWarnings("PMD.LooseCoupling") 115 | public static Object castValue(Method m, Class castType, String value) { 116 | 117 | try { 118 | if (castType.isEnum()) { 119 | Method valueOf; 120 | try { 121 | valueOf = castType.getMethod("valueOf", String.class); 122 | return valueOf.invoke(null, value); 123 | } catch (Exception e) { 124 | log.info("enum value of excute error : (" + castType.getName() + ") | " + value); 125 | return null; 126 | } 127 | } else if (castType == Integer.class || castType == int.class) { 128 | return Integer.parseInt(value); 129 | } else if (castType == Long.class || castType == long.class) { 130 | return Long.parseLong(value); 131 | } else if (castType == Double.class || castType == double.class) { 132 | return Double.parseDouble(value); 133 | } else if (castType == Boolean.class || castType == boolean.class) { 134 | return Boolean.parseBoolean(value); 135 | } else if (castType == Float.class || castType == float.class) { 136 | return Float.parseFloat(value); 137 | } else if (castType == String.class) { 138 | return value; 139 | } else if (castType == ArrayList.class || castType == List.class) { 140 | ParameterizedType paramType = (ParameterizedType) m.getGenericParameterTypes()[0]; 141 | Class paramClass = (Class) paramType.getActualTypeArguments()[0]; 142 | List castList = new ArrayList<>(); 143 | String[] values = value.split(","); 144 | for (String v : values) { 145 | castList.add(castValue(m, paramClass, v)); 146 | } 147 | 148 | return castList; 149 | } else { 150 | log.info("invalid castType : " + castType); 151 | return null; 152 | } 153 | } catch (NumberFormatException e) { 154 | log.info("value : " + value + " is invalid value, setter parameter type is : " + castType); 155 | return null; 156 | } 157 | } 158 | 159 | 160 | /** 161 | * Map to object object. 162 | * 163 | * @param map the map 164 | * @param c the c 165 | * @return the object 166 | */ 167 | public static Object mapToObject(Map map, Class c) { 168 | 169 | Method m = null; 170 | Object obj = null; 171 | 172 | try { 173 | obj = c.newInstance(); 174 | } catch (InstantiationException | IllegalAccessException e) { 175 | log.info("instance create fail : " + c.getName()); 176 | return null; 177 | } 178 | 179 | for (Map.Entry entry : map.entrySet()) { 180 | 181 | if (entry.getValue() == null || entry.getValue().trim().isEmpty()) { 182 | continue; 183 | } 184 | 185 | if (entry.getValue().equalsIgnoreCase("undefined")) { 186 | continue; 187 | } 188 | 189 | try { 190 | m = findMethod(c, getSetMethodName(entry.getKey())); 191 | if (m == null) { 192 | log.info("not found mapping method : " + entry.getKey()); 193 | continue; 194 | } 195 | try { 196 | m.invoke(obj, castValue(m, m.getParameterTypes()[0], entry.getValue())); 197 | } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { 198 | log.info("method invoke error : " + m.getName()); 199 | } 200 | } catch (SecurityException e) { 201 | log.info("security exception : " + e.getMessage()); 202 | } 203 | } 204 | 205 | return obj; 206 | } 207 | } 208 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Check-Point 3 | Http request auto validation library for spring framework 4 | 5 | Check-Point depends on [Jackson Json Processor](https://github.com/FasterXML/jackson), [Project Lombok](http://projectlombok.org/), 6 | [Apache POI](https://github.com/apache/poi) 7 | 8 | #### Check-Point is a library that automatically checks the integrity of request messages that developers are most likely to miss during the spring project development. 9 | Null check, minimum, maximum value of message.. You do not need to code anymore, just only need to click the checkbox on the setting page. 10 | 11 | ##### I realized that I was born into a person who can not fully handle message exceptions and developed this library. 12 | 13 | #### Are you a diligent person who can handle exceptions for every message? 14 | 15 | 16 | # Installation 17 | 18 | #### 1. MAVEN 19 | ```xml 20 | 21 | com.github.ckpoint 22 | check-point 23 | 0.1.2 24 | 25 | 26 | ``` 27 | #### 2. GRADLE 28 | ```gradle 29 | compile group: 'com.github.ckpoint', name: 'check-point', version: '0.1.2' 30 | ``` 31 | # Check-Point Setting Guide 32 | https://youtu.be/I1aEIztXlhE 33 | 34 | # Usage 35 | 36 | ## Table of Contents 37 | - [ 1. Add Properties ](#add-properteis) 38 | - [ 2. Setting Api Controller Add ](#add-setting-controller) 39 | - [ 3. Add Annotation ](#add-annotation) 40 | - [ 4. Add Custom Validation Rule](#add-custom-validation-rule) 41 | - [ 5. Replace Validation Exception](#replace-validation-exception) 42 | - [ 6. Replace Object Mapper](#replace-object-mapper) 43 | - [ 7. Client and Validation Setting](#client-and-validation-setting) 44 | 45 | 46 | 47 | ## Add Properties 48 | 49 | - {ckpoint.save.url:true} : for controller with UrlMapping annotation, save when new url recived. 50 | - {ckpoint.max.deeplevel:5} : scan object default deep level 51 | - {ckpoint.body.logging:true} : Whether the body of the request message is logged 52 | - {ckpoint.password:taeon} : When connecting from the setting client, the authentication key value 53 | - {ckpoint.path.repository:/checkpoint/validation.json} : The location of the json file where validation information will be stored 54 | 55 | ## Add Setting Controller 56 | Add the controller to the project as shown below. 57 | 58 | - The controller to be added must extends the MsgSettingController. 59 | - You can also use RequestMapping annotation to set a unique address value to receive the configuration api. 60 | 61 | ```java 62 | 63 | @RestController 64 | @RequestMapping("/uniquepath") 65 | public class CheckPointController extends MsgSettingController { } 66 | 67 | ``` 68 | 69 | ## Add Annotation 70 | 71 | #### @ValidationParam 72 | - You can use the ValidationParam annotation to map a Request Parameter to Object. 73 | 74 | ```java 75 | @GetMapping("/find") 76 | public UserModel findUser(@ValidationParam BaseModel findModel) { 77 | UserModel userModel = new UserModel(); 78 | userModel.setId(findModel.getId()); 79 | ... 80 | return userModel; 81 | } 82 | ``` 83 | #### @ValidationBody 84 | - You can use the ValidationBody annotation to map a json body to Object. 85 | 86 | ```java 87 | @PutMapping("/create") 88 | public OrderModel createOrder(@ValidationBody OrderModel orderModel) { 89 | ... 90 | return orderModel; 91 | } 92 | ``` 93 | #### @ValidationUrlMapping 94 | - If the url and method can not be mapped to 1: 1, you can add an UrlMapping annotation. 95 | - If the {{ckpoint.save.url}} property is true, it generates configuration data that maps to the request when a new url request is received. 96 | - Setting the {{ckpoint.max.deeplevel}} property allows you to specify the depth of the object to be scanned at save time, and default value is 5 97 | ```java 98 | 99 | @RequestMapping("/proxy/**") 100 | @ValidationUrlMapping 101 | public void proxy(@ValidationParam ProxyModel proxymodel) { 102 | ... 103 | } 104 | ``` 105 | 106 | ## Add Custom Validation Rule 107 | - In addition to the basic rules, you can easily add a rule that does what you want. 108 | - Define a class that implements BaseValidaitonCheck as shown below. 109 | ```java 110 | 111 | import hsim.checkpoint.core.component.validationRule.type.BaseValidationCheck; 112 | import hsim.checkpoint.core.domain.ValidationData; 113 | import hsim.checkpoint.exception.ValidationLibException; 114 | import lombok.extern.slf4j.Slf4j; 115 | import org.springframework.http.HttpStatus; 116 | 117 | @Slf4j 118 | public class EmptyValueCheck implements BaseValidationCheck { 119 | 120 | @Override 121 | public boolean check(Object receiveValue, Object standardValue) { 122 | 123 | if (receiveValue instanceof String) { 124 | return !((String) receiveValue).isEmpty(); 125 | } 126 | return false; 127 | } 128 | 129 | @Override 130 | public Object replace(Object receiveValue, Object standardValue, ValidationData param) { 131 | 132 | if (receiveValue instanceof String && ((String) receiveValue).isEmpty()) { 133 | return standardValue; 134 | } 135 | return receiveValue; 136 | } 137 | 138 | @Override 139 | public void exception(ValidationData param, Object inputValue, Object standardValue) { 140 | throw new ValidationLibException("custom rule check error", HttpStatus.BAD_REQUEST); 141 | } 142 | 143 | } 144 | ``` 145 | 146 | - Then add the rule using CheckPointHelper as below and call flush at the end. 147 | 148 | ```java 149 | CheckPointHelper checkPointHelper = new CheckPointHelper(); 150 | checkPointHelper.addValidationRule("emptyValueCheck", StandardValueType.STRING, new EmptyValueCheck(), new AssistType().string()); 151 | checkPointHelper.flush(); 152 | ``` 153 | 154 | ## Replace Validation Exception 155 | 156 | - Define a class that implements ValidationInvalidCallback as shown below. 157 | ```java 158 | import hsim.checkpoint.core.component.validationRule.callback.ValidationInvalidCallback; 159 | import hsim.checkpoint.core.domain.ValidationData; 160 | import hsim.checkpoint.exception.ValidationLibException; 161 | import org.springframework.http.HttpStatus; 162 | 163 | public class MinSizeCallback implements ValidationInvalidCallback { 164 | @Override 165 | public void exception(ValidationData param, Object inputValue, Object standardValue) { 166 | throw new ValidationLibException(param.getName() + " value minimum is " + standardValue + " but, input " + inputValue, HttpStatus.NOT_ACCEPTABLE); 167 | } 168 | } 169 | ``` 170 | - Then replace the callback using CheckPointHelper as below. 171 | 172 | ```java 173 | public void replaceMinSizeCallback(){ 174 | CheckPointHelper checkPointHelper = new CheckPointHelper(); 175 | checkPointHelper.replaceExceptionCallback(BasicCheckRule.MinSize, new MinSizeCallback()); 176 | } 177 | ``` 178 | 179 | ## Replace Object Mapper 180 | 181 | - You can replace ObjectMapper, which is used for message parsing. 182 | ```java 183 | public void replaceObjectMapper(){ 184 | CheckPointHelper helper = new CheckPointHelper(); 185 | ObjectMapper mapper = new ObjectMapper(); 186 | mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 187 | mapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true); 188 | mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); 189 | mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); 190 | helper.replaceObjectMapper(mapper); 191 | } 192 | ``` 193 | 194 | ## Client and Validation Setting 195 | 196 | https://github.com/ckpoint/CheckPointClient 197 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/util/excel/PoiWorkSheet.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.util.excel; 2 | 3 | import hsim.checkpoint.util.ValidationObjUtil; 4 | import lombok.Getter; 5 | import org.apache.poi.hssf.usermodel.HSSFSheet; 6 | import org.apache.poi.ss.usermodel.Cell; 7 | import org.apache.poi.ss.usermodel.CellType; 8 | import org.apache.poi.ss.usermodel.Row; 9 | 10 | import java.util.ArrayList; 11 | import java.util.Date; 12 | import java.util.List; 13 | 14 | /** 15 | * The type Poi work sheet. 16 | */ 17 | @Getter 18 | public class PoiWorkSheet { 19 | 20 | private static final double DEFAULT_WIDTH = 1; 21 | 22 | private HSSFSheet sheet; 23 | private PoiCellStyle style; 24 | 25 | /** 26 | * Instantiates a new Poi work sheet. 27 | * 28 | * @param workBook the work book 29 | */ 30 | public PoiWorkSheet(PoiWorkBook workBook) { 31 | this.init(workBook, null); 32 | } 33 | 34 | /** 35 | * Instantiates a new Poi work sheet. 36 | * 37 | * @param workBook the work book 38 | * @param sheetName the sheet name 39 | */ 40 | public PoiWorkSheet(PoiWorkBook workBook, String sheetName) { 41 | this.init(workBook, sheetName); 42 | } 43 | 44 | /** 45 | * Next row row. 46 | * 47 | * @param cnt the cnt 48 | * @return the row 49 | */ 50 | public Row nextRow(int cnt) { 51 | Row lastrow = null; 52 | for (int i = 0; i < cnt; i++) { 53 | lastrow = this.nextRow(); 54 | } 55 | return lastrow; 56 | } 57 | 58 | /** 59 | * Next row row. 60 | * 61 | * @return the row 62 | */ 63 | public Row nextRow() { 64 | return this.sheet.createRow(this.sheet.getLastRowNum() + 1); 65 | } 66 | 67 | /** 68 | * Gets last row. 69 | * 70 | * @return the last row 71 | */ 72 | public Row getLastRow() { 73 | return this.sheet.getRow(this.sheet.getLastRowNum()); 74 | } 75 | 76 | private String checkSheetName(String sheetName){ 77 | return sheetName.replaceAll("\\*", ""); 78 | } 79 | 80 | private void init(PoiWorkBook workBook, String sheetName) { 81 | 82 | this.style = new PoiCellStyle(workBook); 83 | 84 | if (sheetName != null) { 85 | this.sheet = workBook.getWorkBook().createSheet(this.checkSheetName(sheetName)); 86 | } else { 87 | this.sheet = workBook.getWorkBook().createSheet(); 88 | } 89 | 90 | this.sheet.createRow(0); 91 | 92 | } 93 | 94 | private int getCellCnt() { 95 | int cellCnt = this.getLastRow().getLastCellNum(); 96 | return cellCnt < 0 ? 0 : cellCnt; 97 | } 98 | 99 | /** 100 | * Create title cells list. 101 | * 102 | * @param strs the strs 103 | * @return the list 104 | */ 105 | public List createTitleCells(String... strs) { 106 | List cells = new ArrayList<>(); 107 | 108 | for (String s : strs) { 109 | Cell cell = this.createTitleCell(s, DEFAULT_WIDTH); 110 | cells.add(cell); 111 | } 112 | return cells; 113 | } 114 | 115 | /** 116 | * Create title cells. 117 | * 118 | * @param width the width 119 | * @param strs the strs 120 | */ 121 | public void createTitleCells(double width, String... strs) { 122 | for (String s : strs) { 123 | this.createTitleCell(s, width); 124 | } 125 | } 126 | 127 | /** 128 | * Create title cell cell. 129 | * 130 | * @param str the str 131 | * @param width the width 132 | * @return the cell 133 | */ 134 | public Cell createTitleCell(String str, double width) { 135 | 136 | int cellCnt = this.getCellCnt(); 137 | 138 | Cell cell = this.getLastRow().createCell(cellCnt); 139 | cell.setCellValue(str); 140 | cell.setCellType(CellType.STRING); 141 | cell.setCellStyle(this.style.getStringCs()); 142 | 143 | sheet.setColumnWidth(cellCnt, (int) (sheet.getColumnWidth(cellCnt) * width)); 144 | 145 | return cell; 146 | } 147 | 148 | 149 | /** 150 | * Create value cells. 151 | * 152 | * @param values the values 153 | */ 154 | public void createValueCells(Object... values) { 155 | for (Object value : values) { 156 | if (value == null) { 157 | this.createCell(""); 158 | continue; 159 | } 160 | 161 | if (value instanceof String) { 162 | this.createCell((String) value); 163 | } else if (value instanceof Date) { 164 | this.createCell((Date) value); 165 | } else if (ValidationObjUtil.isIntType(value.getClass())) { 166 | long longValue = Long.valueOf(value + ""); 167 | this.createCell(longValue); 168 | } else if (ValidationObjUtil.isDoubleType(value.getClass())) { 169 | double doubleValue = Double.valueOf(value + ""); 170 | this.createCell(doubleValue); 171 | } else { 172 | this.createCell(value); 173 | } 174 | } 175 | } 176 | 177 | private Cell getNextCell(CellType cellType) { 178 | int cellCnt = this.getCellCnt(); 179 | Cell cell = this.getLastRow().createCell(cellCnt); 180 | cell.setCellType(cellType); 181 | cell.setCellStyle(this.style.getNumberCs()); 182 | return cell; 183 | } 184 | 185 | /** 186 | * Create cell cell. 187 | * 188 | * @param value the value 189 | * @return the cell 190 | */ 191 | public Cell createCell(double value) { 192 | 193 | Cell cell = this.getNextCell(CellType.NUMERIC); 194 | cell.setCellValue(value); 195 | cell.setCellStyle(this.style.getNumberCs()); 196 | return cell; 197 | } 198 | 199 | /** 200 | * Create cell cell. 201 | * 202 | * @param value the value 203 | * @return the cell 204 | */ 205 | public Cell createCell(Long value) { 206 | Cell cell = this.getNextCell(CellType.NUMERIC); 207 | cell.setCellValue(value); 208 | cell.setCellStyle(this.style.getNumberCs()); 209 | return cell; 210 | } 211 | 212 | /** 213 | * Create cell cell. 214 | * 215 | * @param value the value 216 | * @return the cell 217 | */ 218 | public Cell createCell(long value) { 219 | Cell cell = this.getNextCell(CellType.NUMERIC); 220 | cell.setCellValue(value); 221 | cell.setCellStyle(this.style.getNumberCs()); 222 | return cell; 223 | } 224 | 225 | 226 | /** 227 | * Create cell cell. 228 | * 229 | * @param obj the obj 230 | * @return the cell 231 | */ 232 | public Cell createCell(Object obj) { 233 | 234 | Cell cell = this.getNextCell(CellType.STRING); 235 | cell.setCellValue(String.valueOf(obj)); 236 | cell.setCellStyle(this.style.getStringCs()); 237 | return cell; 238 | } 239 | 240 | /** 241 | * Create cell cell. 242 | * 243 | * @param str the str 244 | * @return the cell 245 | */ 246 | public Cell createCell(String str) { 247 | 248 | Cell cell = this.getNextCell(CellType.STRING); 249 | cell.setCellValue(str); 250 | cell.setCellStyle(this.style.getStringCs()); 251 | return cell; 252 | } 253 | 254 | /** 255 | * Create cell cell. 256 | * 257 | * @param date the date 258 | * @return the cell 259 | */ 260 | public Cell createCell(Date date) { 261 | 262 | Cell cell = this.getNextCell(CellType.STRING); 263 | if (date != null) { 264 | cell.setCellValue(date); 265 | } 266 | cell.setCellStyle(this.style.getDateCs()); 267 | return cell; 268 | } 269 | 270 | 271 | } 272 | -------------------------------------------------------------------------------- /src/main/java/hsim/checkpoint/setting/controller/MsgSettingController.java: -------------------------------------------------------------------------------- 1 | package hsim.checkpoint.setting.controller; 2 | 3 | import hsim.checkpoint.config.ValidationConfig; 4 | import hsim.checkpoint.config.ValidationIntercepterConfig; 5 | import hsim.checkpoint.core.component.ComponentMap; 6 | import hsim.checkpoint.core.domain.ReqUrl; 7 | import hsim.checkpoint.core.domain.ValidationData; 8 | import hsim.checkpoint.core.msg.MsgSaver; 9 | import hsim.checkpoint.exception.resolver.ValidationExceptionResolver; 10 | import hsim.checkpoint.init.InitCheckPoint; 11 | import hsim.checkpoint.setting.service.MsgExcelService; 12 | import hsim.checkpoint.setting.service.MsgExcelServiceImpl; 13 | import hsim.checkpoint.setting.service.MsgSettingService; 14 | import hsim.checkpoint.setting.service.MsgSettingServiceImpl; 15 | import hsim.checkpoint.setting.session.ValidationLoginInfo; 16 | import hsim.checkpoint.setting.session.ValidationSessionComponent; 17 | import hsim.checkpoint.setting.session.ValidationSessionInfo; 18 | import hsim.checkpoint.util.ParameterMapper; 19 | import hsim.checkpoint.util.ValidationFileUtil; 20 | import hsim.checkpoint.util.excel.PoiWorkBook; 21 | import org.springframework.context.annotation.Bean; 22 | import org.springframework.web.bind.annotation.*; 23 | import org.springframework.web.multipart.MultipartHttpServletRequest; 24 | 25 | import javax.servlet.http.HttpServletRequest; 26 | import javax.servlet.http.HttpServletResponse; 27 | import java.util.Base64; 28 | import java.util.List; 29 | 30 | /** 31 | * The type Msg setting controller. 32 | */ 33 | @CrossOrigin(origins = "*") 34 | public class MsgSettingController { 35 | 36 | private MsgSettingService msgSettingService = ComponentMap.get(MsgSettingServiceImpl.class); 37 | private MsgExcelService msgExcelService = ComponentMap.get(MsgExcelServiceImpl.class); 38 | private ValidationSessionComponent validationSessionComponent = ComponentMap.get(ValidationSessionComponent.class); 39 | private MsgSaver msgSaver = ComponentMap.get(MsgSaver.class); 40 | 41 | 42 | /** 43 | * Login validation session info. 44 | * 45 | * @param info the info 46 | * @param req the req 47 | * @param res the res 48 | * @return the validation session info 49 | */ 50 | @PostMapping("/setting/auth") 51 | public ValidationSessionInfo login(@RequestBody ValidationLoginInfo info, HttpServletRequest req, HttpServletResponse res) { 52 | return this.validationSessionComponent.checkAuth(info, req, res); 53 | } 54 | 55 | /** 56 | * Annotation scan. 57 | * 58 | * @param maxdeeplevel the maxdeeplevel 59 | * @param req the req 60 | * @param res the res 61 | */ 62 | @GetMapping("/setting/scan/{maxdeeplevel}") 63 | public void annotationScan(@PathVariable int maxdeeplevel, HttpServletRequest req, HttpServletResponse res) { 64 | this.validationSessionComponent.sessionCheck(req); 65 | this.msgSaver.annotationScan(maxdeeplevel); 66 | } 67 | 68 | /** 69 | * Download api json all. 70 | * 71 | * @param req the req 72 | * @param res the res 73 | */ 74 | @GetMapping("/setting/download/api/json/all") 75 | public void downloadApiJsonAll(HttpServletRequest req, HttpServletResponse res) { 76 | this.validationSessionComponent.sessionCheck(req); 77 | List list = this.msgSettingService.getAllValidationData(); 78 | ValidationFileUtil.sendFileToHttpServiceResponse("validation.json", list, res); 79 | } 80 | 81 | /** 82 | * Download api json. 83 | * 84 | * @param req the req 85 | * @param method the method 86 | * @param url the url 87 | * @param res the res 88 | */ 89 | @GetMapping("/setting/download/api/json") 90 | public void downloadApiJson(HttpServletRequest req, @RequestParam("method") String method, @RequestParam("url") String url, HttpServletResponse res) { 91 | this.validationSessionComponent.sessionCheck(req); 92 | url = new String(Base64.getDecoder().decode(url)); 93 | List list = this.msgSettingService.getValidationData(method, url); 94 | ValidationFileUtil.sendFileToHttpServiceResponse(method + url.replaceAll("/", "-") + ".json", list, res); 95 | } 96 | 97 | /** 98 | * Download api all. 99 | * 100 | * @param req the req 101 | * @param res the res 102 | */ 103 | @GetMapping("/setting/download/api/excel/all") 104 | public void downloadApiAll(HttpServletRequest req, HttpServletResponse res) { 105 | this.validationSessionComponent.sessionCheck(req); 106 | PoiWorkBook workBook = this.msgExcelService.getAllExcels(); 107 | workBook.writeFile("ValidationApis_" + System.currentTimeMillis(), res); 108 | } 109 | 110 | /** 111 | * Download api. 112 | * 113 | * @param req the req 114 | * @param method the method 115 | * @param url the url 116 | * @param res the res 117 | */ 118 | @GetMapping("/setting/download/api/excel") 119 | public void downloadApi(HttpServletRequest req, @RequestParam("method") String method, @RequestParam("url") String url, HttpServletResponse res) { 120 | this.validationSessionComponent.sessionCheck(req); 121 | url = new String(Base64.getDecoder().decode(url)); 122 | PoiWorkBook workBook = this.msgExcelService.getExcel(method, url); 123 | workBook.writeFile("ValidationApis_" + System.currentTimeMillis(), res); 124 | } 125 | 126 | /** 127 | * Upload setting. 128 | * 129 | * @param req the req 130 | */ 131 | @PostMapping("/setting/upload/json") 132 | public void uploadSetting(HttpServletRequest req) { 133 | this.validationSessionComponent.sessionCheck(req); 134 | this.msgSettingService.updateValidationData((MultipartHttpServletRequest) req); 135 | } 136 | 137 | 138 | /** 139 | * Req url all list list. 140 | * 141 | * @param req the req 142 | * @return the list 143 | */ 144 | @GetMapping("/setting/url/list/all") 145 | public List reqUrlAllList(HttpServletRequest req) { 146 | this.validationSessionComponent.sessionCheck(req); 147 | return this.msgSettingService.getAllUrlList(); 148 | } 149 | 150 | /** 151 | * Gets validation data lists. 152 | * 153 | * @param req the req 154 | * @return the validation data lists 155 | */ 156 | @GetMapping("/setting/param/from/url") 157 | public List getValidationDataLists(HttpServletRequest req) { 158 | this.validationSessionComponent.sessionCheck(req); 159 | ValidationData data = ParameterMapper.requestParamaterToObject(req, ValidationData.class, "UTF-8"); 160 | return this.msgSettingService.getValidationData(data.getParamType(), data.getMethod(), data.getUrl()); 161 | } 162 | 163 | /** 164 | * Update validation data lists. 165 | * 166 | * @param req the req 167 | * @param datas the datas 168 | */ 169 | @PostMapping("/setting/update/param/from/url") 170 | public void updateValidationDataLists(HttpServletRequest req, @RequestBody List datas) { 171 | this.validationSessionComponent.sessionCheck(req); 172 | this.msgSettingService.updateValidationData(datas); 173 | } 174 | 175 | /** 176 | * Delete validation data lists. 177 | * 178 | * @param req the req 179 | * @param datas the datas 180 | */ 181 | @DeleteMapping("/setting/delete/param/from/url") 182 | public void deleteValidationDataLists(HttpServletRequest req, @RequestBody List datas) { 183 | this.validationSessionComponent.sessionCheck(req); 184 | this.msgSettingService.deleteValidationData(datas); 185 | } 186 | 187 | /** 188 | * Delete validation url. 189 | * 190 | * @param req the req 191 | * @param reqUrl the req url 192 | */ 193 | @DeleteMapping("/setting/delete/url") 194 | public void deleteValidationUrl(HttpServletRequest req, @RequestBody ReqUrl reqUrl) { 195 | this.validationSessionComponent.sessionCheck(req); 196 | this.msgSettingService.deleteValidationData(reqUrl); 197 | } 198 | 199 | /** 200 | * Delete validation url. 201 | * 202 | * @param req the req 203 | */ 204 | @DeleteMapping("/setting/delete/all") 205 | public void cleanValidationDatas(HttpServletRequest req) { 206 | this.validationSessionComponent.sessionCheck(req); 207 | this.msgSettingService.deleteAll(); 208 | } 209 | 210 | 211 | /** 212 | * Validation exception resolver validation exception resolver. 213 | * 214 | * @return the validation exception resolver 215 | */ 216 | @Bean 217 | public ValidationExceptionResolver validationExceptionResolver() { 218 | return ComponentMap.get(ValidationExceptionResolver.class); 219 | } 220 | 221 | /** 222 | * Intercepter config validation intercepter config. 223 | * 224 | * @return the validation intercepter config 225 | */ 226 | @Bean 227 | public ValidationIntercepterConfig intercepterConfig() { 228 | return ComponentMap.get(ValidationIntercepterConfig.class); 229 | } 230 | 231 | /** 232 | * Validation config validation config. 233 | * 234 | * @return the validation config 235 | */ 236 | @Bean 237 | public ValidationConfig validationConfig() { 238 | return ComponentMap.get(ValidationConfig.class); 239 | } 240 | 241 | /** 242 | * Init check point init check point. 243 | * 244 | * @return the init check point 245 | */ 246 | @Bean 247 | public InitCheckPoint initCheckPoint() { 248 | return ComponentMap.get(InitCheckPoint.class); 249 | } 250 | 251 | } 252 | --------------------------------------------------------------------------------