Skip to content

Commit

Permalink
create @bytesize validator #761
Browse files Browse the repository at this point in the history
  • Loading branch information
yoshikawaa committed Oct 19, 2017
1 parent 0f4c27a commit 545070a
Show file tree
Hide file tree
Showing 5 changed files with 526 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/*
* 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.ElementType.TYPE;
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>
* Supported types are:
* </p>
* <ul>
* <li>{@code String}</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"}. If specify a charset that can not be used, it
* is thrown {@link IllegalArgumentException}(wrapped in {@link ValidationException}).
* </p>
* @since 5.1.0
* @see ByteSizeValidator
*/
@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();

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

/**
* @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.1.0
*/
@Documented
@Target({ METHOD, FIELD, TYPE, 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
@@ -0,0 +1,93 @@
/*
* 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.1.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 max is lower than min.
* @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 (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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,20 @@ protected void setExpectedFailedToInitialize(Class<?> cls) {
}

/**
* set {@code ExpectedException} for failed to initialize.
* @param cls expected inner exception.
* @param message expected message of inner exception.
*/
protected void setExpectedFailedToInitialize(Class<?> cls, String message) {
thrown.expect(ValidationException.class);
thrown.expectCause(allOf(Matchers.<Throwable> instanceOf(
IllegalArgumentException.class), hasProperty("message", is(
MESSAGE_INITIALIZE_ERROR)), hasProperty("cause", allOf(
Matchers.<Throwable> instanceOf(cls),
hasProperty("message", is(message))))));
}

/**
* set {@code ExpectedException} for type not support.
* @param cls expected not support type.
*/
Expand Down
Loading

0 comments on commit 545070a

Please sign in to comment.