Skip to content

Commit

Permalink
create @bytesize validator #761
Browse files Browse the repository at this point in the history
(cherry picked from commit e3e85c0)
  • Loading branch information
yoshikawaa committed Mar 20, 2019
1 parent 15db52c commit b470004
Show file tree
Hide file tree
Showing 12 changed files with 697 additions and 45 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
Expand All @@ -37,18 +36,23 @@
* The annotated element must be a {@link CharSequence}({@link String}, {@link StringBuilder}, etc ...) whose byte length must
* be lower or equal to the specified maximum.
* <p>
* If you want to specify not only a maximum length but also a minimum length, it is recommended to use {@link ByteSize}.
* </p>
* <p>
* Supported types are:
* </p>
* <ul>
* <li>{@code String}</li>
* <li>{@code CharSequence}</li>
* </ul>
* <p>
* {@code null} elements are considered valid. Determine the byte length By encoding the string in the specified
* {@link ByteMax#charset()}. If not specify, encode with charset {@code "UTF-8"}. If specify a charset that can not be used, it
* is thrown {@link IllegalArgumentException}(wrapped in {@link ValidationException}).
* {@link ByteMax#charset()}. If not specify, encode with charset {@code "UTF-8"}.
* An {@link IllegalArgumentException}(wrapped in {@link ValidationException}) is thrown if specify
* {@link ByteMax#charset()} that can not be used or specify {@link ByteMax#value()} that is negative value.
* </p>
* @since 5.1.0
* @see ByteMaxValidator
* @see ByteSize
*/
@Documented
@Constraint(validatedBy = { ByteMaxValidator.class })
Expand Down Expand Up @@ -90,7 +94,7 @@
* @since 5.1.0
*/
@Documented
@Target({ METHOD, FIELD, TYPE, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@interface List {
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
Expand All @@ -37,18 +36,23 @@
* The annotated element must be a {@link CharSequence}({@link String}, {@link StringBuilder}, etc ...) whose byte length must
* be higher or equal to the specified minimum.
* <p>
* If you want to specify not only a minimum length but also a maximum length, it is recommended to use {@link ByteSize}.
* </p>
* <p>
* Supported types are:
* </p>
* <ul>
* <li>{@code String}</li>
* <li>{@code CharSequence}</li>
* </ul>
* <p>
* {@code null} elements are considered valid. Determine the byte length By encoding the string in the specified
* {@link ByteMin#charset()}. If not specify, encode with charset {@code "UTF-8"}. If specify a charset that can not be used, it
* is thrown {@link IllegalArgumentException}(wrapped in {@link ValidationException}).
* {@link ByteMin#charset()}. If not specify, encode with charset {@code "UTF-8"}.
* An {@link IllegalArgumentException}(wrapped in {@link ValidationException}) is thrown if specify
* {@link ByteMin#charset()} that can not be used or specify {@link ByteMin#value()} that is negative value.
* </p>
* @since 5.1.0
* @see ByteMinValidator
* @see ByteSize
*/
@Documented
@Constraint(validatedBy = { ByteMinValidator.class })
Expand Down Expand Up @@ -90,7 +94,7 @@
* @since 5.1.0
*/
@Documented
@Target({ METHOD, FIELD, TYPE, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@interface List {
/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/*
* Copyright (C) 2013-2017 NTT DATA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.terasoluna.gfw.common.validator.constraints;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.ValidationException;

import org.terasoluna.gfw.common.validator.constraintvalidators.ByteSizeValidator;

/**
* The annotated element must be a {@link CharSequence}({@link String}, {@link StringBuilder}, etc ...) whose byte length must
* be between the specified minimum and maximum.
* <p>
* This is an annotation combining the functions {@link ByteMin} and {@link ByteMax}. Compared to using two annotations,
* the advantage is that overhead can be reduced by getting byte length at a time.
* </p>
* <p>
* Supported types are:
* </p>
* <ul>
* <li>{@code CharSequence}</li>
* </ul>
* <p>
* {@code null} elements are considered valid. Determine the byte length By encoding the string in the specified
* {@link ByteSize#charset()}. If not specify, encode with charset {@code "UTF-8"}.
* An {@link IllegalArgumentException}(wrapped in {@link ValidationException}) is thrown if specify
* {@link ByteSize#charset()} that can not be used or specify {@link ByteSize#min()} or {@link ByteSize#max()}
* that is negative or specify {@link ByteSize#max()} that lower than {@link ByteSize#min()} value.
* </p>
* @since 5.4.2
* @see ByteSizeValidator
* @see ByteMin
* @see ByteMax
*/
@Documented
@Constraint(validatedBy = { ByteSizeValidator.class })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
public @interface ByteSize {

/**
* Error message or message key
* @return error message or message key
*/
String message() default "{org.terasoluna.gfw.common.validator.constraints.ByteSize.message}";

/**
* Constraint groups
* @return constraint groups
*/
Class<?>[] groups() default {};

/**
* Payload
* @return payload
*/
Class<? extends Payload>[] payload() default {};

/**
* @return value the element's byte length must be higher or equal to
*/
long min() default 0;

/**
* @return value the element's byte length must be lower or equal to
*/
long max() default Long.MAX_VALUE;

/**
* @return the charset name used in parse to a string
*/
String charset() default "UTF-8";

/**
* Defines several {@link ByteSize} annotations on the same element.
* @see ByteSize
* @since 5.4.2
*/
@Documented
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@interface List {
/**
* <code>@ByteSize</code> annotations
* @return annotations
*/
ByteSize[] value();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@
* </ul>
* <p>
* {@code null} elements are considered valid. If any of the specified two properties is {@code null}, are considered valid. If
* specify two properties of different types, are considered invalid. If specify a property not {@link Comparable}, it is thrown
* {@link IllegalArgumentException}(wrapped in {@link ValidationException}).
* specify two properties of different types, are considered invalid.
* An {@link IllegalArgumentException}(wrapped in {@link ValidationException}) is thrown if specify a property not {@link Comparable}.
* </p>
* @since 5.1.0
* @see CompareValidator
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public class ByteMaxValidator implements
/**
* Initialize validator.
* @param constraintAnnotation annotation instance for a given constraint declaration
* @throws IllegalArgumentException failed to get a charset by name.
* @throws IllegalArgumentException failed to get a charset by name, or value is invalid.
* @see javax.validation.ConstraintValidator#initialize(java.lang.annotation.Annotation)
*/
@Override
Expand All @@ -61,6 +61,10 @@ public void initialize(ByteMax constraintAnnotation) {
throw reportFailedToInitialize(e);
}
max = constraintAnnotation.value();
if (max < 0) {
throw reportFailedToInitialize(new IllegalArgumentException("value["
+ max + "] must not be negative value."));
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public class ByteMinValidator implements
/**
* Initialize validator.
* @param constraintAnnotation annotation instance for a given constraint declaration
* @throws IllegalArgumentException failed to get a charset by name.
* @throws IllegalArgumentException failed to get a charset by name, or value is invalid.
* @see javax.validation.ConstraintValidator#initialize(java.lang.annotation.Annotation)
*/
@Override
Expand All @@ -61,6 +61,10 @@ public void initialize(ByteMin constraintAnnotation) {
throw reportFailedToInitialize(e);
}
min = constraintAnnotation.value();
if (min < 0) {
throw reportFailedToInitialize(new IllegalArgumentException("value["
+ min + "] must not be negative value."));
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
* Copyright (C) 2013-2017 NTT DATA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.terasoluna.gfw.common.validator.constraintvalidators;

import static org.terasoluna.gfw.common.validator.constraintvalidators.ConstraintValidatorsUtils.reportFailedToInitialize;

import java.nio.charset.Charset;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.terasoluna.gfw.common.validator.constraints.ByteSize;

/**
* Constraint validator class of {@link ByteSize} annotation.
* <p>
* Validate the {@link CharSequence}({@link String}, {@link StringBuilder}, etc ...) whose byte length must be between the
* specified minimum and maximum. Determine the byte length By encoding the string in the specified charset.
* </p>
* @since 5.4.0
* @see ConstraintValidator
* @see ByteSize
*/
public class ByteSizeValidator implements
ConstraintValidator<ByteSize, CharSequence> {

/**
* The charset used in parse to a string.
*/
private Charset charset;

/**
* Byte length must be higher or equal to.
*/
private long min;

/**
* Byte length must be lower or equal to.
*/
private long max;

/**
* Initialize validator.
* @param constraintAnnotation annotation instance for a given constraint declaration
* @throws IllegalArgumentException failed to get a charset by name, or min and max are invalid.
* @see javax.validation.ConstraintValidator#initialize(java.lang.annotation.Annotation)
*/
@Override
public void initialize(ByteSize constraintAnnotation) {
try {
charset = Charset.forName(constraintAnnotation.charset());
} catch (IllegalArgumentException e) {
throw reportFailedToInitialize(e);
}
min = constraintAnnotation.min();
max = constraintAnnotation.max();
if (min < 0) {
throw reportFailedToInitialize(new IllegalArgumentException("min["
+ min + "] must not be negative value."));
}
if (max < 0) {
throw reportFailedToInitialize(new IllegalArgumentException("max["
+ max + "] must not be negative value."));
}
if (max < min) {
throw reportFailedToInitialize(new IllegalArgumentException("max["
+ max + "] must be higher or equal to min[" + min + "]."));
}
}

/**
* Validate execute.
* @param value object to validate
* @param context context in which the constraint is evaluated
* @return {@code true} if {@code value} length is between the specified minimum and maximum, or null. otherwise {@code false}.
* @see javax.validation.ConstraintValidator#isValid(java.lang.Object, javax.validation.ConstraintValidatorContext)
*/
@Override
public boolean isValid(CharSequence value,
ConstraintValidatorContext context) {
if (value == null) {
return true;
}

long byteLength = value.toString().getBytes(charset).length;
return min <= byteLength && byteLength <= max;
}
}
Loading

0 comments on commit b470004

Please sign in to comment.