From bfad16fcaec537cebc277a3bd37a8bf67fed5bfe Mon Sep 17 00:00:00 2001 From: Florent CHAMFROY Date: Thu, 20 Jan 2022 22:30:38 +0100 Subject: [PATCH] style: setup & apply prettier --- .prettierrc | 2 + pom.xml | 17 +++ .../policy/requestvalidation/Constraint.java | 3 +- .../requestvalidation/ConstraintType.java | 1 - .../ConstraintValidator.java | 4 +- .../ConstraintValidatorContext.java | 1 - .../RequestValidationPolicy.java | 46 +++---- .../policy/requestvalidation/Rule.java | 8 +- .../policy/requestvalidation/Validator.java | 1 - .../configuration/PolicyScope.java | 2 +- .../RequestValidationPolicyConfiguration.java | 1 - .../RequestValidationOAIOperationVisitor.java | 67 +++++----- ...uestValidationSwaggerOperationVisitor.java | 5 +- .../AbstractConstraintValidator.java | 5 +- .../DateFormatConstraintValidator.java | 26 ++-- .../validator/DefaultValidator.java | 7 +- .../validator/EnumConstraintValidator.java | 10 +- .../validator/ExpressionBasedValidator.java | 6 +- .../validator/MailConstraintValidator.java | 7 +- .../validator/MaxConstraintValidator.java | 6 +- .../validator/MinConstraintValidator.java | 6 +- .../validator/NotNullConstraintValidator.java | 1 - .../validator/PatternConstraintValidator.java | 12 +- .../validator/SizeConstraintValidator.java | 10 +- .../validator/StringConstraintValidator.java | 3 +- .../RequestValidationPolicyTest.java | 115 +++++++----------- .../DateFormatConstraintValidatorTest.java | 6 +- .../EnumConstraintValidatorTest.java | 1 - .../PatternConstraintValidatorTest.java | 13 +- 29 files changed, 182 insertions(+), 210 deletions(-) create mode 100644 .prettierrc diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..aa85a8f --- /dev/null +++ b/.prettierrc @@ -0,0 +1,2 @@ +printWidth: 140 +tabWidth: 4 diff --git a/pom.xml b/pom.xml index 3a6100d..ae48278 100644 --- a/pom.xml +++ b/pom.xml @@ -179,6 +179,23 @@ + + com.hubspot.maven.plugins + prettier-maven-plugin + 0.17 + + 12.13.0 + 1.6.1 + + + + validate + + check + + + + diff --git a/src/main/java/io/gravitee/policy/requestvalidation/Constraint.java b/src/main/java/io/gravitee/policy/requestvalidation/Constraint.java index 0a65a6d..486ee00 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/Constraint.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/Constraint.java @@ -30,8 +30,7 @@ public class Constraint { private String message; - public Constraint() { - } + public Constraint() {} public Constraint(Constraint other) { this.type = other.type; diff --git a/src/main/java/io/gravitee/policy/requestvalidation/ConstraintType.java b/src/main/java/io/gravitee/policy/requestvalidation/ConstraintType.java index 8d49dfd..38c2a66 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/ConstraintType.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/ConstraintType.java @@ -22,7 +22,6 @@ * @author GraviteeSource Team */ public enum ConstraintType { - NOT_NULL(NotNullConstraintValidator.class), MAIL(MailConstraintValidator.class), PATTERN(PatternConstraintValidator.class), diff --git a/src/main/java/io/gravitee/policy/requestvalidation/ConstraintValidator.java b/src/main/java/io/gravitee/policy/requestvalidation/ConstraintValidator.java index 54c78f6..3799be4 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/ConstraintValidator.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/ConstraintValidator.java @@ -20,11 +20,9 @@ * @author GraviteeSource Team */ public interface ConstraintValidator { - - void initialize(String ... parameters); + void initialize(String... parameters); boolean isValid(T value); String getMessageTemplate(); - } diff --git a/src/main/java/io/gravitee/policy/requestvalidation/ConstraintValidatorContext.java b/src/main/java/io/gravitee/policy/requestvalidation/ConstraintValidatorContext.java index f6e3e0c..71f0d64 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/ConstraintValidatorContext.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/ConstraintValidatorContext.java @@ -22,6 +22,5 @@ * @author GraviteeSource Team */ public interface ConstraintValidatorContext { - List rules(); } diff --git a/src/main/java/io/gravitee/policy/requestvalidation/RequestValidationPolicy.java b/src/main/java/io/gravitee/policy/requestvalidation/RequestValidationPolicy.java index 2089293..cd0b045 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/RequestValidationPolicy.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/RequestValidationPolicy.java @@ -15,6 +15,8 @@ */ package io.gravitee.policy.requestvalidation; +import static java.util.stream.Collectors.toList; + import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; @@ -36,13 +38,10 @@ import io.gravitee.policy.requestvalidation.configuration.PolicyScope; import io.gravitee.policy.requestvalidation.configuration.RequestValidationPolicyConfiguration; import io.gravitee.policy.requestvalidation.validator.ExpressionBasedValidator; - import java.util.LinkedHashSet; import java.util.List; import java.util.Set; -import static java.util.stream.Collectors.toList; - /** * @author David BRASSELY (david.brassely at graviteesource.com) * @author GraviteeSource Team @@ -54,15 +53,14 @@ public class RequestValidationPolicy { */ private RequestValidationPolicyConfiguration configuration; - private final static String FIELD_MESSAGE = "message"; - private final static String FIELD_CONSTRAINTS = "constraints"; - private final static String DEFAULT_MESSAGE = "Request is not valid according to constraint rules"; + private static final String FIELD_MESSAGE = "message"; + private static final String FIELD_CONSTRAINTS = "constraints"; + private static final String DEFAULT_MESSAGE = "Request is not valid according to constraint rules"; - private final static String REQUEST_VARIABLE = "request"; + private static final String REQUEST_VARIABLE = "request"; private static final String REQUEST_VALIDATION_INVALID = "REQUEST_VALIDATION_INVALID"; - /** * Create a new policy instance based on its associated configuration * @@ -74,21 +72,24 @@ public RequestValidationPolicy(RequestValidationPolicyConfiguration configuratio @OnRequest public void onRequest(Request request, Response response, ExecutionContext executionContext, PolicyChain policyChain) { - if ((configuration.getScope() == null || configuration.getScope() == PolicyScope.REQUEST) - && (configuration.getRules() != null && !configuration.getRules().isEmpty())) { + if ( + (configuration.getScope() == null || configuration.getScope() == PolicyScope.REQUEST) && + (configuration.getRules() != null && !configuration.getRules().isEmpty()) + ) { Set violations = validate(executionContext); if (violations.isEmpty()) { policyChain.doNext(request, response); } else { final List messageViolations = violations.stream().map(ConstraintViolation::getMessage).collect(toList()); - policyChain.failWith(PolicyResult.failure( + policyChain.failWith( + PolicyResult.failure( REQUEST_VALIDATION_INVALID, configuration.getStatus(), createErrorPayload(violations), - Maps.builder() - .put("violations", messageViolations) - .build())); + Maps.builder().put("violations", messageViolations).build() + ) + ); } } else { policyChain.doNext(request, response); @@ -99,7 +100,6 @@ public void onRequest(Request request, Response response, ExecutionContext execu public ReadWriteStream onRequestContent(Request request, ExecutionContext executionContext, PolicyChain policyChain) { if (configuration.getScope() != null && configuration.getScope() == PolicyScope.REQUEST_CONTENT) { return new BufferedReadWriteStream() { - Buffer buffer = Buffer.buffer(); @Override @@ -111,21 +111,24 @@ public SimpleReadWriteStream write(Buffer content) { @Override public void end() { String content = buffer.toString(); - executionContext.getTemplateEngine().getTemplateContext() - .setVariable(REQUEST_VARIABLE, new EvaluableRequest(request, content)); + executionContext + .getTemplateEngine() + .getTemplateContext() + .setVariable(REQUEST_VARIABLE, new EvaluableRequest(request, content)); // Apply validation rules Set violations = validate(executionContext); if (!violations.isEmpty()) { final List messageViolations = violations.stream().map(ConstraintViolation::getMessage).collect(toList()); - policyChain.streamFailWith(PolicyResult.failure( + policyChain.streamFailWith( + PolicyResult.failure( REQUEST_VALIDATION_INVALID, configuration.getStatus(), createErrorPayload(violations), - Maps.builder() - .put("violations", messageViolations) - .build())); + Maps.builder().put("violations", messageViolations).build() + ) + ); } else { if (buffer.length() > 0) { super.write(buffer); @@ -143,7 +146,6 @@ public void end() { private Set validate(ExecutionContext executionContext) { LinkedHashSet violations = new LinkedHashSet<>(); for (Rule rule : configuration.getRules()) { - TemplateEngine templateEngine = executionContext.getTemplateEngine(); String input = templateEngine.getValue(rule.getInput(), String.class); if (rule.getIsRequired() || input != null) { diff --git a/src/main/java/io/gravitee/policy/requestvalidation/Rule.java b/src/main/java/io/gravitee/policy/requestvalidation/Rule.java index d02a94a..bab56f4 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/Rule.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/Rule.java @@ -43,7 +43,11 @@ public void setConstraint(Constraint constraint) { this.constraint = constraint; } - public boolean getIsRequired() { return isRequired; } + public boolean getIsRequired() { + return isRequired; + } - public void setIsRequired(boolean isRequired) { this.isRequired = isRequired;} + public void setIsRequired(boolean isRequired) { + this.isRequired = isRequired; + } } diff --git a/src/main/java/io/gravitee/policy/requestvalidation/Validator.java b/src/main/java/io/gravitee/policy/requestvalidation/Validator.java index 1f2d0fb..c3078d0 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/Validator.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/Validator.java @@ -20,6 +20,5 @@ * @author GraviteeSource Team */ public interface Validator { - ConstraintViolation validate(String input, Constraint constraint); } diff --git a/src/main/java/io/gravitee/policy/requestvalidation/configuration/PolicyScope.java b/src/main/java/io/gravitee/policy/requestvalidation/configuration/PolicyScope.java index 410df1e..024966f 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/configuration/PolicyScope.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/configuration/PolicyScope.java @@ -21,5 +21,5 @@ */ public enum PolicyScope { REQUEST, - REQUEST_CONTENT + REQUEST_CONTENT, } diff --git a/src/main/java/io/gravitee/policy/requestvalidation/configuration/RequestValidationPolicyConfiguration.java b/src/main/java/io/gravitee/policy/requestvalidation/configuration/RequestValidationPolicyConfiguration.java index bfad4a1..5f27554 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/configuration/RequestValidationPolicyConfiguration.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/configuration/RequestValidationPolicyConfiguration.java @@ -18,7 +18,6 @@ import io.gravitee.common.http.HttpStatusCode; import io.gravitee.policy.api.PolicyConfiguration; import io.gravitee.policy.requestvalidation.Rule; - import java.util.List; /** diff --git a/src/main/java/io/gravitee/policy/requestvalidation/swagger/RequestValidationOAIOperationVisitor.java b/src/main/java/io/gravitee/policy/requestvalidation/swagger/RequestValidationOAIOperationVisitor.java index 93dbeae..1688c4a 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/swagger/RequestValidationOAIOperationVisitor.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/swagger/RequestValidationOAIOperationVisitor.java @@ -29,7 +29,6 @@ import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.parameters.Parameter; - import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -41,7 +40,7 @@ */ public class RequestValidationOAIOperationVisitor implements OAIOperationVisitor { - private final ObjectMapper mapper = new ObjectMapper(); + private final ObjectMapper mapper = new ObjectMapper(); { mapper.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true); @@ -54,41 +53,43 @@ public Optional visit(OpenAPI oapi, Operation operation) { List rules = new ArrayList<>(); if (parameters != null && !parameters.isEmpty()) { - parameters.forEach(new Consumer() { - @Override - public void accept(Parameter parameter) { - String in = parameter.getIn(); - switch (in) { - case "query": - Rule rule = new Rule(); - rule.setInput("{#request.params['" + parameter.getName() + "']}"); - - Constraint constraint = new Constraint(); - constraint.setType(ConstraintType.NOT_NULL); - constraint.setMessage(parameter.getName() + " query parameter is required"); - - rule.setConstraint(constraint); - - rules.add(rule); - break; - case "header": - Rule headerRule = new Rule(); - headerRule.setInput("{#request.headers['" + parameter.getName() + "'][0]}"); - - Constraint headerConstraint = new Constraint(); - headerConstraint.setType(ConstraintType.NOT_NULL); - headerConstraint.setMessage(parameter.getName() + " header is required"); - - headerRule.setConstraint(headerConstraint); - - rules.add(headerRule); - break; + parameters.forEach( + new Consumer() { + @Override + public void accept(Parameter parameter) { + String in = parameter.getIn(); + switch (in) { + case "query": + Rule rule = new Rule(); + rule.setInput("{#request.params['" + parameter.getName() + "']}"); + + Constraint constraint = new Constraint(); + constraint.setType(ConstraintType.NOT_NULL); + constraint.setMessage(parameter.getName() + " query parameter is required"); + + rule.setConstraint(constraint); + + rules.add(rule); + break; + case "header": + Rule headerRule = new Rule(); + headerRule.setInput("{#request.headers['" + parameter.getName() + "'][0]}"); + + Constraint headerConstraint = new Constraint(); + headerConstraint.setType(ConstraintType.NOT_NULL); + headerConstraint.setMessage(parameter.getName() + " header is required"); + + headerRule.setConstraint(headerConstraint); + + rules.add(headerRule); + break; + } } } - }); + ); } - if (! rules.isEmpty()) { + if (!rules.isEmpty()) { try { Policy policy = new Policy(); policy.setName("policy-request-validation"); diff --git a/src/main/java/io/gravitee/policy/requestvalidation/swagger/RequestValidationSwaggerOperationVisitor.java b/src/main/java/io/gravitee/policy/requestvalidation/swagger/RequestValidationSwaggerOperationVisitor.java index 02caabd..fd00609 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/swagger/RequestValidationSwaggerOperationVisitor.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/swagger/RequestValidationSwaggerOperationVisitor.java @@ -29,7 +29,6 @@ import io.swagger.models.Operation; import io.swagger.models.Swagger; import io.swagger.models.parameters.Parameter; - import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -40,7 +39,7 @@ */ public class RequestValidationSwaggerOperationVisitor implements SwaggerOperationVisitor { - private final ObjectMapper mapper = new ObjectMapper(); + private final ObjectMapper mapper = new ObjectMapper(); { mapper.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true); @@ -84,7 +83,7 @@ public Optional visit(Swagger descriptor, Operation operation) { }); } - if (! rules.isEmpty()) { + if (!rules.isEmpty()) { try { Policy policy = new Policy(); policy.setName("policy-request-validation"); diff --git a/src/main/java/io/gravitee/policy/requestvalidation/validator/AbstractConstraintValidator.java b/src/main/java/io/gravitee/policy/requestvalidation/validator/AbstractConstraintValidator.java index 64f9887..53e142b 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/validator/AbstractConstraintValidator.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/validator/AbstractConstraintValidator.java @@ -16,7 +16,6 @@ package io.gravitee.policy.requestvalidation.validator; import io.gravitee.policy.requestvalidation.ConstraintValidator; - import java.util.List; /** @@ -26,7 +25,5 @@ public abstract class AbstractConstraintValidator implements ConstraintValidator { @Override - public void initialize(String ... parameters) { - - } + public void initialize(String... parameters) {} } diff --git a/src/main/java/io/gravitee/policy/requestvalidation/validator/DateFormatConstraintValidator.java b/src/main/java/io/gravitee/policy/requestvalidation/validator/DateFormatConstraintValidator.java index f4822b1..29f3e40 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/validator/DateFormatConstraintValidator.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/validator/DateFormatConstraintValidator.java @@ -29,34 +29,32 @@ public class DateFormatConstraintValidator extends StringConstraintValidator { private SimpleDateFormat dateFormat; @Override - public void initialize(String ... parameters) { + public void initialize(String... parameters) { try { if (parameters != null && parameters.length > 0) { dateFormat = new SimpleDateFormat(parameters[0]); dateFormat.setLenient(false); init = true; } - } catch (Throwable t) { - } + } catch (Throwable t) {} } @Override public boolean isValid(String value) { - if (value == null || !init) { - return false; - } - - try { - dateFormat.parse(value); - return true; - } catch (ParseException pex) { - return false; - } + if (value == null || !init) { + return false; + } + + try { + dateFormat.parse(value); + return true; + } catch (ParseException pex) { + return false; + } } @Override public String getMessageTemplate() { return "'%s' is not valid (format: '%s')"; } - } diff --git a/src/main/java/io/gravitee/policy/requestvalidation/validator/DefaultValidator.java b/src/main/java/io/gravitee/policy/requestvalidation/validator/DefaultValidator.java index 79976d5..be8cfc4 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/validator/DefaultValidator.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/validator/DefaultValidator.java @@ -33,15 +33,16 @@ public ConstraintViolation validate(String input, Constraint constraint) { ConstraintValidator constraintValidator = clazz.newInstance(); constraintValidator.initialize(constraint.getParameters()); boolean valid = constraintValidator.isValid(input); - if (! valid) { + if (!valid) { ConstraintViolation violation = new ConstraintViolation(); // Get message from validator String[] parameters = (constraint.getParameters() != null) ? constraint.getParameters() : new String[0]; - String[] inputs = new String[parameters.length+1]; + String[] inputs = new String[parameters.length + 1]; inputs[0] = input; System.arraycopy(parameters, 0, inputs, 1, parameters.length); String message = (constraint.getMessage() == null || constraint.getMessage().isEmpty()) - ? constraintValidator.getMessageTemplate() : constraint.getMessage(); + ? constraintValidator.getMessageTemplate() + : constraint.getMessage(); violation.setMessage(String.format(message, inputs)); return violation; diff --git a/src/main/java/io/gravitee/policy/requestvalidation/validator/EnumConstraintValidator.java b/src/main/java/io/gravitee/policy/requestvalidation/validator/EnumConstraintValidator.java index 3d38ff3..df82e78 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/validator/EnumConstraintValidator.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/validator/EnumConstraintValidator.java @@ -29,7 +29,7 @@ public class EnumConstraintValidator extends StringConstraintValidator { private boolean init = false; @Override - public void initialize(String ... parameters) { + public void initialize(String... parameters) { try { if (parameters != null) { for (String s : parameters) { @@ -37,20 +37,16 @@ public void initialize(String ... parameters) { } init = true; } - } catch (Throwable t) { - } + } catch (Throwable t) {} } @Override public boolean isValid(String value) { - return init && - value != null && - data.contains(value); + return init && value != null && data.contains(value); } @Override public String getMessageTemplate() { return "'%s' not included in ENUM"; } - } diff --git a/src/main/java/io/gravitee/policy/requestvalidation/validator/ExpressionBasedValidator.java b/src/main/java/io/gravitee/policy/requestvalidation/validator/ExpressionBasedValidator.java index 537e16b..9b54b29 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/validator/ExpressionBasedValidator.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/validator/ExpressionBasedValidator.java @@ -18,7 +18,6 @@ import io.gravitee.el.TemplateEngine; import io.gravitee.policy.requestvalidation.Constraint; import io.gravitee.policy.requestvalidation.ConstraintViolation; - import java.util.Arrays; /** @@ -36,10 +35,7 @@ public ExpressionBasedValidator(TemplateEngine templateEngine) { @Override public ConstraintViolation validate(String input, Constraint constraint) { if (constraint.getParameters() != null) { - constraint.setParameters(Arrays - .stream(constraint.getParameters()) - .map(templateEngine::convert) - .toArray(String[]::new)); + constraint.setParameters(Arrays.stream(constraint.getParameters()).map(templateEngine::convert).toArray(String[]::new)); } return super.validate(templateEngine.convert(input), constraint); diff --git a/src/main/java/io/gravitee/policy/requestvalidation/validator/MailConstraintValidator.java b/src/main/java/io/gravitee/policy/requestvalidation/validator/MailConstraintValidator.java index a157ae0..48033ff 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/validator/MailConstraintValidator.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/validator/MailConstraintValidator.java @@ -24,8 +24,10 @@ */ public class MailConstraintValidator extends PatternConstraintValidator { - private static final Pattern VALID_EMAIL_ADDRESS_REGEX = - Pattern.compile("^[A-Z0-9._%+-]+(@|%40)[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE); + private static final Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern.compile( + "^[A-Z0-9._%+-]+(@|%40)[A-Z0-9.-]+\\.[A-Z]{2,6}$", + Pattern.CASE_INSENSITIVE + ); @Override public boolean isValid(String value) { @@ -41,5 +43,4 @@ public boolean isValid(String value) { public String getMessageTemplate() { return "%s is not a valid email."; } - } diff --git a/src/main/java/io/gravitee/policy/requestvalidation/validator/MaxConstraintValidator.java b/src/main/java/io/gravitee/policy/requestvalidation/validator/MaxConstraintValidator.java index 3fd2b60..4603d27 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/validator/MaxConstraintValidator.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/validator/MaxConstraintValidator.java @@ -26,14 +26,13 @@ public class MaxConstraintValidator extends NumberConstraintValidator { private boolean init = false; @Override - public void initialize(String ... parameters) { + public void initialize(String... parameters) { try { if (parameters != null && parameters.length > 0) { max = Long.parseLong(parameters[0]); init = true; } - } catch (Throwable t) { - } + } catch (Throwable t) {} } @Override @@ -45,5 +44,4 @@ boolean isValid(Number value) { public String getMessageTemplate() { return "'%s' must be lower or equals to '%s'"; } - } diff --git a/src/main/java/io/gravitee/policy/requestvalidation/validator/MinConstraintValidator.java b/src/main/java/io/gravitee/policy/requestvalidation/validator/MinConstraintValidator.java index 7cb4820..5342ece 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/validator/MinConstraintValidator.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/validator/MinConstraintValidator.java @@ -26,14 +26,13 @@ public class MinConstraintValidator extends NumberConstraintValidator { private boolean init = false; @Override - public void initialize(String ... parameters) { + public void initialize(String... parameters) { try { if (parameters != null && parameters.length > 0) { min = Long.parseLong(parameters[0]); init = true; } - } catch (Throwable t) { - } + } catch (Throwable t) {} } @Override @@ -45,5 +44,4 @@ boolean isValid(Number value) { public String getMessageTemplate() { return "'%s' must be higher or equals to '%s'"; } - } diff --git a/src/main/java/io/gravitee/policy/requestvalidation/validator/NotNullConstraintValidator.java b/src/main/java/io/gravitee/policy/requestvalidation/validator/NotNullConstraintValidator.java index 8766f50..37d8135 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/validator/NotNullConstraintValidator.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/validator/NotNullConstraintValidator.java @@ -30,5 +30,4 @@ public boolean isValid(String value) { public String getMessageTemplate() { return "'%s' can not be null."; } - } diff --git a/src/main/java/io/gravitee/policy/requestvalidation/validator/PatternConstraintValidator.java b/src/main/java/io/gravitee/policy/requestvalidation/validator/PatternConstraintValidator.java index 567360f..fbc9287 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/validator/PatternConstraintValidator.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/validator/PatternConstraintValidator.java @@ -28,21 +28,20 @@ public class PatternConstraintValidator extends StringConstraintValidator { private Pattern pattern; @Override - public void initialize(String ... parameters) { + public void initialize(String... parameters) { try { if (parameters != null && parameters.length > 0) { pattern = Pattern.compile(parameters[0]); init = true; } - } catch (Throwable t) { - } + } catch (Throwable t) {} } @Override public boolean isValid(String value) { - if(value == null) { - return false; - } + if (value == null) { + return false; + } return init && pattern.matcher(value).find(); } @@ -50,5 +49,4 @@ public boolean isValid(String value) { public String getMessageTemplate() { return "'%s' is not valid (pattern: '%s')"; } - } diff --git a/src/main/java/io/gravitee/policy/requestvalidation/validator/SizeConstraintValidator.java b/src/main/java/io/gravitee/policy/requestvalidation/validator/SizeConstraintValidator.java index 21a364d..f694f7f 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/validator/SizeConstraintValidator.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/validator/SizeConstraintValidator.java @@ -27,27 +27,23 @@ public class SizeConstraintValidator extends StringConstraintValidator { private boolean init = false; @Override - public void initialize(String ... parameters) { + public void initialize(String... parameters) { try { if (parameters != null && parameters.length > 1) { min = Long.parseLong(parameters[0]); max = Long.parseLong(parameters[1]); init = true; } - } catch (Throwable t) { - } + } catch (Throwable t) {} } @Override public boolean isValid(String value) { - return init && - value != null && - value.length() >= min && value.length() <= max; + return init && value != null && value.length() >= min && value.length() <= max; } @Override public String getMessageTemplate() { return "'%s' length must be higher or equals to '%s' and lower or equals to '%s'"; } - } diff --git a/src/main/java/io/gravitee/policy/requestvalidation/validator/StringConstraintValidator.java b/src/main/java/io/gravitee/policy/requestvalidation/validator/StringConstraintValidator.java index f7c9e87..3d01eba 100644 --- a/src/main/java/io/gravitee/policy/requestvalidation/validator/StringConstraintValidator.java +++ b/src/main/java/io/gravitee/policy/requestvalidation/validator/StringConstraintValidator.java @@ -19,5 +19,4 @@ * @author David BRASSELY (david.brassely at graviteesource.com) * @author GraviteeSource Team */ -abstract class StringConstraintValidator extends AbstractConstraintValidator { -} +abstract class StringConstraintValidator extends AbstractConstraintValidator {} diff --git a/src/test/java/io/gravitee/policy/requestvalidation/RequestValidationPolicyTest.java b/src/test/java/io/gravitee/policy/requestvalidation/RequestValidationPolicyTest.java index 532634f..c2da875 100644 --- a/src/test/java/io/gravitee/policy/requestvalidation/RequestValidationPolicyTest.java +++ b/src/test/java/io/gravitee/policy/requestvalidation/RequestValidationPolicyTest.java @@ -15,6 +15,9 @@ */ package io.gravitee.policy.requestvalidation; +import static org.mockito.Matchers.argThat; +import static org.mockito.Mockito.*; + import io.gravitee.common.http.HttpStatusCode; import io.gravitee.common.util.MultiValueMap; import io.gravitee.el.TemplateEngine; @@ -26,6 +29,8 @@ import io.gravitee.policy.api.PolicyChain; import io.gravitee.policy.requestvalidation.configuration.RequestValidationPolicyConfiguration; import io.gravitee.policy.requestvalidation.validator.*; +import java.util.*; +import java.util.regex.Pattern; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -33,12 +38,6 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import java.util.*; -import java.util.regex.Pattern; - -import static org.mockito.Matchers.argThat; -import static org.mockito.Mockito.*; - /** * @author David BRASSELY (david.brassely at graviteesource.com) * @author GraviteeSource Team @@ -143,7 +142,7 @@ public void shouldNotValidateQueryParameter_invalidMinConstraint() { rule.setInput("{#request.params['my-param']}"); Constraint constraint = new Constraint(); constraint.setType(ConstraintType.MIN); - constraint.setParameters(new String []{"toto"}); // Toto is not a valid number + constraint.setParameters(new String[] { "toto" }); // Toto is not a valid number rule.setConstraint(constraint); when(configuration.getRules()).thenReturn(Collections.singletonList(rule)); @@ -179,7 +178,7 @@ public void shouldValidateQueryParameter_multipleRules() { constraint.setType(ConstraintType.NOT_NULL); Constraint constraintMin = new Constraint(); constraintMin.setType(ConstraintType.MIN); - constraintMin.setParameters(new String []{"50"}); + constraintMin.setParameters(new String[] { "50" }); rule.setConstraint(constraint); Rule rule2 = new Rule(); @@ -213,7 +212,7 @@ public void shouldValidatePathParameter_el_Rule() { rule.setInput("{#request.pathInfos[1]}"); Constraint constraint = new Constraint(); constraint.setType(ConstraintType.PATTERN); - constraint.setParameters(new String []{"{#request.pathInfos[1]}"}); + constraint.setParameters(new String[] { "{#request.pathInfos[1]}" }); rule.setConstraint(constraint); when(configuration.getRules()).thenReturn(Arrays.asList(rule)); @@ -243,7 +242,7 @@ public void shouldValidateQueryParameter_RuleWithParamsContainsNull() { rule.setInput("{#request.params['my-param']}"); Constraint constraint = new Constraint(); constraint.setType(ConstraintType.NOT_NULL); - constraint.setParameters(new String[]{null}); + constraint.setParameters(new String[] { null }); rule.setConstraint(constraint); when(configuration.getRules()).thenReturn(Collections.singletonList(rule)); @@ -255,7 +254,7 @@ public void shouldValidateQueryParameter_RuleWithParamsContainsNull() { verify(policyChain).doNext(request, response); } - public Rule prepareRule(String input, String[] params, ConstraintType constraintType){ + public Rule prepareRule(String input, String[] params, ConstraintType constraintType) { Rule rule = new Rule(); rule.setInput(input); Constraint constraint = new Constraint(); @@ -267,7 +266,6 @@ public Rule prepareRule(String input, String[] params, ConstraintType constraint @Test public void shouldValidateTheOrderOfViolationsWhenUsingMultipleRules() { - final String RULE_VALUE = "{#request.headers['my-header']}"; final String PATTERN = "^[0-9a-fA-F]{32}\\z"; @@ -286,34 +284,19 @@ public void shouldValidateTheOrderOfViolationsWhenUsingMultipleRules() { validatorRegexMap.put(PatternConstraintValidator.class, "^'.+' is not valid \\(pattern: '.+'\\)$"); validatorRegexMap.put(MinConstraintValidator.class, "^'.+' must be higher or equals to '\\d+'"); validatorRegexMap.put(MaxConstraintValidator.class, "^'.+' must be lower or equals to '\\d+'"); - validatorRegexMap.put(SizeConstraintValidator.class, "'.+' length must be higher or equals to '\\d+' and lower or equals to '\\d+'"); + validatorRegexMap.put( + SizeConstraintValidator.class, + "'.+' length must be higher or equals to '\\d+' and lower or equals to '\\d+'" + ); validatorRegexMap.put(MailConstraintValidator.class, "^.+ is not a valid email.$"); LinkedHashMap rulesMap = new LinkedHashMap<>(); - rulesMap.put( - prepareRule(RULE_VALUE, new String[]{"*"}, ConstraintType.NOT_NULL), - new NotNullConstraintValidator() - ); - rulesMap.put( - prepareRule(RULE_VALUE, new String[]{PATTERN}, ConstraintType.PATTERN), - new PatternConstraintValidator() - ); - rulesMap.put( - prepareRule(RULE_VALUE, new String[]{"5"}, ConstraintType.MIN), - new MinConstraintValidator() - ); - rulesMap.put( - prepareRule(RULE_VALUE, new String[]{"5"}, ConstraintType.MAX), - new MaxConstraintValidator() - ); - rulesMap.put( - prepareRule(RULE_VALUE, new String[]{"5","10"}, ConstraintType.SIZE), - new SizeConstraintValidator() - ); - rulesMap.put( - prepareRule(RULE_VALUE, new String[]{"wrong-mail"}, ConstraintType.MAIL), - new MailConstraintValidator() - ); + rulesMap.put(prepareRule(RULE_VALUE, new String[] { "*" }, ConstraintType.NOT_NULL), new NotNullConstraintValidator()); + rulesMap.put(prepareRule(RULE_VALUE, new String[] { PATTERN }, ConstraintType.PATTERN), new PatternConstraintValidator()); + rulesMap.put(prepareRule(RULE_VALUE, new String[] { "5" }, ConstraintType.MIN), new MinConstraintValidator()); + rulesMap.put(prepareRule(RULE_VALUE, new String[] { "5" }, ConstraintType.MAX), new MaxConstraintValidator()); + rulesMap.put(prepareRule(RULE_VALUE, new String[] { "5", "10" }, ConstraintType.SIZE), new SizeConstraintValidator()); + rulesMap.put(prepareRule(RULE_VALUE, new String[] { "wrong-mail" }, ConstraintType.MAIL), new MailConstraintValidator()); ArrayList rules = new ArrayList<>(rulesMap.keySet()); when(configuration.getRules()).thenReturn(rules); @@ -322,23 +305,26 @@ public void shouldValidateTheOrderOfViolationsWhenUsingMultipleRules() { policy.onRequest(request, response, executionContext, policyChain); // Check results - verify(policyChain).failWith( - argThat(result -> { - ArrayList violationsTemp = (ArrayList) result.parameters().get("violations"); - ArrayDeque violations = new ArrayDeque<>(violationsTemp); - - rulesMap.entrySet().stream().forEach(ruleMapEntry -> { - ConstraintValidator validator = ruleMapEntry.getValue(); - String violation = violations.pollFirst(); - Assert.assertTrue(Pattern.matches(validatorRegexMap.get(validator.getClass()), violation)); - }); - - return result.statusCode() == HttpStatusCode.BAD_REQUEST_400; - }) - ); + verify(policyChain) + .failWith( + argThat(result -> { + ArrayList violationsTemp = (ArrayList) result.parameters().get("violations"); + ArrayDeque violations = new ArrayDeque<>(violationsTemp); + + rulesMap + .entrySet() + .stream() + .forEach(ruleMapEntry -> { + ConstraintValidator validator = ruleMapEntry.getValue(); + String violation = violations.pollFirst(); + Assert.assertTrue(Pattern.matches(validatorRegexMap.get(validator.getClass()), violation)); + }); + + return result.statusCode() == HttpStatusCode.BAD_REQUEST_400; + }) + ); } - @Test public void shouldValidateQueryParameter_NotRequiredAndNotPresent() { // Prepare inbound request @@ -355,7 +341,7 @@ public void shouldValidateQueryParameter_NotRequiredAndNotPresent() { rule.setInput("{#request.params['my-param']}"); Constraint constraint = new Constraint(); constraint.setType(ConstraintType.PATTERN); - String[] patterns = {"^[A-Za-z]+$"}; + String[] patterns = { "^[A-Za-z]+$" }; constraint.setParameters(patterns); rule.setConstraint(constraint); rule.setIsRequired(false); @@ -385,7 +371,7 @@ public void shouldNotValidateQueryParameter_RequiredAndNotPresent() { rule.setInput("{#request.params['my-param']}"); Constraint constraint = new Constraint(); constraint.setType(ConstraintType.PATTERN); - String[] patterns = {"^[A-Za-z]+$"}; + String[] patterns = { "^[A-Za-z]+$" }; constraint.setParameters(patterns); rule.setConstraint(constraint); rule.setIsRequired(true); @@ -399,7 +385,6 @@ public void shouldNotValidateQueryParameter_RequiredAndNotPresent() { verify(policyChain).failWith(argThat(result -> result.statusCode() == HttpStatusCode.BAD_REQUEST_400)); } - @Test public void shouldValidateQueryParameter_ValidPatternNotRequiredAndPresent() { // Prepare inbound request @@ -418,7 +403,7 @@ public void shouldValidateQueryParameter_ValidPatternNotRequiredAndPresent() { rule.setInput("{#request.params['my-param']}"); Constraint constraint = new Constraint(); constraint.setType(ConstraintType.PATTERN); - String[] patterns = {"^[A-Za-z]+$"}; + String[] patterns = { "^[A-Za-z]+$" }; constraint.setParameters(patterns); rule.setConstraint(constraint); rule.setIsRequired(false); @@ -432,7 +417,6 @@ public void shouldValidateQueryParameter_ValidPatternNotRequiredAndPresent() { verify(policyChain).doNext(request, response); } - @Test public void shouldValidateQueryParameter_ValidPatternRequiredAndPresent() { // Prepare inbound request @@ -451,7 +435,7 @@ public void shouldValidateQueryParameter_ValidPatternRequiredAndPresent() { rule.setInput("{#request.params['my-param']}"); Constraint constraint = new Constraint(); constraint.setType(ConstraintType.PATTERN); - String[] patterns = {"^[A-Za-z]+$"}; + String[] patterns = { "^[A-Za-z]+$" }; constraint.setParameters(patterns); rule.setConstraint(constraint); rule.setIsRequired(true); @@ -465,7 +449,6 @@ public void shouldValidateQueryParameter_ValidPatternRequiredAndPresent() { verify(policyChain).doNext(request, response); } - @Test public void shouldNotValidateQueryParameter_NotValidPatternNotRequiredAndPresent() { // Prepare inbound request @@ -484,7 +467,7 @@ public void shouldNotValidateQueryParameter_NotValidPatternNotRequiredAndPresent rule.setInput("{#request.params['my-param']}"); Constraint constraint = new Constraint(); constraint.setType(ConstraintType.PATTERN); - String[] patterns = {"^[A-Za-z]+$"}; + String[] patterns = { "^[A-Za-z]+$" }; constraint.setParameters(patterns); rule.setConstraint(constraint); rule.setIsRequired(false); @@ -496,7 +479,6 @@ public void shouldNotValidateQueryParameter_NotValidPatternNotRequiredAndPresent // Check results verify(policyChain).failWith(argThat(result -> result.statusCode() == HttpStatusCode.BAD_REQUEST_400)); - } @Test @@ -517,7 +499,7 @@ public void shouldNotValidateQueryParameter_NotValidPatternRequiredAndPresent() rule.setInput("{#request.params['my-param']}"); Constraint constraint = new Constraint(); constraint.setType(ConstraintType.PATTERN); - String[] patterns = {"^[A-Za-z]+$"}; + String[] patterns = { "^[A-Za-z]+$" }; constraint.setParameters(patterns); rule.setConstraint(constraint); rule.setIsRequired(true); @@ -529,7 +511,6 @@ public void shouldNotValidateQueryParameter_NotValidPatternRequiredAndPresent() // Check results verify(policyChain).failWith(argThat(result -> result.statusCode() == HttpStatusCode.BAD_REQUEST_400)); - } @Test @@ -550,7 +531,7 @@ public void shouldNotValidateQueryParameter_RuleNotRequiredAndEmptyParameter() { rule.setInput("{#request.params['my-param']}"); Constraint constraint = new Constraint(); constraint.setType(ConstraintType.PATTERN); - String[] patterns = {"^[A-Za-z]+$"}; + String[] patterns = { "^[A-Za-z]+$" }; constraint.setParameters(patterns); rule.setConstraint(constraint); rule.setIsRequired(false); @@ -562,7 +543,6 @@ public void shouldNotValidateQueryParameter_RuleNotRequiredAndEmptyParameter() { // Check results verify(policyChain).failWith(argThat(result -> result.statusCode() == HttpStatusCode.BAD_REQUEST_400)); - } @Test @@ -583,7 +563,7 @@ public void shouldValidateQueryParameter_inENUM() { rule.setInput("{#request.params['my-param']}"); Constraint constraint = new Constraint(); constraint.setType(ConstraintType.ENUM); - constraint.setParameters(new String []{"One", "Two"}); + constraint.setParameters(new String[] { "One", "Two" }); rule.setConstraint(constraint); when(configuration.getRules()).thenReturn(Arrays.asList(rule)); @@ -613,7 +593,7 @@ public void shouldValidateQueryParameter_outENUM() { rule.setInput("{#request.params['my-param']}"); Constraint constraint = new Constraint(); constraint.setType(ConstraintType.ENUM); - constraint.setParameters(new String []{"One", "Two"}); + constraint.setParameters(new String[] { "One", "Two" }); rule.setConstraint(constraint); when(configuration.getRules()).thenReturn(Arrays.asList(rule)); @@ -624,5 +604,4 @@ public void shouldValidateQueryParameter_outENUM() { // Check results verify(policyChain).failWith(argThat(result -> result.statusCode() == HttpStatusCode.BAD_REQUEST_400)); } - } diff --git a/src/test/java/io/gravitee/policy/requestvalidation/validator/DateFormatConstraintValidatorTest.java b/src/test/java/io/gravitee/policy/requestvalidation/validator/DateFormatConstraintValidatorTest.java index 4cef7ef..34059ed 100644 --- a/src/test/java/io/gravitee/policy/requestvalidation/validator/DateFormatConstraintValidatorTest.java +++ b/src/test/java/io/gravitee/policy/requestvalidation/validator/DateFormatConstraintValidatorTest.java @@ -23,7 +23,7 @@ * @author GraviteeSource Team */ public class DateFormatConstraintValidatorTest { - + @Test public void shouldNotValidate_nullValue() { DateFormatConstraintValidator validator = new DateFormatConstraintValidator(); @@ -35,7 +35,7 @@ public void shouldNotValidate_nullValue() { @Test public void shouldNotValidate_doesNotRespectPattern() { DateFormatConstraintValidator validator = new DateFormatConstraintValidator(); - validator.initialize("dd/MM/yyyy"); + validator.initialize("dd/MM/yyyy"); boolean valid = validator.isValid("31/20/19991"); Assert.assertFalse(valid); } @@ -43,7 +43,7 @@ public void shouldNotValidate_doesNotRespectPattern() { @Test public void shouldValidate_simpleFormat() { DateFormatConstraintValidator validator = new DateFormatConstraintValidator(); - validator.initialize("dd/MM/yyyy"); + validator.initialize("dd/MM/yyyy"); boolean valid = validator.isValid("29/02/2012"); Assert.assertTrue(valid); } diff --git a/src/test/java/io/gravitee/policy/requestvalidation/validator/EnumConstraintValidatorTest.java b/src/test/java/io/gravitee/policy/requestvalidation/validator/EnumConstraintValidatorTest.java index 984a783..079af99 100644 --- a/src/test/java/io/gravitee/policy/requestvalidation/validator/EnumConstraintValidatorTest.java +++ b/src/test/java/io/gravitee/policy/requestvalidation/validator/EnumConstraintValidatorTest.java @@ -34,5 +34,4 @@ public void test() { result = enumConstraintValidator.isValid("Three"); Assert.assertFalse(result); } - } diff --git a/src/test/java/io/gravitee/policy/requestvalidation/validator/PatternConstraintValidatorTest.java b/src/test/java/io/gravitee/policy/requestvalidation/validator/PatternConstraintValidatorTest.java index 7d114b8..55454a2 100644 --- a/src/test/java/io/gravitee/policy/requestvalidation/validator/PatternConstraintValidatorTest.java +++ b/src/test/java/io/gravitee/policy/requestvalidation/validator/PatternConstraintValidatorTest.java @@ -24,8 +24,8 @@ */ public class PatternConstraintValidatorTest { - String pattern = "^test$"; - + String pattern = "^test$"; + @Test public void shouldNotValidate_nullValue() { PatternConstraintValidator validator = new PatternConstraintValidator(); @@ -36,18 +36,17 @@ public void shouldNotValidate_nullValue() { @Test public void shouldNotValidate_doesNotRespectPattern() { - PatternConstraintValidator validator = new PatternConstraintValidator(); - validator.initialize(pattern); + PatternConstraintValidator validator = new PatternConstraintValidator(); + validator.initialize(pattern); boolean valid = validator.isValid(""); Assert.assertFalse(valid); } @Test public void shouldValidate() { - PatternConstraintValidator validator = new PatternConstraintValidator(); - validator.initialize(pattern); + PatternConstraintValidator validator = new PatternConstraintValidator(); + validator.initialize(pattern); boolean valid = validator.isValid("test"); Assert.assertTrue(valid); } - }