Hibernate SVN: r16031 - in validator/trunk/hibernate-validator/src: main/java/org/hibernate/validation/engine and 11 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-02-25 08:09:51 -0500 (Wed, 25 Feb 2009)
New Revision: 16031
Added:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintHelper.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ConstraintHelperTest.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/Car.java
Removed:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/constraints/Pattern.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/constraints/Patterns.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BuiltinConstraints.java
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/constraints/PatternValidator.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaData.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintDescriptorImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorContextImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorFactoryImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/groups/Group.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/ReflectionHelper.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/annotationfactory/AnnotationProxy.java
validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation/ValidationMessages.properties
validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation/ValidationMessages_de.properties
validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation/ValidationMessages_fr.properties
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/PatternValidatorTest.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/composition/FrenchZipcode.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/eg/Engine.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolatorTest.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/GroupTest.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/User.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/ReflectionHelperTest.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/annotationfactory/AnnotationFactoryTest.java
Log:
HV-113 Implemented redefining of default group for validate, validateValue and validateProperty
HV-121 Added support for javax.validation.Pattern and removed obsolete classes
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/constraints/Pattern.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/constraints/Pattern.java 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/constraints/Pattern.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -1,50 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* 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.hibernate.validation.constraints;
-
-import java.lang.annotation.Documented;
-import static java.lang.annotation.ElementType.FIELD;
-import static java.lang.annotation.ElementType.METHOD;
-import java.lang.annotation.Retention;
-import static java.lang.annotation.RetentionPolicy.RUNTIME;
-import java.lang.annotation.Target;
-import javax.validation.Constraint;
-
-/**
- * @author Hardy Ferentschik
- */
-@Documented
-@Constraint(validatedBy = PatternValidator.class)
-@Target({ METHOD, FIELD })
-@Retention(RUNTIME)
-public @interface Pattern {
- String message() default "{validator.pattern}";
-
- Class<?>[] groups() default { };
-
- /**
- * @return the regular expression the annotated string must match.
- */
- String regex();
-
- /**
- * @return Additioanl regular expression processing flags. Default is 0.
- */
- int flags() default 0;
-}
-
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/constraints/PatternValidator.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/constraints/PatternValidator.java 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/constraints/PatternValidator.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -20,6 +20,7 @@
import java.util.regex.Matcher;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
+import javax.validation.constraints.Pattern;
/**
* @author Hardy Ferentschik
@@ -29,10 +30,17 @@
private java.util.regex.Pattern pattern;
public void initialize(Pattern parameters) {
- pattern = java.util.regex.Pattern.compile(
- parameters.regex(),
- parameters.flags()
- );
+ Pattern.Flag flags[] = parameters.flags();
+ if ( flags.length == 0 ) {
+ pattern = java.util.regex.Pattern.compile( parameters.regexp() );
+ }
+ else {
+ int intFlag = 0;
+ for ( Pattern.Flag flag : flags ) {
+ intFlag = intFlag | mapFlagToInt( flag );
+ }
+ pattern = java.util.regex.Pattern.compile( parameters.regexp(), intFlag );
+ }
}
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
@@ -42,4 +50,39 @@
Matcher m = pattern.matcher( value );
return m.matches();
}
+
+ private int mapFlagToInt(Pattern.Flag flag) {
+ int intFlag = 0;
+ switch ( flag ) {
+ case UNIX_LINES: {
+ intFlag = java.util.regex.Pattern.UNIX_LINES;
+ break;
+ }
+ case CASE_INSENSITIVE: {
+ intFlag = java.util.regex.Pattern.CASE_INSENSITIVE;
+ break;
+ }
+ case COMMENTS: {
+ intFlag = java.util.regex.Pattern.COMMENTS;
+ break;
+ }
+ case MULTILINE: {
+ intFlag = java.util.regex.Pattern.MULTILINE;
+ break;
+ }
+ case DOTALL: {
+ intFlag = java.util.regex.Pattern.DOTALL;
+ break;
+ }
+ case UNICODE_CASE: {
+ intFlag = java.util.regex.Pattern.UNICODE_CASE;
+ break;
+ }
+ case CANON_EQ: {
+ intFlag = java.util.regex.Pattern.CANON_EQ;
+ break;
+ }
+ }
+ return intFlag;
+ }
}
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/constraints/Patterns.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/constraints/Patterns.java 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/constraints/Patterns.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -1,36 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* 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.hibernate.validation.constraints;
-
-import java.lang.annotation.Documented;
-import static java.lang.annotation.ElementType.FIELD;
-import static java.lang.annotation.ElementType.METHOD;
-import static java.lang.annotation.ElementType.TYPE;
-import java.lang.annotation.Retention;
-import static java.lang.annotation.RetentionPolicy.RUNTIME;
-import java.lang.annotation.Target;
-
-/**
- * @author Hardy Ferentschik
- */
-@Documented
-@Target({ METHOD, FIELD, TYPE })
-@Retention(RUNTIME)
-public @interface Patterns {
- Pattern[] value();
-}
\ No newline at end of file
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaData.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaData.java 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaData.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -67,7 +67,7 @@
* @return A list of <code>MetaConstraint</code> instances encapsulating the information of all the constraints
* defined on the bean.
*/
- List<MetaConstraint> geMetaConstraintList();
+ List<MetaConstraint<T>> geMetaConstraintList();
/**
* @return A map keying the property name of a constraint to its <code>ElementDescriptor</code>.
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataImpl.java 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataImpl.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -63,7 +63,7 @@
/**
* List of constraints.
*/
- private List<MetaConstraint> metaConstraintList = new ArrayList<MetaConstraint>();
+ private List<MetaConstraint<T>> metaConstraintList = new ArrayList<MetaConstraint<T>>();
/**
* List of cascaded fields.
@@ -85,11 +85,14 @@
*/
private List<Class<?>> defaultGroupSequence = new ArrayList<Class<?>>();
- private final BuiltinConstraints builtinConstraints;
+ /**
+ * Object keeping track of all builtin constraints.
+ */
+ private final ConstraintHelper constraintHelper;
- public BeanMetaDataImpl(Class<T> beanClass, BuiltinConstraints builtinConstraints) {
+ public BeanMetaDataImpl(Class<T> beanClass, ConstraintHelper constraintHelper) {
this.beanClass = beanClass;
- this.builtinConstraints = builtinConstraints;
+ this.constraintHelper = constraintHelper;
createMetaData();
}
@@ -173,7 +176,7 @@
List<ConstraintDescriptorImpl> fieldMetadata = findFieldLevelConstraints( field );
for ( ConstraintDescriptorImpl constraintDescription : fieldMetadata ) {
ReflectionHelper.setAccessibility( field );
- MetaConstraint metaConstraint = new MetaConstraint( field, constraintDescription );
+ MetaConstraint<T> metaConstraint = new MetaConstraint<T>( field, beanClass, constraintDescription );
metaConstraintList.add( metaConstraint );
}
if ( field.isAnnotationPresent( Valid.class ) ) {
@@ -188,7 +191,7 @@
List<ConstraintDescriptorImpl> methodMetadata = findMethodLevelConstraints( method );
for ( ConstraintDescriptorImpl constraintDescription : methodMetadata ) {
ReflectionHelper.setAccessibility( method );
- MetaConstraint metaConstraint = new MetaConstraint( method, constraintDescription );
+ MetaConstraint<T> metaConstraint = new MetaConstraint<T>( method, beanClass, constraintDescription );
metaConstraintList.add( metaConstraint );
}
if ( method.isAnnotationPresent( Valid.class ) ) {
@@ -201,7 +204,7 @@
private void initClassConstraints(Class clazz) {
List<ConstraintDescriptorImpl> classMetadata = findClassLevelConstraints( clazz );
for ( ConstraintDescriptorImpl constraintDescription : classMetadata ) {
- MetaConstraint metaConstraint = new MetaConstraint( clazz, constraintDescription );
+ MetaConstraint<T> metaConstraint = new MetaConstraint<T>( clazz, constraintDescription );
metaConstraintList.add( metaConstraint );
}
}
@@ -218,13 +221,13 @@
List<ConstraintDescriptorImpl> constraintDescriptors = new ArrayList<ConstraintDescriptorImpl>();
List<Annotation> constraints = new ArrayList<Annotation>();
- if ( ReflectionHelper.isConstraintAnnotation( annotation ) ||
- ReflectionHelper.isBuiltInConstraintAnnotation( annotation ) ) {
+ if ( constraintHelper.isConstraintAnnotation( annotation ) ||
+ constraintHelper.isBuiltinConstraint( annotation ) ) {
constraints.add( annotation );
}
// check if we have a multi value constraint
- constraints.addAll( ReflectionHelper.getMultiValueConstraints( annotation ) );
+ constraints.addAll( constraintHelper.getMultiValueConstraints( annotation ) );
for ( Annotation constraint : constraints ) {
final ConstraintDescriptorImpl constraintDescriptor = buildConstraintDescriptor( constraint );
@@ -236,7 +239,7 @@
@SuppressWarnings("unchecked")
private <A extends Annotation> ConstraintDescriptorImpl buildConstraintDescriptor(A annotation) {
Class<?>[] groups = ReflectionHelper.getAnnotationParameter( annotation, "groups", Class[].class );
- return new ConstraintDescriptorImpl( annotation, groups, builtinConstraints );
+ return new ConstraintDescriptorImpl( annotation, groups, constraintHelper );
}
/**
@@ -346,7 +349,7 @@
return cascadedMembers;
}
- public List<MetaConstraint> geMetaConstraintList() {
+ public List<MetaConstraint<T>> geMetaConstraintList() {
return metaConstraintList;
}
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BuiltinConstraints.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BuiltinConstraints.java 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BuiltinConstraints.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -1,129 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* 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.hibernate.validation.engine;
-
-import java.lang.annotation.Annotation;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import javax.validation.ConstraintValidator;
-import javax.validation.ValidationException;
-import javax.validation.constraints.AssertFalse;
-import javax.validation.constraints.AssertTrue;
-import javax.validation.constraints.Digits;
-import javax.validation.constraints.Future;
-import javax.validation.constraints.Max;
-import javax.validation.constraints.Min;
-import javax.validation.constraints.NotNull;
-import javax.validation.constraints.Null;
-import javax.validation.constraints.Size;
-import javax.validation.constraints.Past;
-
-import org.hibernate.validation.constraints.AssertFalseValidator;
-import org.hibernate.validation.constraints.AssertTrueValidator;
-import org.hibernate.validation.constraints.DigitsValidatorForNumber;
-import org.hibernate.validation.constraints.DigitsValidatorForString;
-import org.hibernate.validation.constraints.FutureValidatorForCalendar;
-import org.hibernate.validation.constraints.FutureValidatorForDate;
-import org.hibernate.validation.constraints.MaxValidatorForNumber;
-import org.hibernate.validation.constraints.MaxValidatorForString;
-import org.hibernate.validation.constraints.MinValidatorForNumber;
-import org.hibernate.validation.constraints.MinValidatorForString;
-import org.hibernate.validation.constraints.NotNullValidator;
-import org.hibernate.validation.constraints.NullValidator;
-import org.hibernate.validation.constraints.PastValidatorForCalendar;
-import org.hibernate.validation.constraints.PastValidatorForDate;
-import org.hibernate.validation.constraints.SizeValidatorForString;
-import org.hibernate.validation.constraints.SizeValidatorForCollection;
-import org.hibernate.validation.constraints.SizeValidatorForArray;
-import org.hibernate.validation.constraints.SizeValidatorForMap;
-
-/**
- * @author Hardy Ferentschik
- * @author Alaa Nassef
- */
-public class BuiltinConstraints {
-
- private final Map<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<?, ?>>>> builtinConstraints =
- new HashMap<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<?, ?>>>>();
-
- public BuiltinConstraints() {
-
- List<Class<? extends ConstraintValidator<?, ?>>> constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
- constraintList.add( AssertFalseValidator.class );
- builtinConstraints.put( AssertFalse.class, constraintList );
-
- constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
- constraintList.add( AssertTrueValidator.class );
- builtinConstraints.put( AssertTrue.class, constraintList );
-
- constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
- constraintList.add( FutureValidatorForCalendar.class );
- constraintList.add( FutureValidatorForDate.class );
- builtinConstraints.put( Future.class, constraintList );
-
- constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
- constraintList.add( MaxValidatorForNumber.class );
- constraintList.add( MaxValidatorForString.class );
- builtinConstraints.put( Max.class, constraintList );
-
- constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
- constraintList.add( MinValidatorForNumber.class );
- constraintList.add( MinValidatorForString.class );
- builtinConstraints.put( Min.class, constraintList );
-
- constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
- constraintList.add( NotNullValidator.class );
- builtinConstraints.put( NotNull.class, constraintList );
-
- constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
- constraintList.add( NullValidator.class );
- builtinConstraints.put( Null.class, constraintList );
-
- constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
- constraintList.add( PastValidatorForCalendar.class );
- constraintList.add( PastValidatorForDate.class );
- builtinConstraints.put( Past.class, constraintList );
-
- constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
- constraintList.add( DigitsValidatorForString.class );
- constraintList.add( DigitsValidatorForNumber.class );
- builtinConstraints.put( Digits.class, constraintList );
-
- constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
- constraintList.add( SizeValidatorForString.class );
- constraintList.add( SizeValidatorForCollection.class );
- constraintList.add( SizeValidatorForArray.class );
- constraintList.add( SizeValidatorForMap.class );
- builtinConstraints.put( Size.class, constraintList );
-
-
- }
-
- public List<Class<? extends ConstraintValidator<?, ?>>> getBuiltInConstraints(Annotation annotation) {
- List<Class<? extends ConstraintValidator<?, ?>>> constraints = builtinConstraints.get( annotation.annotationType() );
-
- if ( constraints == null ) {
- throw new ValidationException( "Unable to find constraints for " + annotation.annotationType() );
- }
-
- return constraints;
- }
-
-}
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintDescriptorImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintDescriptorImpl.java 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintDescriptorImpl.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -40,7 +40,6 @@
import org.slf4j.Logger;
import org.hibernate.validation.util.LoggerFactory;
-import org.hibernate.validation.util.ReflectionHelper;
import org.hibernate.validation.util.annotationfactory.AnnotationDescriptor;
import org.hibernate.validation.util.annotationfactory.AnnotationFactory;
@@ -95,21 +94,21 @@
/**
* Handle to the builtin constraint implementations.
*/
- private final BuiltinConstraints builtinConstraints;
+ private final ConstraintHelper constraintHelper;
- public ConstraintDescriptorImpl(U annotation, Class<?>[] groups, BuiltinConstraints builtinConstraints) {
- this( annotation, new HashSet<Class<?>>(), builtinConstraints );
+ public ConstraintDescriptorImpl(U annotation, Class<?>[] groups, ConstraintHelper constraintHelper) {
+ this( annotation, new HashSet<Class<?>>(), constraintHelper );
if ( groups.length == 0 ) {
groups = DEFAULT_GROUP;
}
this.groups.addAll( Arrays.asList( groups ) );
}
- public ConstraintDescriptorImpl(U annotation, Set<Class<?>> groups, BuiltinConstraints builtinConstraints) {
+ public ConstraintDescriptorImpl(U annotation, Set<Class<?>> groups, ConstraintHelper constraintHelper) {
this.annotation = annotation;
this.groups = groups;
this.parameters = getAnnotationParameters( annotation );
- this.builtinConstraints = builtinConstraints;
+ this.constraintHelper = constraintHelper;
this.isReportAsSingleInvalidConstraint = annotation.annotationType().isAnnotationPresent(
ReportAsSingleViolation.class
@@ -122,8 +121,8 @@
}
private void findConstraintClasses() {
- if ( ReflectionHelper.isBuiltInConstraintAnnotation( annotation ) ) {
- constraintClasses.addAll( builtinConstraints.getBuiltInConstraints( annotation ) );
+ if ( constraintHelper.isBuiltinConstraint( annotation ) ) {
+ constraintClasses.addAll( constraintHelper.getBuiltInConstraints( annotation ) );
}
else {
Constraint constraint = annotation.annotationType().getAnnotation( Constraint.class );
@@ -248,9 +247,8 @@
private void parseComposingConstraints() {
for ( Annotation declaredAnnotation : annotation.annotationType().getDeclaredAnnotations() ) {
- if ( ReflectionHelper.isConstraintAnnotation( declaredAnnotation ) || ReflectionHelper.isBuiltInConstraintAnnotation(
- declaredAnnotation
- ) ) {
+ if ( constraintHelper.isConstraintAnnotation( declaredAnnotation )
+ || constraintHelper.isBuiltinConstraint( declaredAnnotation ) ) {
ConstraintDescriptorImpl descriptor = createComposingConstraintDescriptor(
OVERRIDES_PARAMETER_DEFAULT_INDEX,
declaredAnnotation
@@ -258,8 +256,8 @@
composingConstraints.add( descriptor );
log.debug( "Adding composing constraint: " + descriptor );
}
- else if ( ReflectionHelper.isMultiValueConstraint( declaredAnnotation ) ) {
- List<Annotation> multiValueConstraints = ReflectionHelper.getMultiValueConstraints( declaredAnnotation );
+ else if ( constraintHelper.isMultiValueConstraint( declaredAnnotation ) ) {
+ List<Annotation> multiValueConstraints = constraintHelper.getMultiValueConstraints( declaredAnnotation );
int index = 1;
for ( Annotation constraintAnnotation : multiValueConstraints ) {
ConstraintDescriptorImpl descriptor = createComposingConstraintDescriptor(
@@ -288,7 +286,7 @@
}
}
Annotation annotationProxy = AnnotationFactory.create( annotationDescriptor );
- return new ConstraintDescriptorImpl( annotationProxy, groups, builtinConstraints );
+ return new ConstraintDescriptorImpl( annotationProxy, groups, constraintHelper );
}
private class ClassIndexWrapper {
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintHelper.java (from rev 16028, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BuiltinConstraints.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintHelper.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintHelper.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -0,0 +1,272 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* 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.hibernate.validation.engine;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.validation.Constraint;
+import javax.validation.ConstraintValidator;
+import javax.validation.ValidationException;
+import javax.validation.constraints.AssertFalse;
+import javax.validation.constraints.AssertTrue;
+import javax.validation.constraints.Digits;
+import javax.validation.constraints.Future;
+import javax.validation.constraints.Max;
+import javax.validation.constraints.Min;
+import javax.validation.constraints.NotNull;
+import javax.validation.constraints.Null;
+import javax.validation.constraints.Past;
+import javax.validation.constraints.Pattern;
+import javax.validation.constraints.Size;
+
+import org.slf4j.Logger;
+
+import org.hibernate.validation.constraints.AssertFalseValidator;
+import org.hibernate.validation.constraints.AssertTrueValidator;
+import org.hibernate.validation.constraints.DigitsValidatorForNumber;
+import org.hibernate.validation.constraints.DigitsValidatorForString;
+import org.hibernate.validation.constraints.FutureValidatorForCalendar;
+import org.hibernate.validation.constraints.FutureValidatorForDate;
+import org.hibernate.validation.constraints.MaxValidatorForNumber;
+import org.hibernate.validation.constraints.MaxValidatorForString;
+import org.hibernate.validation.constraints.MinValidatorForNumber;
+import org.hibernate.validation.constraints.MinValidatorForString;
+import org.hibernate.validation.constraints.NotNullValidator;
+import org.hibernate.validation.constraints.NullValidator;
+import org.hibernate.validation.constraints.PastValidatorForCalendar;
+import org.hibernate.validation.constraints.PastValidatorForDate;
+import org.hibernate.validation.constraints.PatternValidator;
+import org.hibernate.validation.constraints.SizeValidatorForArray;
+import org.hibernate.validation.constraints.SizeValidatorForCollection;
+import org.hibernate.validation.constraints.SizeValidatorForMap;
+import org.hibernate.validation.constraints.SizeValidatorForString;
+import org.hibernate.validation.util.LoggerFactory;
+import org.hibernate.validation.util.ReflectionHelper;
+
+/**
+ * Keeps track of builtin constraints and their validator implementations.
+ *
+ * @author Hardy Ferentschik
+ * @author Alaa Nassef
+ */
+public class ConstraintHelper {
+
+ private static final Logger log = LoggerFactory.make();
+
+ private final Map<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<?, ?>>>> builtinConstraints =
+ new HashMap<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<?, ?>>>>();
+
+ public ConstraintHelper() {
+
+ List<Class<? extends ConstraintValidator<?, ?>>> constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
+ constraintList.add( AssertFalseValidator.class );
+ builtinConstraints.put( AssertFalse.class, constraintList );
+
+ constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
+ constraintList.add( AssertTrueValidator.class );
+ builtinConstraints.put( AssertTrue.class, constraintList );
+
+ constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
+ constraintList.add( FutureValidatorForCalendar.class );
+ constraintList.add( FutureValidatorForDate.class );
+ builtinConstraints.put( Future.class, constraintList );
+
+ constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
+ constraintList.add( MaxValidatorForNumber.class );
+ constraintList.add( MaxValidatorForString.class );
+ builtinConstraints.put( Max.class, constraintList );
+
+ constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
+ constraintList.add( MinValidatorForNumber.class );
+ constraintList.add( MinValidatorForString.class );
+ builtinConstraints.put( Min.class, constraintList );
+
+ constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
+ constraintList.add( NotNullValidator.class );
+ builtinConstraints.put( NotNull.class, constraintList );
+
+ constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
+ constraintList.add( NullValidator.class );
+ builtinConstraints.put( Null.class, constraintList );
+
+ constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
+ constraintList.add( PastValidatorForCalendar.class );
+ constraintList.add( PastValidatorForDate.class );
+ builtinConstraints.put( Past.class, constraintList );
+
+ constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
+ constraintList.add( DigitsValidatorForString.class );
+ constraintList.add( DigitsValidatorForNumber.class );
+ builtinConstraints.put( Digits.class, constraintList );
+
+ constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
+ constraintList.add( SizeValidatorForString.class );
+ constraintList.add( SizeValidatorForCollection.class );
+ constraintList.add( SizeValidatorForArray.class );
+ constraintList.add( SizeValidatorForMap.class );
+ builtinConstraints.put( Size.class, constraintList );
+
+ constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
+ constraintList.add( PatternValidator.class );
+ builtinConstraints.put( Pattern.class, constraintList );
+ }
+
+ public List<Class<? extends ConstraintValidator<?, ?>>> getBuiltInConstraints(Annotation annotation) {
+ List<Class<? extends ConstraintValidator<?, ?>>> constraints = builtinConstraints.get( annotation.annotationType() );
+
+ if ( constraints == null ) {
+ throw new ValidationException( "Unable to find constraints for " + annotation.annotationType() );
+ }
+
+ return constraints;
+ }
+
+ public boolean isBuiltinConstraint(Annotation annotation) {
+ return builtinConstraints.containsKey( annotation.annotationType() );
+ }
+
+ /**
+ * Checks whether a given annotation is a multi value constraint or not.
+ *
+ * @param annotation the annotation to check.
+ *
+ * @return <code>true</code> if the specified annotation is a multi value constraints, <code>false</code>
+ * otherwise.
+ */
+ public boolean isMultiValueConstraint(Annotation annotation) {
+ boolean isMultiValueConstraint = false;
+ try {
+ Method m = annotation.getClass().getMethod( "value" );
+ Class returnType = m.getReturnType();
+ if ( returnType.isArray() && returnType.getComponentType().isAnnotation() ) {
+ Annotation[] annotations = ( Annotation[] ) m.invoke( annotation );
+ for ( Annotation a : annotations ) {
+ if ( isConstraintAnnotation( a ) || isBuiltinConstraint( a ) ) {
+ isMultiValueConstraint = true;
+ }
+ else {
+ isMultiValueConstraint = false;
+ break;
+ }
+ }
+ }
+ }
+ catch ( NoSuchMethodException nsme ) {
+ // ignore
+ }
+ catch ( IllegalAccessException iae ) {
+ // ignore
+ }
+ catch ( InvocationTargetException ite ) {
+ // ignore
+ }
+ return isMultiValueConstraint;
+ }
+
+
+ /**
+ * Checks whether a given annotation is a multi value constraint and returns the contained constraints if so.
+ *
+ * @param annotation the annotation to check.
+ *
+ * @return A list of constraint annotations or the empty list if <code>annotation</code> is not a multi constraint
+ * annotation.
+ */
+ public <A extends Annotation> List<Annotation> getMultiValueConstraints(A annotation) {
+ List<Annotation> annotationList = new ArrayList<Annotation>();
+ try {
+ Method m = annotation.getClass().getMethod( "value" );
+ Class returnType = m.getReturnType();
+ if ( returnType.isArray() && returnType.getComponentType().isAnnotation() ) {
+ Annotation[] annotations = ( Annotation[] ) m.invoke( annotation );
+ for ( Annotation a : annotations ) {
+ if ( isConstraintAnnotation( a ) || isBuiltinConstraint( a ) ) {
+ annotationList.add( a );
+ }
+ }
+ }
+ }
+ catch ( NoSuchMethodException nsme ) {
+ // ignore
+ }
+ catch ( IllegalAccessException iae ) {
+ // ignore
+ }
+ catch ( InvocationTargetException ite ) {
+ // ignore
+ }
+ return annotationList;
+ }
+
+ /**
+ * Checks whehter the specified annotation is a valid constraint annotation. A constraint annotations has to
+ * fulfill the following conditions:
+ * <ul>
+ * <li>Has to contain a <code>ConstraintValidator</code> implementation.</li>
+ * <li>Defines a message parameter.</li>
+ * <li>Defines a group parameter.</li>
+ * </ul>
+ *
+ * @param annotation The annotation to test.
+ *
+ * @return <code>true</code> if the annotation fulfills the above condtions, <code>false</code> otherwise.
+ */
+ public boolean isConstraintAnnotation(Annotation annotation) {
+
+ Constraint constraint = annotation.annotationType()
+ .getAnnotation( Constraint.class );
+ if ( constraint == null ) {
+ return false;
+ }
+
+ try {
+ ReflectionHelper.getAnnotationParameter( annotation, "message", String.class );
+ }
+ catch ( Exception e ) {
+ String msg = annotation.annotationType().getName() + " contains Constraint annotation, but does " +
+ "not contain a message parameter. Annotation is getting ignored.";
+ log.warn( msg );
+ return false;
+ }
+
+ try {
+ ReflectionHelper.getAnnotationParameter( annotation, "groups", Class[].class );
+ }
+ catch ( Exception e ) {
+ String msg = annotation.annotationType().getName() + " contains Constraint annotation, but does " +
+ "not contain a groups parameter. Annotation is getting ignored.";
+ log.warn( msg );
+ return false;
+ }
+
+ Method[] methods = annotation.getClass().getMethods();
+ for ( Method m : methods ) {
+ if ( m.getName().startsWith( "valid" ) ) {
+ String msg = "Parameters starting with 'valid' are not allowed in a constraint.";
+ log.warn( msg );
+ return false;
+ }
+ }
+ return true;
+ }
+}
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintHelper.java
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -35,7 +35,7 @@
*
* @author Hardy Ferentschik
*/
-public class MetaConstraint {
+public class MetaConstraint<T> {
/**
* The constraint tree created from the constraint annotation.
@@ -71,31 +71,38 @@
*/
private final ElementType elementType;
+ /**
+ * The class of the bean hosting this constraint.
+ */
+ private final Class<T> beanClass;
+
public MetaConstraint(Type t, ConstraintDescriptor constraintDescriptor) {
- this( t, null, null, ElementType.TYPE, constraintDescriptor, "" );
+ this( t, null, null, ElementType.TYPE, (Class<T>) t.getClass(), constraintDescriptor, "" );
}
- public MetaConstraint(Method m, ConstraintDescriptor constraintDescriptor) {
+ public MetaConstraint(Method m, Class<T> beanClass, ConstraintDescriptor constraintDescriptor) {
this(
null,
m,
null,
ElementType.METHOD,
+ beanClass,
constraintDescriptor,
ReflectionHelper.getPropertyName( m )
);
}
- public MetaConstraint(Field f, ConstraintDescriptor constraintDescriptor) {
- this( null, null, f, ElementType.FIELD, constraintDescriptor, f.getName());
+ public MetaConstraint(Field f, Class<T> beanClass, ConstraintDescriptor constraintDescriptor) {
+ this( null, null, f, ElementType.FIELD, beanClass, constraintDescriptor, f.getName());
}
- private MetaConstraint(Type t, Method m, Field f, ElementType elementType, ConstraintDescriptor constraintDescriptor, String property) {
+ private MetaConstraint(Type t, Method m, Field f, ElementType elementType, Class<T> beanClass, ConstraintDescriptor constraintDescriptor, String property) {
this.type = t;
this.method = m;
this.field = f;
this.elementType = elementType;
this.propertyName = property;
+ this.beanClass = beanClass;
constraintTree = new ConstraintTree( constraintDescriptor );
}
@@ -167,6 +174,10 @@
return type;
}
+ public Class<T> getBeanClass() {
+ return beanClass;
+ }
+
public String getPropertyName() {
return propertyName;
}
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorContextImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorContextImpl.java 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorContextImpl.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -15,16 +15,16 @@
private final MessageInterpolator factoryMessageInterpolator;
private final TraversableResolver factoryTraversableResolver;
private final ConstraintValidatorFactory constraintValidatorFactory;
- private final BuiltinConstraints builtinConstraints;
+ private final ConstraintHelper constraintHelper;
public ValidatorContextImpl(ConstraintValidatorFactory constraintValidatorFactory,
MessageInterpolator factoryMessageInterpolator,
TraversableResolver factoryTraversableResolver,
- BuiltinConstraints builtinConstraints) {
+ ConstraintHelper constraintHelper) {
this.constraintValidatorFactory = constraintValidatorFactory;
this.factoryMessageInterpolator = factoryMessageInterpolator;
this.factoryTraversableResolver = factoryTraversableResolver;
- this.builtinConstraints = builtinConstraints;
+ this.constraintHelper = constraintHelper;
messageInterpolator( factoryMessageInterpolator );
traversableResolver( factoryTraversableResolver );
}
@@ -50,6 +50,6 @@
}
public Validator getValidator() {
- return new ValidatorImpl( constraintValidatorFactory, messageInterpolator, builtinConstraints );
+ return new ValidatorImpl( constraintValidatorFactory, messageInterpolator, constraintHelper );
}
}
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorFactoryImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorFactoryImpl.java 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorFactoryImpl.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -34,7 +34,7 @@
private final MessageInterpolator messageInterpolator;
private final TraversableResolver traversableResolver;
private final ConstraintValidatorFactory constraintValidatorFactory;
- private final BuiltinConstraints builtinConstraints = new BuiltinConstraints();
+ private final ConstraintHelper constraintHelper = new ConstraintHelper();
public ValidatorFactoryImpl(ConfigurationState configurationState) {
this.messageInterpolator = configurationState.getMessageInterpolator();
@@ -61,6 +61,8 @@
* {@inheritDoc}
*/
public ValidatorContext usingContext() {
- return new ValidatorContextImpl( constraintValidatorFactory, messageInterpolator, traversableResolver, builtinConstraints );
+ return new ValidatorContextImpl( constraintValidatorFactory, messageInterpolator, traversableResolver,
+ constraintHelper
+ );
}
}
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -86,12 +86,12 @@
private final MessageInterpolator messageInterpolator;
- private final BuiltinConstraints builtinConstraints;
+ private final ConstraintHelper constraintHelper;
- public ValidatorImpl(ConstraintValidatorFactory constraintValidatorFactory, MessageInterpolator messageInterpolator, BuiltinConstraints builtinConstraints) {
+ public ValidatorImpl(ConstraintValidatorFactory constraintValidatorFactory, MessageInterpolator messageInterpolator, ConstraintHelper constraintHelper) {
this.constraintValidatorFactory = constraintValidatorFactory;
this.messageInterpolator = messageInterpolator;
- this.builtinConstraints = builtinConstraints;
+ this.constraintHelper = constraintHelper;
groupChainGenerator = new GroupChainGenerator();
}
@@ -103,15 +103,13 @@
if ( object == null ) {
throw new IllegalArgumentException( "Validation of a null object" );
}
+ GroupChain groupChain = determineGroupExecutionOrder( groups );
ExecutionContext<T> context = new ExecutionContext<T>(
object, messageInterpolator, constraintValidatorFactory
);
-
- groups = validateGroupVararg( groups );
-
- List<ConstraintViolationImpl<T>> list = validateInContext( context, Arrays.asList( groups ) );
+ List<ConstraintViolationImpl<T>> list = validateInContext( context, groupChain );
return new HashSet<ConstraintViolation<T>>( list );
}
@@ -119,15 +117,14 @@
* {@inheritDoc}
*/
public <T> Set<ConstraintViolation<T>> validateProperty(T object, String propertyName, Class<?>... groups) {
-
- sanityCheckPropertyPath( propertyName );
-
if ( object == null ) {
throw new IllegalArgumentException( "Validated object cannot be null." );
}
+ sanityCheckPropertyPath( propertyName );
+ GroupChain groupChain = determineGroupExecutionOrder( groups );
List<ConstraintViolationImpl<T>> failingConstraintViolations = new ArrayList<ConstraintViolationImpl<T>>();
- validateProperty( object, new PropertyIterator( propertyName ), failingConstraintViolations, groups );
+ validateProperty( object, new PropertyIterator( propertyName ), failingConstraintViolations, groupChain );
return new HashSet<ConstraintViolation<T>>( failingConstraintViolations );
}
@@ -135,15 +132,14 @@
* {@inheritDoc}
*/
public <T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups) {
-
- sanityCheckPropertyPath( propertyName );
-
if ( beanType == null ) {
throw new IllegalArgumentException( "The bean type cannot be null." );
}
+ sanityCheckPropertyPath( propertyName );
+ GroupChain groupChain = determineGroupExecutionOrder( groups );
List<ConstraintViolationImpl<T>> failingConstraintViolations = new ArrayList<ConstraintViolationImpl<T>>();
- validateValue( beanType, value, new PropertyIterator( propertyName ), failingConstraintViolations, groups );
+ validateValue( beanType, value, new PropertyIterator( propertyName ), failingConstraintViolations, groupChain );
return new HashSet<ConstraintViolation<T>>( failingConstraintViolations );
}
@@ -160,7 +156,7 @@
}
}
- private Class<?>[] validateGroupVararg(Class<?>[] groups) {
+ private GroupChain determineGroupExecutionOrder(Class<?>[] groups) {
if ( groups == null ) {
throw new IllegalArgumentException( "null passed as group name" );
}
@@ -169,7 +165,8 @@
if ( groups.length == 0 ) {
groups = DEFAULT_GROUP_ARRAY;
}
- return groups;
+
+ return groupChainGenerator.getGroupChainFor( Arrays.asList( groups ) );
}
/**
@@ -177,16 +174,15 @@
*
* @param context A context object containing the object to validate together with other state information needed
* for validation.
- * @param groups A list of groups to validate.
+ * @param groupChain A <code>GroupChain</code> instance containing the resolved group sequence to execute
*
* @return List of invalid constraints.
*/
- private <T> List<ConstraintViolationImpl<T>> validateInContext(ExecutionContext<T> context, List<Class<?>> groups) {
+ private <T> List<ConstraintViolationImpl<T>> validateInContext(ExecutionContext<T> context, GroupChain groupChain) {
if ( context.peekValidatedObject() == null ) {
return Collections.emptyList();
}
- GroupChain groupChain = groupChainGenerator.getGroupChainFor( groups );
while ( groupChain.hasNext() ) {
int numberOfViolations = context.getFailingConstraints().size();
Group group = groupChain.next();
@@ -209,9 +205,8 @@
*/
private <T> void validateConstraints(ExecutionContext<T> executionContext) {
//casting rely on the fact that root object is at the top of the stack
- @SuppressWarnings("unchecked")
- BeanMetaData<T> beanMetaData =
- ( BeanMetaData<T> ) getBeanMetaData( executionContext.peekValidatedObjectType() );
+ @SuppressWarnings(" unchecked")
+ BeanMetaData<T> beanMetaData = getBeanMetaData( ( Class<T> ) executionContext.peekValidatedObjectType() );
if ( executionContext.getCurrentGroup().getName().equals( Default.class.getName() ) ) {
List<Class<?>> defaultGroupSequence = beanMetaData.getDefaultGroupSequence();
if ( log.isDebugEnabled() && defaultGroupSequence.size() > 0 ) {
@@ -251,7 +246,7 @@
*/
private <T> boolean validateConstraintsForCurrentGroup(ExecutionContext<T> executionContext, BeanMetaData<T> beanMetaData) {
boolean validationSuccessful = true;
- for ( MetaConstraint metaConstraint : beanMetaData.geMetaConstraintList() ) {
+ for ( MetaConstraint<T> metaConstraint : beanMetaData.geMetaConstraintList() ) {
executionContext.pushProperty( metaConstraint.getPropertyName() );
if ( executionContext.checkValidationRequired( metaConstraint.getGroupList() ) ) {
boolean tmp = metaConstraint.validateConstraint( beanMetaData.getBeanClass(), executionContext );
@@ -313,6 +308,7 @@
return iter;
}
+ @SuppressWarnings("RedundantArrayCreation")
private <T> void validateCascadedConstraint(ExecutionContext<T> context, Iterator<?> iter) {
Object actualValue;
String propertyIndex;
@@ -336,21 +332,24 @@
context.replacePropertyIndex( propertyIndex );
context.pushValidatedObject( actualValue );
- validateInContext( context, Arrays.asList( new Class<?>[] { context.getCurrentGroup() } ) );
+ validateInContext(
+ context,
+ groupChainGenerator.getGroupChainFor( Arrays.asList( new Class<?>[] { context.getCurrentGroup() } ) )
+ );
context.popValidatedObject();
i++;
}
}
- private <T> void validateProperty(T object, PropertyIterator propertyIter, List<ConstraintViolationImpl<T>> failingConstraintViolations, Class<?>... groups) {
+ private <T> void validateProperty(T object, PropertyIterator propertyIter, List<ConstraintViolationImpl<T>> failingConstraintViolations, GroupChain groupChain) {
@SuppressWarnings("unchecked")
final Class<T> beanType = ( Class<T> ) object.getClass();
- Set<MetaConstraint> metaConstraints = new HashSet<MetaConstraint>();
- Object hostingBean = collectMetaConstraintsForPath( beanType, object, propertyIter, metaConstraints );
+ Set<MetaConstraint<T>> metaConstraints = new HashSet<MetaConstraint<T>>();
+ Object hostingBeanInstance = collectMetaConstraintsForPath( beanType, object, propertyIter, metaConstraints );
- if ( hostingBean == null ) {
+ if ( hostingBeanInstance == null ) {
throw new IllegalArgumentException( "Invalid property path." );
}
@@ -358,57 +357,82 @@
return;
}
- groups = validateGroupVararg( groups );
-
- GroupChain groupChain = groupChainGenerator.getGroupChainFor( Arrays.asList( groups ) );
while ( groupChain.hasNext() ) {
Group group = groupChain.next();
- for ( MetaConstraint metaConstraint : metaConstraints ) {
- if ( !metaConstraint.getGroupList().contains( group.getGroup() ) ) {
- continue;
+ int numberOfConstraintViolations = failingConstraintViolations.size();
+ BeanMetaData<T> beanMetaData = getBeanMetaData( metaConstraints.iterator().next().getBeanClass() );
+
+ List<Class<?>> groupList;
+ if ( group.isDefaultGroup() ) {
+ groupList = beanMetaData.getDefaultGroupSequence();
+ }
+ else {
+ groupList = new ArrayList<Class<?>>();
+ groupList.add( group.getGroup() );
+ }
+
+ for ( Class<?> groupClass : groupList ) {
+ for ( MetaConstraint<T> metaConstraint : metaConstraints ) {
+ if ( metaConstraint.getGroupList().contains( groupClass ) ) {
+ ExecutionContext<T> context = new ExecutionContext<T>(
+ object, hostingBeanInstance, messageInterpolator, constraintValidatorFactory
+ );
+ context.pushProperty( propertyIter.getOriginalProperty() );
+ metaConstraint.validateConstraint( object.getClass(), context );
+ failingConstraintViolations.addAll( context.getFailingConstraints() );
+ }
}
- ExecutionContext<T> context = new ExecutionContext<T>(
- object, hostingBean, messageInterpolator, constraintValidatorFactory
- );
- context.pushProperty( propertyIter.getOriginalProperty() );
- metaConstraint.validateConstraint( object.getClass(), context );
- failingConstraintViolations.addAll( context.getFailingConstraints() );
+ if ( failingConstraintViolations.size() > numberOfConstraintViolations) {
+ break;
+ }
}
- if ( groupChain.inSequence() && failingConstraintViolations.size() > 0 ) {
+ if ( groupChain.inSequence() && failingConstraintViolations.size() > numberOfConstraintViolations ) {
groupChain.moveToLastInCurrentSequence();
}
}
}
- private <T> void validateValue(Class<T> beanType, Object value, PropertyIterator propertyIter, List<ConstraintViolationImpl<T>> failingConstraintViolations, Class<?>... groups) {
- Set<MetaConstraint> metaConstraints = new HashSet<MetaConstraint>();
+ @SuppressWarnings("unchecked")
+ private <T> void validateValue(Class<T> beanType, Object value, PropertyIterator propertyIter, List<ConstraintViolationImpl<T>> failingConstraintViolations, GroupChain groupChain) {
+ Set<MetaConstraint<T>> metaConstraints = new HashSet<MetaConstraint<T>>();
collectMetaConstraintsForPath( beanType, null, propertyIter, metaConstraints );
if ( metaConstraints.size() == 0 ) {
return;
}
- groups = validateGroupVararg( groups );
-
- GroupChain groupChain = groupChainGenerator.getGroupChainFor( Arrays.asList( groups ) );
while ( groupChain.hasNext() ) {
Group group = groupChain.next();
+ int numberOfConstraintViolations = failingConstraintViolations.size();
+ BeanMetaData<T> beanMetaData = getBeanMetaData( metaConstraints.iterator().next().getBeanClass() );
- for ( MetaConstraint metaConstraint : metaConstraints ) {
- if ( !metaConstraint.getGroupList().contains( group.getGroup() ) ) {
- continue;
+ List<Class<?>> groupList;
+ if ( group.isDefaultGroup() ) {
+ groupList = beanMetaData.getDefaultGroupSequence();
+ }
+ else {
+ groupList = new ArrayList<Class<?>>();
+ groupList.add( group.getGroup() );
+ }
+
+ for ( Class<?> groupClass : groupList ) {
+ for ( MetaConstraint<T> metaConstraint : metaConstraints ) {
+ if ( metaConstraint.getGroupList().contains( groupClass ) ) {
+ ExecutionContext<T> context = new ExecutionContext<T>(
+ ( T ) value, messageInterpolator, constraintValidatorFactory
+ );
+ context.pushProperty( propertyIter.getOriginalProperty() );
+ metaConstraint.validateConstraint( beanType.getClass(), value, context );
+ failingConstraintViolations.addAll( context.getFailingConstraints() );
+ }
}
-
- ExecutionContext<T> context = new ExecutionContext<T>(
- ( T ) value, messageInterpolator, constraintValidatorFactory
- );
- context.pushProperty( propertyIter.getOriginalProperty() );
- metaConstraint.validateConstraint( beanType, value, context );
- failingConstraintViolations.addAll( context.getFailingConstraints() );
+ if ( failingConstraintViolations.size() > numberOfConstraintViolations) {
+ break;
+ }
}
- if ( groupChain.inSequence() && failingConstraintViolations.size() > 0 ) {
+ if ( groupChain.inSequence() && failingConstraintViolations.size() > numberOfConstraintViolations ) {
groupChain.moveToLastInCurrentSequence();
}
}
@@ -427,7 +451,8 @@
*
* @return Returns the bean hosting the constraints which match the specified property path.
*/
- private Object collectMetaConstraintsForPath(Class<?> clazz, Object value, PropertyIterator propertyIter, Set<MetaConstraint> metaConstraints) {
+ @SuppressWarnings("unchecked")
+ private <T> Object collectMetaConstraintsForPath(Class<T> clazz, Object value, PropertyIterator propertyIter, Set<MetaConstraint<T>> metaConstraints) {
propertyIter.split();
if ( !propertyIter.hasNext() ) {
@@ -435,8 +460,8 @@
throw new IllegalArgumentException( "Invalid property path." );
}
- List<MetaConstraint> metaConstraintList = getBeanMetaData( clazz ).geMetaConstraintList();
- for ( MetaConstraint metaConstraint : metaConstraintList ) {
+ List<MetaConstraint<T>> metaConstraintList = getBeanMetaData( clazz ).geMetaConstraintList();
+ for ( MetaConstraint<T> metaConstraint : metaConstraintList ) {
if ( metaConstraint.getPropertyName().equals( propertyIter.getHead() ) ) {
metaConstraints.add( metaConstraint );
}
@@ -458,7 +483,7 @@
}
}
collectMetaConstraintsForPath(
- ( Class<?> ) type, value, propertyIter, metaConstraints
+ ( Class<T> ) type, value, propertyIter, metaConstraints
);
}
}
@@ -469,14 +494,14 @@
/**
* {@inheritDoc}
*/
- private <T> BeanMetaDataImpl<T> getBeanMetaData(Class<T> beanClass) {
+ private <T> BeanMetaData<T> getBeanMetaData(Class<T> beanClass) {
if ( beanClass == null ) {
throw new IllegalArgumentException( "Class cannot be null" );
}
@SuppressWarnings("unchecked")
BeanMetaDataImpl<T> metadata = ( BeanMetaDataImpl<T> ) metadataProviders.get( beanClass );
if ( metadata == null ) {
- metadata = new BeanMetaDataImpl<T>( beanClass, builtinConstraints );
+ metadata = new BeanMetaDataImpl<T>( beanClass, constraintHelper );
metadataProviders.put( beanClass, metadata );
}
return metadata;
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/groups/Group.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/groups/Group.java 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/groups/Group.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -17,6 +17,8 @@
*/
package org.hibernate.validation.engine.groups;
+import javax.validation.groups.Default;
+
/**
* Encapsulates a single group.
*
@@ -68,6 +70,10 @@
return true;
}
+ public boolean isDefaultGroup() {
+ return getGroup().getName().equals( Default.class.getName() );
+ }
+
@Override
public int hashCode() {
int result = group != null ? group.hashCode() : 0;
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/ReflectionHelper.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/ReflectionHelper.java 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/ReflectionHelper.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -29,17 +29,13 @@
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
-import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import javax.validation.Constraint;
import javax.validation.ValidationException;
-import org.slf4j.Logger;
-
/**
* Some reflection utility methods.
*
@@ -47,8 +43,6 @@
*/
public class ReflectionHelper {
- private static final Logger log = LoggerFactory.make();
-
/**
* Private constructor in order to avoid instantiation.
*/
@@ -73,133 +67,6 @@
return isBuiltInConstraintAnnotation;
}
- /**
- * Checks whehter the specified annotation is a valid constraint annotation. A constraint annotations has to
- * fulfill the following conditions:
- * <ul>
- * <li>Has to contain a <code>ConstraintValidator</code> implementation.</li>
- * <li>Defines a message parameter.</li>
- * <li>Defines a group parameter.</li>
- * </ul>
- *
- * @param annotation The annotation to test.
- *
- * @return <code>true</code> if the annotation fulfills the above condtions, <code>false</code> otherwise.
- */
- public static boolean isConstraintAnnotation(Annotation annotation) {
-
- Constraint constraint = annotation.annotationType()
- .getAnnotation( Constraint.class );
- if ( constraint == null ) {
- return false;
- }
-
- try {
- getAnnotationParameter( annotation, "message", String.class );
- }
- catch ( Exception e ) {
- String msg = annotation.annotationType().getName() + " contains Constraint annotation, but does " +
- "not contain a message parameter. Annotation is getting ignored.";
- log.warn( msg );
- return false;
- }
-
- try {
- getAnnotationParameter( annotation, "groups", Class[].class );
- }
- catch ( Exception e ) {
- String msg = annotation.annotationType().getName() + " contains Constraint annotation, but does " +
- "not contain a groups parameter. Annotation is getting ignored.";
- log.warn( msg );
- return false;
- }
-
- Method[] methods = annotation.getClass().getMethods();
- for ( Method m : methods ) {
- if ( m.getName().startsWith( "valid" ) ) {
- String msg = "Parameters starting with 'valid' are not allowed in a constraint.";
- log.warn( msg );
- return false;
- }
- }
-
- return true;
- }
-
- /**
- * Checks whether a given annotation is a multi value constraint or not.
- *
- * @param annotation the annotation to check.
- *
- * @return <code>true</code> if the specified annotation is a multi value constraints, <code>false</code>
- * otherwise.
- */
- public static boolean isMultiValueConstraint(Annotation annotation) {
- boolean isMultiValueConstraint = false;
- try {
- Method m = annotation.getClass().getMethod( "value" );
- Class returnType = m.getReturnType();
- if ( returnType.isArray() && returnType.getComponentType().isAnnotation() ) {
- Annotation[] annotations = ( Annotation[] ) m.invoke( annotation );
- for ( Annotation a : annotations ) {
- if ( isConstraintAnnotation( a ) || isBuiltInConstraintAnnotation( a ) ) {
- isMultiValueConstraint = true;
- }
- else {
- isMultiValueConstraint = false;
- break;
- }
- }
- }
- }
- catch ( NoSuchMethodException nsme ) {
- // ignore
- }
- catch ( IllegalAccessException iae ) {
- // ignore
- }
- catch ( InvocationTargetException ite ) {
- // ignore
- }
- return isMultiValueConstraint;
- }
-
-
- /**
- * Checks whether a given annotation is a multi value constraint and returns the contained constraints if so.
- *
- * @param annotation the annotation to check.
- *
- * @return A list of constraint annotations or the empty list if <code>annotation</code> is not a multi constraint
- * annotation.
- */
- public static <A extends Annotation> List<Annotation> getMultiValueConstraints(A annotation) {
- List<Annotation> annotationList = new ArrayList<Annotation>();
- try {
- Method m = annotation.getClass().getMethod( "value" );
- Class returnType = m.getReturnType();
- if ( returnType.isArray() && returnType.getComponentType().isAnnotation() ) {
- Annotation[] annotations = ( Annotation[] ) m.invoke( annotation );
- for ( Annotation a : annotations ) {
- if ( isConstraintAnnotation( a ) || isBuiltInConstraintAnnotation( a ) ) {
- annotationList.add( a );
- }
- }
- }
- }
- catch ( NoSuchMethodException nsme ) {
- // ignore
- }
- catch ( IllegalAccessException iae ) {
- // ignore
- }
- catch ( InvocationTargetException ite ) {
- // ignore
- }
- return annotationList;
- }
-
-
@SuppressWarnings("unchecked")
public static <T> T getAnnotationParameter(Annotation annotation, String parameterName, Class<T> type) {
try {
@@ -502,7 +369,7 @@
return true;
}
catch ( NoSuchFieldException e ) {
- ; // ignore
+ // ignore
}
try {
@@ -510,7 +377,7 @@
return true;
}
catch ( NoSuchMethodException e ) {
- ; // ignore
+ // ignore
}
return false;
}
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/annotationfactory/AnnotationProxy.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/annotationfactory/AnnotationProxy.java 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/annotationfactory/AnnotationProxy.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -79,7 +79,7 @@
}
}
if ( processedValuesFromDescriptor != descriptor.numberOfElements() ) {
- throw new RuntimeException( "Trying to instanciate " + annotationType + " with unknown elements" );
+ throw new RuntimeException( "Trying to instanciate " + annotationType + " with unknown paramters." );
}
return result;
}
Modified: validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation/ValidationMessages.properties
===================================================================
--- validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation/ValidationMessages.properties 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation/ValidationMessages.properties 2009-02-25 13:09:51 UTC (rev 16031)
@@ -3,7 +3,7 @@
validator.size=size must be between {min} and {max}
validator.length=length must be between {min} and {max}
validator.notEmpty=may not be empty
-validator.pattern=must match "{regex}"
+validator.pattern=must match "{regexp}"
validator.min=must be greater than {value}
validator.max=must be less than {value}
validator.null=must be null
Modified: validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation/ValidationMessages_de.properties
===================================================================
--- validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation/ValidationMessages_de.properties 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation/ValidationMessages_de.properties 2009-02-25 13:09:51 UTC (rev 16031)
@@ -1,9 +1,9 @@
-# $Id: ValidationMessages.properties 15846 2009-02-02 11:56:15Z hardy.ferentschik $
+# $Id$
validator.notNull=kann nicht null sein
validator.size=muss zwischen {min} und {max} liegen
validator.length=muss zwischen {min} und {max} liegen
validator.notEmpty=kann nicht leer sein
-validator.pattern=muss auf Ausdruck "{regex}" passen
+validator.pattern=muss auf Ausdruck "{regexp}" passen
validator.min=muss gr\u00F6\u00DFer sein als {value}
validator.max=muss kleiner sein als {value}
validator.null=muss null sein
Property changes on: validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation/ValidationMessages_de.properties
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation/ValidationMessages_fr.properties
===================================================================
--- validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation/ValidationMessages_fr.properties 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation/ValidationMessages_fr.properties 2009-02-25 13:09:51 UTC (rev 16031)
@@ -1,9 +1,9 @@
-# $Id: ValidationMessages.properties 15846 2009-02-02 11:56:15Z hardy.ferentschik $
+# $Id$
validator.notNull=ne peut pas \u00EAtre nul
validator.size=la taille doit \u00EAtre entre {min} et {max}
validator.length=length must be between {min} and {max}
validator.notEmpty=ne peut pas \u00EAtre vide
-validator.pattern=doit suivre "{regex}"
+validator.pattern=doit suivre "{regexp}"
validator.min=doit \u00EAtre plus grand que {value}
validator.max=doit \u00EAtre plus petit que {value}
validator.null=doit \u00EAtre nul
Property changes on: validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation/ValidationMessages_fr.properties
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/PatternValidatorTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/PatternValidatorTest.java 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/PatternValidatorTest.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -17,6 +17,8 @@
*/
package org.hibernate.validation.constraints;
+import javax.validation.constraints.Pattern;
+
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
@@ -36,7 +38,7 @@
public static void init() {
AnnotationDescriptor descriptor = new AnnotationDescriptor( Pattern.class );
- descriptor.setValue( "regex", "foobar" );
+ descriptor.setValue( "regexp", "foobar" );
descriptor.setValue( "message", "{validator.pattern}" );
Pattern p = AnnotationFactory.create( descriptor );
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/composition/FrenchZipcode.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/composition/FrenchZipcode.java 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/composition/FrenchZipcode.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -29,9 +29,8 @@
import javax.validation.OverridesParameters;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
+import javax.validation.constraints.Pattern;
-import org.hibernate.validation.constraints.Pattern;
-import org.hibernate.validation.constraints.Patterns;
/**
* @author Hardy Ferentschik
@@ -39,7 +38,7 @@
@NotNull
@Size
// first pattern just duplicates the length of 5 characters, the second pattern is just to proof that parameters can be overridden.
-@Patterns({ @Pattern(regex = "....."), @Pattern(regex = "bar") })
+(a)Pattern.List({ @Pattern(regexp = "....."), @Pattern(regexp = "bar") })
@Constraint(validatedBy = FrenchZipcodeConstraintValidator.class)
@Documented
@Target({ METHOD, FIELD, TYPE })
@@ -58,5 +57,5 @@
parameter = "message") String sizeMessage() default "A french zip code has a length of 5";
- @OverridesParameter(constraint = Pattern.class, parameter = "regex", index = 2) String regex() default "\\d*";
+ @OverridesParameter(constraint = Pattern.class, parameter = "regexp", index = 2) String regex() default "\\d*";
}
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/eg/Engine.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/eg/Engine.java 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/eg/Engine.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -17,17 +17,17 @@
*/
package org.hibernate.validation.eg;
-import org.hibernate.validation.constraints.Pattern;
-import org.hibernate.validation.constraints.Patterns;
+import javax.validation.constraints.Pattern;
+
/**
* @author Hardy Ferentschik
*/
public class Engine {
- @Patterns({
- @Pattern(regex = "^[A-Z0-9-]+$",
+ @Pattern.List({
+ @Pattern(regexp = "^[A-Z0-9-]+$",
message = "must contain alphabetical characters only"),
- @Pattern(regex = "^....-....-....$", message = "must match ....-....-....")
+ @Pattern(regexp = "^....-....-....$", message = "must match ....-....-....")
})
private String serialNumber;
Added: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ConstraintHelperTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ConstraintHelperTest.java (rev 0)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ConstraintHelperTest.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -0,0 +1,134 @@
+// $Id:$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* 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.hibernate.validation.engine;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+import java.util.List;
+import javax.validation.constraints.NotNull;
+import javax.validation.constraints.Pattern;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import org.hibernate.validation.constraints.incomplete.NoGroups;
+import org.hibernate.validation.constraints.incomplete.NoMessage;
+import org.hibernate.validation.constraints.incomplete.ValidProperty;
+import org.hibernate.validation.eg.Engine;
+import org.hibernate.validation.eg.Order;
+import org.hibernate.validation.util.ReflectionHelper;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class ConstraintHelperTest {
+
+ private static ConstraintHelper constraintHelper;
+
+ @BeforeClass
+ public static void init() {
+ constraintHelper = new ConstraintHelper();
+ }
+
+ @Test
+ public void testConstraintWithNoMessage() {
+ Annotation annotation = new NoGroups() {
+ public String message() {
+ return "";
+ }
+
+ public Class<? extends Annotation> annotationType() {
+ return this.getClass();
+ }
+ };
+ assertFalse(
+ "The constraint annotation should not be valid", constraintHelper.isConstraintAnnotation( annotation )
+ );
+ }
+
+ @Test
+ public void testConstraintWithNoGroups() {
+ Annotation annotation = new NoMessage() {
+ public Class<?>[] groups() {
+ return null;
+ }
+
+ public Class<? extends Annotation> annotationType() {
+ return this.getClass();
+ }
+ };
+ assertFalse(
+ "The constraint annotation should not be valid", constraintHelper.isConstraintAnnotation( annotation )
+ );
+ }
+
+ @Test
+ public void testConstraintWithValidInPropertyName() {
+ Annotation annotation = new ValidProperty() {
+ public String message() {
+ return null;
+ }
+
+ public Class<?>[] groups() {
+ return null;
+ }
+
+ public int validLength() {
+ return 0;
+ }
+
+ public Class<? extends Annotation> annotationType() {
+ return this.getClass();
+ }
+ };
+ assertFalse(
+ "The constraint annotation should not be valid", constraintHelper.isConstraintAnnotation( annotation )
+ );
+ }
+
+ @Test
+ public void testGetMultiValueConstraints() throws Exception {
+ Engine engine = new Engine();
+ Field[] fields = engine.getClass().getDeclaredFields();
+ assertNotNull( fields );
+ assertTrue( fields.length == 1 );
+ ReflectionHelper.setAccessibility( fields[0] );
+
+ Annotation annotation = fields[0].getAnnotation( Pattern.List.class );
+ assertNotNull( annotation );
+ List<Annotation> multiValueConstraintAnnotations = constraintHelper.getMultiValueConstraints( annotation );
+ assertTrue( "There should be two constraint annotations", multiValueConstraintAnnotations.size() == 2 );
+ assertTrue( "Wrong constraint annotation", multiValueConstraintAnnotations.get( 0 ) instanceof Pattern );
+ assertTrue( "Wrong constraint annotation", multiValueConstraintAnnotations.get( 1 ) instanceof Pattern );
+
+
+ Order order = new Order();
+ fields = order.getClass().getDeclaredFields();
+ assertNotNull( fields );
+ assertTrue( fields.length == 1 );
+ ReflectionHelper.setAccessibility( fields[0] );
+
+ annotation = fields[0].getAnnotation( NotNull.class );
+ assertNotNull( annotation );
+ multiValueConstraintAnnotations = constraintHelper.getMultiValueConstraints( annotation );
+ assertTrue( "There should be no constraint annotations", multiValueConstraintAnnotations.size() == 0 );
+ }
+}
Property changes on: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ConstraintHelperTest.java
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolatorTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolatorTest.java 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolatorTest.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -59,7 +59,7 @@
@Test
public void testSuccessfulInterpolation() {
ConstraintDescriptorImpl<NotNull> descriptor = new ConstraintDescriptorImpl<NotNull>(
- notNull, new Class<?>[] { }, new BuiltinConstraints()
+ notNull, new Class<?>[] { }, new ConstraintHelper()
);
String expected = "replacement worked";
@@ -82,7 +82,7 @@
@Test
public void testUnSuccessfulInterpolation() {
ConstraintDescriptorImpl<NotNull> descriptor = new ConstraintDescriptorImpl<NotNull>(
- notNull, new Class<?>[] { }, new BuiltinConstraints()
+ notNull, new Class<?>[] { }, new ConstraintHelper()
);
String expected = "foo"; // missing {}
String actual = interpolator.interpolate( "foo", descriptor, null );
@@ -96,7 +96,7 @@
@Test
public void testUnkownTokenInterpolation() {
ConstraintDescriptorImpl<NotNull> descriptor = new ConstraintDescriptorImpl<NotNull>(
- notNull, new Class<?>[] { }, new BuiltinConstraints()
+ notNull, new Class<?>[] { }, new ConstraintHelper()
);
String expected = "{bar}"; // unkown token {}
String actual = interpolator.interpolate( "{bar}", descriptor, null );
@@ -106,14 +106,14 @@
@Test
public void testDefaultInterpolation() {
ConstraintDescriptorImpl<NotNull> descriptor = new ConstraintDescriptorImpl<NotNull>(
- notNull, new Class<?>[] { }, new BuiltinConstraints()
+ notNull, new Class<?>[] { }, new ConstraintHelper()
);
String expected = "may not be null";
String actual = interpolator.interpolate( notNull.message(), descriptor, null );
assertEquals( "Wrong substitution", expected, actual );
ConstraintDescriptorImpl<Size> sizeDescriptor = new ConstraintDescriptorImpl<Size>(
- size, new Class<?>[] { }, new BuiltinConstraints()
+ size, new Class<?>[] { }, new ConstraintHelper()
);
expected = "size must be between 0 and 2147483647"; // unkown token {}
actual = interpolator.interpolate( size.message(), sizeDescriptor, null );
@@ -125,7 +125,7 @@
interpolator = new ResourceBundleMessageInterpolator();
ConstraintDescriptorImpl<NotNull> descriptor = new ConstraintDescriptorImpl<NotNull>(
- notNull, new Class<?>[] { }, new BuiltinConstraints()
+ notNull, new Class<?>[] { }, new ConstraintHelper()
);
String expected = "kann nicht null sein";
@@ -138,7 +138,7 @@
interpolator = new ResourceBundleMessageInterpolator();
ConstraintDescriptorImpl<NotNull> descriptor = new ConstraintDescriptorImpl<NotNull>(
- notNull, new Class<?>[] { }, new BuiltinConstraints()
+ notNull, new Class<?>[] { }, new ConstraintHelper()
);
String expected = "may not be null";
@@ -151,7 +151,7 @@
interpolator = new ResourceBundleMessageInterpolator();
ConstraintDescriptorImpl<NotNull> descriptor = new ConstraintDescriptorImpl<NotNull>(
- notNull, new Class<?>[] { }, new BuiltinConstraints()
+ notNull, new Class<?>[] { }, new ConstraintHelper()
);
String expected = "no puede ser null";
Copied: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/Car.java (from rev 16024, validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/User.java)
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/Car.java (rev 0)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/Car.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -0,0 +1,30 @@
+package org.hibernate.validation.engine.groups;
+
+import javax.validation.GroupSequence;
+import javax.validation.constraints.Pattern;
+import javax.validation.groups.Default;
+
+import org.hibernate.validation.constraints.Length;
+
+/**
+ * @author Emmanuel Bernard
+ * @author Hardy Ferentschik
+ */
+@GroupSequence({ Car.class, Car.Test.class })
+public class Car {
+ @Pattern(regexp = ".*", groups = Default.class)
+ @Length(min = 2, max = 20, groups = Car.Test.class)
+ private String type;
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public interface Test {
+
+ }
+}
\ No newline at end of file
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/GroupTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/GroupTest.java 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/GroupTest.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -332,6 +332,41 @@
* HV-113
*/
@Test
+ public void testRedefiningDefaultGroup2() {
+ Car car = new Car();
+ car.setType( "A" );
+
+ Validator validator = TestUtil.getValidator();
+
+ Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car );
+ assertEquals(
+ "There should be one violations due to the re-defintion of the default group",
+ 1,
+ constraintViolations.size()
+ );
+ assertEquals( "Wrong constraint", "length must be between 2 and 20", constraintViolations.iterator().next().getMessage() );
+
+ constraintViolations = validator.validateProperty( car, "type" );
+ assertEquals(
+ "There should be one violations due to the re-defintion of the default group",
+ 1,
+ constraintViolations.size()
+ );
+ assertEquals( "Wrong constraint", "length must be between 2 and 20", constraintViolations.iterator().next().getMessage() );
+
+ constraintViolations = validator.validateValue( Car.class, "type", "A" );
+ assertEquals(
+ "There should be one violations due to the re-defintion of the default group",
+ 1,
+ constraintViolations.size()
+ );
+ assertEquals( "Wrong constraint", "length must be between 2 and 20", constraintViolations.iterator().next().getMessage() );
+ }
+
+ /**
+ * HV-113
+ */
+ @Test
public void testInvalidRedefinitionOfDefaultGroup() {
Address address = new AddressWithInvalidGroupSequence();
Validator validator = TestUtil.getValidator();
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/User.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/User.java 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/User.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -1,14 +1,16 @@
package org.hibernate.validation.engine.groups;
+import javax.validation.GroupSequence;
import javax.validation.constraints.NotNull;
+import javax.validation.constraints.Pattern;
import javax.validation.groups.Default;
-import org.hibernate.validation.constraints.Pattern;
/**
* @author Emmanuel Bernard
* @author Hardy Ferentschik
*/
+@GroupSequence({ User.class })
public class User {
@NotNull
private String firstname;
@@ -16,7 +18,7 @@
@NotNull(groups = Default.class)
private String lastname;
- @Pattern(regex = "[0-9 -]?", groups = Optional.class)
+ @Pattern(regexp = "[0-9 -]?", groups = Optional.class)
private String phoneNumber;
@NotNull(groups = { Billable.class, BuyInOneClick.class })
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/ReflectionHelperTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/ReflectionHelperTest.java 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/ReflectionHelperTest.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -18,7 +18,6 @@
package org.hibernate.validation.util;
import java.lang.annotation.Annotation;
-import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -28,21 +27,11 @@
import javax.validation.groups.Default;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
-import org.hibernate.validation.constraints.Pattern;
-import org.hibernate.validation.constraints.Patterns;
-import org.hibernate.validation.constraints.incomplete.NoGroups;
-import org.hibernate.validation.constraints.incomplete.NoMessage;
-import org.hibernate.validation.constraints.incomplete.ValidProperty;
-import org.hibernate.validation.eg.Engine;
-import org.hibernate.validation.eg.Order;
-
/**
* Tests for the <code>ReflectionHelper</code>.
*
@@ -129,91 +118,4 @@
);
}
}
-
- @Test
- // @SpecAssertion(section = "2.1.1.2", note = "constraint annotation must specify a groups element")
- public void testConstraintWithNoMessage() {
- Annotation annotation = new NoGroups() {
- public String message() {
- return "";
- }
-
- public Class<? extends Annotation> annotationType() {
- return this.getClass();
- }
- };
- assertFalse(
- "The constraint annotation should not be valid", ReflectionHelper.isConstraintAnnotation( annotation )
- );
- }
-
- @Test
- // @SpecAssertion(section = "2.1.1.1", note = "constraint annotation must specify a groups element")
- public void testConstraintWithNoGroups() {
- Annotation annotation = new NoMessage() {
- public Class<?>[] groups() {
- return null;
- }
-
- public Class<? extends Annotation> annotationType() {
- return this.getClass();
- }
- };
- assertFalse(
- "The constraint annotation should not be valid", ReflectionHelper.isConstraintAnnotation( annotation )
- );
- }
-
- @Test
- // @SpecAssertion(section = "2.1.1", note = "properties cannot begin with 'valid'")
- public void testConstraintWithValidInPropertyName() {
- Annotation annotation = new ValidProperty() {
- public String message() {
- return null;
- }
-
- public Class<?>[] groups() {
- return null;
- }
-
- public int validLength() {
- return 0;
- }
-
- public Class<? extends Annotation> annotationType() {
- return this.getClass();
- }
- };
- assertFalse(
- "The constraint annotation should not be valid", ReflectionHelper.isConstraintAnnotation( annotation )
- );
- }
-
- @Test
- public void testGetMultiValueConstraints() throws Exception {
- Engine engine = new Engine();
- Field[] fields = engine.getClass().getDeclaredFields();
- assertNotNull( fields );
- assertTrue( fields.length == 1 );
- ReflectionHelper.setAccessibility( fields[0] );
-
- Annotation annotation = fields[0].getAnnotation( Patterns.class );
- assertNotNull( annotation );
- List<Annotation> multiValueConstraintAnnotations = ReflectionHelper.getMultiValueConstraints( annotation );
- assertTrue( "There should be two constraint annotations", multiValueConstraintAnnotations.size() == 2 );
- assertTrue( "Wrong constraint annotation", multiValueConstraintAnnotations.get( 0 ) instanceof Pattern );
- assertTrue( "Wrong constraint annotation", multiValueConstraintAnnotations.get( 1 ) instanceof Pattern );
-
-
- Order order = new Order();
- fields = order.getClass().getDeclaredFields();
- assertNotNull( fields );
- assertTrue( fields.length == 1 );
- ReflectionHelper.setAccessibility( fields[0] );
-
- annotation = fields[0].getAnnotation( NotNull.class );
- assertNotNull( annotation );
- multiValueConstraintAnnotations = ReflectionHelper.getMultiValueConstraints( annotation );
- assertTrue( "There should be no constraint annotations", multiValueConstraintAnnotations.size() == 0 );
- }
}
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/annotationfactory/AnnotationFactoryTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/annotationfactory/AnnotationFactoryTest.java 2009-02-25 12:21:36 UTC (rev 16030)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/annotationfactory/AnnotationFactoryTest.java 2009-02-25 13:09:51 UTC (rev 16031)
@@ -18,11 +18,11 @@
package org.hibernate.validation.util.annotationfactory;
import javax.validation.constraints.Size;
+import javax.validation.constraints.Pattern;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
-import org.hibernate.validation.constraints.Pattern;
/**
* @author Hardy Ferentschik
@@ -44,16 +44,16 @@
@Test(expected = IllegalArgumentException.class)
public void createAnnotationProxyMissingRequiredParamter() {
AnnotationDescriptor descriptor = new AnnotationDescriptor( Pattern.class );
- Pattern pattern = AnnotationFactory.create( descriptor );
+ AnnotationFactory.create( descriptor );
}
@Test
public void createAnnotationProxyWithRequiredParamter() {
AnnotationDescriptor descriptor = new AnnotationDescriptor( Pattern.class );
- descriptor.setValue( "regex", ".*" );
+ descriptor.setValue( "regexp", ".*" );
Pattern pattern = AnnotationFactory.create( descriptor );
- assertEquals( "Wrong parameter value", ".*", pattern.regex() );
+ assertEquals( "Wrong parameter value", ".*", pattern.regexp() );
}
}
15 years, 9 months
Hibernate SVN: r16030 - core/trunk/testsuite/src/test/java/org/hibernate/test/filter.
by hibernate-commits@lists.jboss.org
Author: jcosta(a)redhat.com
Date: 2009-02-25 07:21:36 -0500 (Wed, 25 Feb 2009)
New Revision: 16030
Modified:
core/trunk/testsuite/src/test/java/org/hibernate/test/filter/DynamicFilterTest.java
Log:
HHH-3637 - Reverted eviction of test for Sybase
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/filter/DynamicFilterTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/filter/DynamicFilterTest.java 2009-02-25 11:41:00 UTC (rev 16029)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/filter/DynamicFilterTest.java 2009-02-25 12:21:36 UTC (rev 16030)
@@ -27,7 +27,6 @@
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Subqueries;
-import org.hibernate.dialect.SybaseDialect;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.impl.SessionFactoryImpl;
import org.hibernate.junit.functional.FunctionalTestCase;
@@ -71,10 +70,6 @@
}
public void testSqlSyntaxOfFiltersWithUnions() {
- // HHH-3637 - Union in where doesn't works for Sybase, need to evict test case
- if ( ( getDialect() instanceof SybaseDialect) ) {
- return;
- }
Session session = openSession();
session.enableFilter( "unioned" );
session.createQuery( "from Category" ).list();
15 years, 9 months
Hibernate SVN: r16029 - in beanvalidation/trunk/validation-api/src/main/java/javax/validation: bootstrap and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2009-02-25 06:41:00 -0500 (Wed, 25 Feb 2009)
New Revision: 16029
Modified:
beanvalidation/trunk/validation-api/src/main/java/javax/validation/Validation.java
beanvalidation/trunk/validation-api/src/main/java/javax/validation/bootstrap/GenericBootstrap.java
beanvalidation/trunk/validation-api/src/main/java/javax/validation/bootstrap/ProviderSpecificBootstrap.java
beanvalidation/trunk/validation-api/src/main/java/javax/validation/spi/ValidationProvider.java
Log:
BVAL-52 BVAL-55 define exception model
Modified: beanvalidation/trunk/validation-api/src/main/java/javax/validation/Validation.java
===================================================================
--- beanvalidation/trunk/validation-api/src/main/java/javax/validation/Validation.java 2009-02-24 20:48:49 UTC (rev 16028)
+++ beanvalidation/trunk/validation-api/src/main/java/javax/validation/Validation.java 2009-02-25 11:41:00 UTC (rev 16029)
@@ -101,6 +101,7 @@
* <code>Validation.byDefaultProvider().configure().buildValidatorFactory()</code>
*
* @return <code>ValidatorFactory</code> instance.
+ * @throws ValidationException if the ValidatorFactory cannot be built
*/
public static ValidatorFactory buildDefaultValidatorFactory() {
return byDefaultProvider().configure().buildValidatorFactory();
Modified: beanvalidation/trunk/validation-api/src/main/java/javax/validation/bootstrap/GenericBootstrap.java
===================================================================
--- beanvalidation/trunk/validation-api/src/main/java/javax/validation/bootstrap/GenericBootstrap.java 2009-02-24 20:48:49 UTC (rev 16028)
+++ beanvalidation/trunk/validation-api/src/main/java/javax/validation/bootstrap/GenericBootstrap.java 2009-02-25 11:41:00 UTC (rev 16029)
@@ -30,6 +30,8 @@
* by the ValidationProviderResolver strategy.
*
* @return a Configuration implementation compliant with the bootstrap state
+ * @throws javax.validation.ValidationException if the Configuration object cannot be built
+ * this is generally due to an issue with the ValidationProviderResolver
*/
Configuration<?> configure();
}
Modified: beanvalidation/trunk/validation-api/src/main/java/javax/validation/bootstrap/ProviderSpecificBootstrap.java
===================================================================
--- beanvalidation/trunk/validation-api/src/main/java/javax/validation/bootstrap/ProviderSpecificBootstrap.java 2009-02-24 20:48:49 UTC (rev 16028)
+++ beanvalidation/trunk/validation-api/src/main/java/javax/validation/bootstrap/ProviderSpecificBootstrap.java 2009-02-25 11:41:00 UTC (rev 16029)
@@ -33,6 +33,8 @@
* the creation of this specific Configuration subclass to the provider.
*
* @return a Configuration sub interface implementation
+ * @throws javax.validation.ValidationException if the Configuration object cannot be built
+ * this is generally due to an issue with the ValidationProviderResolver
*/
public T configure();
}
Modified: beanvalidation/trunk/validation-api/src/main/java/javax/validation/spi/ValidationProvider.java
===================================================================
--- beanvalidation/trunk/validation-api/src/main/java/javax/validation/spi/ValidationProvider.java 2009-02-24 20:48:49 UTC (rev 16028)
+++ beanvalidation/trunk/validation-api/src/main/java/javax/validation/spi/ValidationProvider.java 2009-02-25 11:41:00 UTC (rev 16029)
@@ -63,7 +63,8 @@
* use the current provider. The choice of provider follows the algorithm described
* in {@link javax.validation.Configuration}
* <p/>
- * The ValidationProviderResolver used is provided by <code>state</code>.
+ * The ValidationProviderResolver used by <code>Configuration</code>
+ * is provided by <code>state</code>.
* If null, the default ValidationProviderResolver is used.
*
* @param state bootstrap state
@@ -83,6 +84,7 @@
* @param configurationState the configuration descriptor
*
* @return the instanciated ValidatorFactory
+ * @throws javax.validation.ValidationException if the ValidatorFactory cannot be built
*/
ValidatorFactory buildValidatorFactory(ConfigurationState configurationState);
}
\ No newline at end of file
15 years, 9 months
Hibernate SVN: r16028 - validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-02-24 15:48:49 -0500 (Tue, 24 Feb 2009)
New Revision: 16028
Modified:
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java
Log:
cleanup
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java 2009-02-24 20:36:01 UTC (rev 16027)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java 2009-02-24 20:48:49 UTC (rev 16028)
@@ -354,13 +354,6 @@
order.setOrderNumber( 1234 );
constraintViolations = validator.validateProperty( customer, "orderList[0].orderNumber" );
assertEquals( "Wrong number of constraints", 0, constraintViolations.size() );
-
- try {
- constraintViolations = validator.validateProperty( customer, "orderList[1].orderNumber" );
- }
- catch ( IllegalArgumentException e ) {
- assertEquals( "Invalid property path.", e.getMessage() );
- }
}
@Test
15 years, 9 months
Hibernate SVN: r16027 - in validator/trunk/hibernate-validator/src: main/java/org/hibernate/validation/util and 2 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-02-24 15:36:01 -0500 (Tue, 24 Feb 2009)
New Revision: 16027
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/ReflectionHelper.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/GroupTest.java
Log:
Various bug fixes for validateValue and validateProperty
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java 2009-02-24 20:02:35 UTC (rev 16026)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java 2009-02-24 20:36:01 UTC (rev 16027)
@@ -119,6 +119,13 @@
* {@inheritDoc}
*/
public <T> Set<ConstraintViolation<T>> validateProperty(T object, String propertyName, Class<?>... groups) {
+
+ sanityCheckPropertyPath( propertyName );
+
+ if ( object == null ) {
+ throw new IllegalArgumentException( "Validated object cannot be null." );
+ }
+
List<ConstraintViolationImpl<T>> failingConstraintViolations = new ArrayList<ConstraintViolationImpl<T>>();
validateProperty( object, new PropertyIterator( propertyName ), failingConstraintViolations, groups );
return new HashSet<ConstraintViolation<T>>( failingConstraintViolations );
@@ -128,6 +135,13 @@
* {@inheritDoc}
*/
public <T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups) {
+
+ sanityCheckPropertyPath( propertyName );
+
+ if ( beanType == null ) {
+ throw new IllegalArgumentException( "The bean type cannot be null." );
+ }
+
List<ConstraintViolationImpl<T>> failingConstraintViolations = new ArrayList<ConstraintViolationImpl<T>>();
validateValue( beanType, value, new PropertyIterator( propertyName ), failingConstraintViolations, groups );
return new HashSet<ConstraintViolation<T>>( failingConstraintViolations );
@@ -140,6 +154,12 @@
return getBeanMetaData( clazz ).getBeanDescriptor();
}
+ private void sanityCheckPropertyPath(String propertyName) {
+ if ( propertyName == null || propertyName.length() == 0 ) {
+ throw new IllegalArgumentException( "Invalid property path." );
+ }
+ }
+
private Class<?>[] validateGroupVararg(Class<?>[] groups) {
if ( groups == null ) {
throw new IllegalArgumentException( "null passed as group name" );
@@ -196,14 +216,14 @@
List<Class<?>> defaultGroupSequence = beanMetaData.getDefaultGroupSequence();
if ( log.isDebugEnabled() && defaultGroupSequence.size() > 0 ) {
log.debug(
- "Executing redefined Default group for bean {} as sequence {}",
+ "Executing re-defined Default group for bean {} as sequence {}",
beanMetaData.getBeanClass().getName(),
defaultGroupSequence
);
}
for ( Class<?> defaultSequenceMember : defaultGroupSequence ) {
executionContext.setCurrentGroup( defaultSequenceMember );
- boolean validationSuccessful = validateConstraintsForBean( executionContext, beanMetaData );
+ boolean validationSuccessful = validateConstraintsForCurrentGroup( executionContext, beanMetaData );
if ( !validationSuccessful ) {
if ( log.isDebugEnabled() ) {
log.debug(
@@ -216,11 +236,20 @@
}
}
else {
- validateConstraintsForBean( executionContext, beanMetaData );
+ validateConstraintsForCurrentGroup( executionContext, beanMetaData );
}
}
- private <T> boolean validateConstraintsForBean(ExecutionContext<T> executionContext, BeanMetaData<T> beanMetaData) {
+ /**
+ * Validates all constraints for the given bean using the current group set in the execution context.
+ *
+ * @param executionContext The execution context.
+ * @param beanMetaData The bean metadata object for the bean to validate.
+ *
+ * @return <code>true</code> if the validation was successful (meaning no constraint violations), <code>false</code>
+ * otherwise.
+ */
+ private <T> boolean validateConstraintsForCurrentGroup(ExecutionContext<T> executionContext, BeanMetaData<T> beanMetaData) {
boolean validationSuccessful = true;
for ( MetaConstraint metaConstraint : beanMetaData.geMetaConstraintList() ) {
executionContext.pushProperty( metaConstraint.getPropertyName() );
@@ -314,15 +343,17 @@
}
private <T> void validateProperty(T object, PropertyIterator propertyIter, List<ConstraintViolationImpl<T>> failingConstraintViolations, Class<?>... groups) {
- if ( object == null ) {
- throw new IllegalArgumentException( "Validated object cannot be null" );
- }
+
@SuppressWarnings("unchecked")
final Class<T> beanType = ( Class<T> ) object.getClass();
Set<MetaConstraint> metaConstraints = new HashSet<MetaConstraint>();
- collectMetaConstraintsForPath( beanType, propertyIter, metaConstraints );
+ Object hostingBean = collectMetaConstraintsForPath( beanType, object, propertyIter, metaConstraints );
+ if ( hostingBean == null ) {
+ throw new IllegalArgumentException( "Invalid property path." );
+ }
+
if ( metaConstraints.size() == 0 ) {
return;
}
@@ -337,7 +368,7 @@
continue;
}
ExecutionContext<T> context = new ExecutionContext<T>(
- object, messageInterpolator, constraintValidatorFactory
+ object, hostingBean, messageInterpolator, constraintValidatorFactory
);
context.pushProperty( propertyIter.getOriginalProperty() );
metaConstraint.validateConstraint( object.getClass(), context );
@@ -352,7 +383,7 @@
private <T> void validateValue(Class<T> beanType, Object value, PropertyIterator propertyIter, List<ConstraintViolationImpl<T>> failingConstraintViolations, Class<?>... groups) {
Set<MetaConstraint> metaConstraints = new HashSet<MetaConstraint>();
- collectMetaConstraintsForPath( beanType, propertyIter, metaConstraints );
+ collectMetaConstraintsForPath( beanType, null, propertyIter, metaConstraints );
if ( metaConstraints.size() == 0 ) {
return;
@@ -386,21 +417,24 @@
/**
* Collects all <code>MetaConstraint</code>s which match the given path relative to the specified root class.
* <p>
- * This method does not traverse an actual object, but rather tries to resolve the porperty generically.
+ * This method is called recursively.
* </p>
- * <p>
- * This method is called recursively. Only if there is a valid 'validation path' through the object graph
- * a constraint descriptor will be returned.
- * </p>
*
* @param clazz the class type to check for constraints.
- * @param propertyIter an instance of <code>PropertyIterator</code>
+ * @param value While resolving the property path this instance points to the current object. Might be <code>null</code>.
+ * @param propertyIter an instance of <code>PropertyIterator</code> in order to iterate the items of the original property path.
* @param metaConstraints Set of <code>MetaConstraint</code>s to collect all matching constraints.
+ *
+ * @return Returns the bean hosting the constraints which match the specified property path.
*/
- private void collectMetaConstraintsForPath(Class<?> clazz, PropertyIterator propertyIter, Set<MetaConstraint> metaConstraints) {
+ private Object collectMetaConstraintsForPath(Class<?> clazz, Object value, PropertyIterator propertyIter, Set<MetaConstraint> metaConstraints) {
propertyIter.split();
if ( !propertyIter.hasNext() ) {
+ if ( !ReflectionHelper.containsMember( clazz, propertyIter.getHead() ) ) {
+ throw new IllegalArgumentException( "Invalid property path." );
+ }
+
List<MetaConstraint> metaConstraintList = getBeanMetaData( clazz ).geMetaConstraintList();
for ( MetaConstraint metaConstraint : metaConstraintList ) {
if ( metaConstraint.getPropertyName().equals( propertyIter.getHead() ) ) {
@@ -413,17 +447,23 @@
for ( Member m : cascadedMembers ) {
if ( ReflectionHelper.getPropertyName( m ).equals( propertyIter.getHead() ) ) {
Type type = ReflectionHelper.typeOf( m );
-
+ value = value == null ? null : ReflectionHelper.getValue( m, value );
if ( propertyIter.isIndexed() ) {
type = ReflectionHelper.getIndexedType( type );
+ value = value == null ? null : ReflectionHelper.getIndexedValue(
+ value, propertyIter.getIndex()
+ );
if ( type == null ) {
continue;
}
}
- collectMetaConstraintsForPath( ( Class<?> ) type, propertyIter, metaConstraints );
+ collectMetaConstraintsForPath(
+ ( Class<?> ) type, value, propertyIter, metaConstraints
+ );
}
}
}
+ return value;
}
/**
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/ReflectionHelper.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/ReflectionHelper.java 2009-02-24 20:02:35 UTC (rev 16026)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/ReflectionHelper.java 2009-02-24 20:36:01 UTC (rev 16027)
@@ -234,8 +234,6 @@
*
* @return The bean method name with the "is" or "get" prefix stripped off, <code>null</code>
* the method name id not according to the JavaBeans standard.
- *
- * @todo reference the JavaBean naming conventions spec here
*/
public static String getPropertyName(Member member) {
String name = null;
@@ -253,7 +251,6 @@
name = Introspector.decapitalize( methodName.substring( 3 ) );
}
}
-
return name;
}
@@ -489,4 +486,32 @@
}
return null;
}
+
+ /**
+ * Checks whether the specified class contains a field or member which matches a given property.
+ *
+ * @param clazz The class to check.
+ * @param property The property name.
+ *
+ * @return Returns <code>true</code> if the cass contains a field or member for the specified property, <code>
+ * false</code> otherwise.
+ */
+ public static boolean containsMember(Class clazz, String property) {
+ try {
+ clazz.getField( property );
+ return true;
+ }
+ catch ( NoSuchFieldException e ) {
+ ; // ignore
+ }
+
+ try {
+ clazz.getMethod( "get" + property.substring( 0, 1 ).toUpperCase() + property.substring( 1 ) );
+ return true;
+ }
+ catch ( NoSuchMethodException e ) {
+ ; // ignore
+ }
+ return false;
+ }
}
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java 2009-02-24 20:02:35 UTC (rev 16026)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java 2009-02-24 20:36:01 UTC (rev 16027)
@@ -102,7 +102,7 @@
}
@Test
- @SuppressWarnings( "NullArgumentToVariableArgMethod")
+ @SuppressWarnings("NullArgumentToVariableArgMethod")
public void testPassingNullAsGroup() {
Validator validator = TestUtil.getValidator();
Customer customer = new Customer();
@@ -176,7 +176,7 @@
}
@Test
- public void testValidationMethod() {
+ public void testMultipleValidationMethods() {
Validator validator = TestUtil.getValidator();
Address address = new Address();
@@ -224,15 +224,15 @@
Set<ConstraintViolation<Customer>> constraintViolations = validator.validate( customer );
assertEquals( "Wrong number of constraints", 0, constraintViolations.size() );
- Order order1 = new Order();
- customer.addOrder( order1 );
+ Order order = new Order();
+ customer.addOrder( order );
constraintViolations = validator.validate( customer );
ConstraintViolation constraintViolation = constraintViolations.iterator().next();
assertEquals( "Wrong number of constraints", 1, constraintViolations.size() );
assertEquals( "Wrong message", "may not be null", constraintViolation.getMessage() );
assertEquals( "Wrong root entity", customer, constraintViolation.getRootBean() );
- assertEquals( "Wrong value", order1.getOrderNumber(), constraintViolation.getInvalidValue() );
+ assertEquals( "Wrong value", order.getOrderNumber(), constraintViolation.getInvalidValue() );
assertEquals( "Wrong propertyName", "orderList[0].orderNumber", constraintViolation.getPropertyPath() );
}
@@ -286,8 +286,6 @@
public void testValidateValue() {
Validator validator = TestUtil.getValidator();
- Order order = new Order();
-
Set<ConstraintViolation<Customer>> constraintViolations = validator.validateValue(
Customer.class, "orderList[0].orderNumber", null
);
@@ -297,13 +295,115 @@
assertEquals( "Wrong number of constraints", 1, constraintViolations.size() );
assertEquals( "Wrong message", "may not be null", constraintViolation.getMessage() );
assertEquals( "Wrong root entity", null, constraintViolation.getRootBean() );
- assertEquals( "Wrong value", order.getOrderNumber(), constraintViolation.getInvalidValue() );
+ assertEquals( "Wrong value", null, constraintViolation.getInvalidValue() );
assertEquals( "Wrong propertyName", "orderList[0].orderNumber", constraintViolation.getPropertyPath() );
constraintViolations = validator.validateValue( Customer.class, "orderList[0].orderNumber", "1234" );
assertEquals( "Wrong number of constraints", 0, constraintViolations.size() );
}
+ @Test
+ public void testValidateValueWithInvalidPropertyPath() {
+ Validator validator = TestUtil.getValidator();
+
+ try {
+ validator.validateValue( Customer.class, "", null );
+ fail();
+ }
+ catch ( IllegalArgumentException e ) {
+ assertEquals( "Invalid property path.", e.getMessage() );
+ }
+
+ try {
+ validator.validateValue( Customer.class, "foobar", null );
+ fail();
+ }
+ catch ( IllegalArgumentException e ) {
+ assertEquals( "Invalid property path.", e.getMessage() );
+ }
+
+ try {
+ validator.validateValue( Customer.class, "orderList[0].foobar", null );
+ fail();
+ }
+ catch ( IllegalArgumentException e ) {
+ assertEquals( "Invalid property path.", e.getMessage() );
+ }
+ }
+
+ @Test
+ public void testValidateProperty() {
+ Validator validator = TestUtil.getValidator();
+
+ Customer customer = new Customer();
+ Order order = new Order();
+ customer.addOrder( order );
+
+ Set<ConstraintViolation<Customer>> constraintViolations = validator.validateProperty(
+ customer, "orderList[0].orderNumber"
+ );
+ assertEquals( "Wrong number of constraints", 1, constraintViolations.size() );
+
+ ConstraintViolation constraintViolation = constraintViolations.iterator().next();
+ assertEquals( "Wrong number of constraints", 1, constraintViolations.size() );
+ assertEquals( "Wrong message", "may not be null", constraintViolation.getMessage() );
+ assertEquals( "Wrong root entity", customer, constraintViolation.getRootBean() );
+ assertEquals( "Wrong value", order.getOrderNumber(), constraintViolation.getInvalidValue() );
+ assertEquals( "Wrong propertyName", "orderList[0].orderNumber", constraintViolation.getPropertyPath() );
+
+ order.setOrderNumber( 1234 );
+ constraintViolations = validator.validateProperty( customer, "orderList[0].orderNumber" );
+ assertEquals( "Wrong number of constraints", 0, constraintViolations.size() );
+
+ try {
+ constraintViolations = validator.validateProperty( customer, "orderList[1].orderNumber" );
+ }
+ catch ( IllegalArgumentException e ) {
+ assertEquals( "Invalid property path.", e.getMessage() );
+ }
+ }
+
+ @Test
+ public void testValidatePropertyWithInvalidPropertyPath() {
+ Validator validator = TestUtil.getValidator();
+
+ Customer customer = new Customer();
+ Order order = new Order();
+ customer.addOrder( order );
+
+ try {
+ validator.validateProperty( customer, "orderList[1].orderNumber" );
+ fail();
+ }
+ catch ( IllegalArgumentException e ) {
+ assertEquals( "Invalid property path.", e.getMessage() );
+ }
+
+ try {
+ validator.validateProperty( customer, "" );
+ fail();
+ }
+ catch ( IllegalArgumentException e ) {
+ assertEquals( "Invalid property path.", e.getMessage() );
+ }
+
+ try {
+ validator.validateProperty( customer, "foobar" );
+ fail();
+ }
+ catch ( IllegalArgumentException e ) {
+ assertEquals( "Invalid property path.", e.getMessage() );
+ }
+
+ try {
+ validator.validateProperty( customer, "orderList[0].foobar" );
+ fail();
+ }
+ catch ( IllegalArgumentException e ) {
+ assertEquals( "Invalid property path.", e.getMessage() );
+ }
+ }
+
/**
* HV-108
*/
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/GroupTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/GroupTest.java 2009-02-24 20:02:35 UTC (rev 16026)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/GroupTest.java 2009-02-24 20:36:01 UTC (rev 16027)
@@ -17,7 +17,6 @@
*/
package org.hibernate.validation.engine.groups;
-import java.util.HashSet;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.ValidationException;
15 years, 9 months
Hibernate SVN: r16026 - beanvalidation/trunk/validation-api/src/main/java/javax/validation.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2009-02-24 15:02:35 -0500 (Tue, 24 Feb 2009)
New Revision: 16026
Modified:
beanvalidation/trunk/validation-api/src/main/java/javax/validation/Configuration.java
beanvalidation/trunk/validation-api/src/main/java/javax/validation/MessageInterpolator.java
beanvalidation/trunk/validation-api/src/main/java/javax/validation/Validator.java
Log:
BVAL-52 define exception model
Modified: beanvalidation/trunk/validation-api/src/main/java/javax/validation/Configuration.java
===================================================================
--- beanvalidation/trunk/validation-api/src/main/java/javax/validation/Configuration.java 2009-02-24 15:58:29 UTC (rev 16025)
+++ beanvalidation/trunk/validation-api/src/main/java/javax/validation/Configuration.java 2009-02-24 20:02:35 UTC (rev 16026)
@@ -166,6 +166,7 @@
* Build a ValidatorFactory implementation.
*
* @return ValidatorFactory
+ * @throws ValidationException if the ValidatorFactory cannot be built
*/
ValidatorFactory buildValidatorFactory();
}
Modified: beanvalidation/trunk/validation-api/src/main/java/javax/validation/MessageInterpolator.java
===================================================================
--- beanvalidation/trunk/validation-api/src/main/java/javax/validation/MessageInterpolator.java 2009-02-24 15:58:29 UTC (rev 16025)
+++ beanvalidation/trunk/validation-api/src/main/java/javax/validation/MessageInterpolator.java 2009-02-24 20:02:35 UTC (rev 16026)
@@ -21,6 +21,7 @@
/**
* Interpolate a given constraint violation message.
+ * Implementations should be as tolerant as possible on syntax errors.
*
* @author Emmanuel Bernard
* @author Hardy Ferentschik
Modified: beanvalidation/trunk/validation-api/src/main/java/javax/validation/Validator.java
===================================================================
--- beanvalidation/trunk/validation-api/src/main/java/javax/validation/Validator.java 2009-02-24 15:58:29 UTC (rev 16025)
+++ beanvalidation/trunk/validation-api/src/main/java/javax/validation/Validator.java 2009-02-24 20:02:35 UTC (rev 16026)
@@ -24,7 +24,6 @@
*
* @author Emmanuel Bernard
* @author Hardy Ferentschik
- * @todo Should Serializable be part of the definition?
*/
public interface Validator {
/**
@@ -37,6 +36,8 @@
* @return constraint violations or an empty Set if none
*
* @throws IllegalArgumentException if object is null
+ * @throws ValidationException if a non recoverable error happens
+ * during the validation process
*/
<T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups);
@@ -52,6 +53,8 @@
*
* @throws IllegalArgumentException if object is null, if propertyName null, empty
* or not a valid object property
+ * @throws ValidationException if a non recoverable error happens
+ * during the validation process
*/
<T> Set<ConstraintViolation<T>> validateProperty(T object,
String propertyName,
@@ -72,6 +75,8 @@
* @return constraint violations or an empty Set if none
* @throws IllegalArgumentException if object is null, if propertyName null, empty
* or not a valid object property
+ * @throws ValidationException if a non recoverable error happens
+ * during the validation process
*/
<T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType,
String propertyName,
@@ -85,6 +90,9 @@
*
* @param clazz class type evaluated
* @return the bean descriptor for the specified class.
+ * @throws ValidationException if a non recoverable error happens
+ * during the metadata discovery or if some
+ * constraints are invalid.
*/
BeanDescriptor getConstraintsForClass(Class<?> clazz);
}
15 years, 9 months
Hibernate SVN: r16025 - beanvalidation/trunk/validation-api/src/main/java/javax/validation.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2009-02-24 10:58:29 -0500 (Tue, 24 Feb 2009)
New Revision: 16025
Modified:
beanvalidation/trunk/validation-api/src/main/java/javax/validation/Validator.java
Log:
BVAL-128 Clarify invalid cases for validateProperty / validateValue on proeprtyName being empty or null
Modified: beanvalidation/trunk/validation-api/src/main/java/javax/validation/Validator.java
===================================================================
--- beanvalidation/trunk/validation-api/src/main/java/javax/validation/Validator.java 2009-02-24 15:52:58 UTC (rev 16024)
+++ beanvalidation/trunk/validation-api/src/main/java/javax/validation/Validator.java 2009-02-24 15:58:29 UTC (rev 16025)
@@ -50,7 +50,8 @@
*
* @return constraint violations or an empty Set if none
*
- * @throws IllegalArgumentException if object is null or if propertyName is not present
+ * @throws IllegalArgumentException if object is null, if propertyName null, empty
+ * or not a valid object property
*/
<T> Set<ConstraintViolation<T>> validateProperty(T object,
String propertyName,
@@ -69,7 +70,8 @@
* (default to {@link javax.validation.groups.Default})
*
* @return constraint violations or an empty Set if none
- * @throws IllegalArgumentException if propertyName is not present
+ * @throws IllegalArgumentException if object is null, if propertyName null, empty
+ * or not a valid object property
*/
<T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType,
String propertyName,
15 years, 9 months
Hibernate SVN: r16024 - validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation and 2 other directories.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2009-02-24 10:52:58 -0500 (Tue, 24 Feb 2009)
New Revision: 16024
Added:
beanvalidation/trunk/validation-api/src/main/java/javax/validation/ConstraintDeclarationException.java
beanvalidation/trunk/validation-api/src/main/java/javax/validation/ConstraintDefinitionException.java
beanvalidation/trunk/validation-api/src/main/java/javax/validation/GroupDefinitionException.java
beanvalidation/trunk/validation-api/src/main/java/javax/validation/UnexpectedTypeException.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/AmbiguousConstraintUsageException.java
Removed:
beanvalidation/trunk/validation-api/src/main/java/javax/validation/AmbiguousConstraintUsageException.java
beanvalidation/trunk/validation-api/src/main/java/javax/validation/UnexpectedTypeForConstraintException.java
Modified:
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/GroupTest.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/validatorresolution/Bar.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/validatorresolution/ValidatorResolutionTest.java
Log:
BVAL-52 add exceptions classes
Deleted: beanvalidation/trunk/validation-api/src/main/java/javax/validation/AmbiguousConstraintUsageException.java
===================================================================
--- beanvalidation/trunk/validation-api/src/main/java/javax/validation/AmbiguousConstraintUsageException.java 2009-02-24 15:19:02 UTC (rev 16023)
+++ beanvalidation/trunk/validation-api/src/main/java/javax/validation/AmbiguousConstraintUsageException.java 2009-02-24 15:52:58 UTC (rev 16024)
@@ -1,44 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* 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 javax.validation;
-
-import javax.validation.ValidationException;
-
-/**
- * Exception raised in the case that the constraint validator resolution returns more than one possible validators for
- * a given type.
- *
- * @author Hardy Ferentschik
- */
-public class AmbiguousConstraintUsageException extends ValidationException {
- public AmbiguousConstraintUsageException(String message) {
- super( message );
- }
-
- public AmbiguousConstraintUsageException() {
- super();
- }
-
- public AmbiguousConstraintUsageException(String message, Throwable cause) {
- super( message, cause );
- }
-
- public AmbiguousConstraintUsageException(Throwable cause) {
- super( cause );
- }
-}
Added: beanvalidation/trunk/validation-api/src/main/java/javax/validation/ConstraintDeclarationException.java
===================================================================
--- beanvalidation/trunk/validation-api/src/main/java/javax/validation/ConstraintDeclarationException.java (rev 0)
+++ beanvalidation/trunk/validation-api/src/main/java/javax/validation/ConstraintDeclarationException.java 2009-02-24 15:52:58 UTC (rev 16024)
@@ -0,0 +1,24 @@
+package javax.validation;
+
+/**
+ * Exception raised if a constraint declaration is not legal
+ *
+ * @author Emmanuel Bernard
+ */
+public class ConstraintDeclarationException extends ValidationException {
+ public ConstraintDeclarationException(String message) {
+ super( message );
+ }
+
+ public ConstraintDeclarationException() {
+ super();
+ }
+
+ public ConstraintDeclarationException(String message, Throwable cause) {
+ super( message, cause );
+ }
+
+ public ConstraintDeclarationException(Throwable cause) {
+ super( cause );
+ }
+}
\ No newline at end of file
Added: beanvalidation/trunk/validation-api/src/main/java/javax/validation/ConstraintDefinitionException.java
===================================================================
--- beanvalidation/trunk/validation-api/src/main/java/javax/validation/ConstraintDefinitionException.java (rev 0)
+++ beanvalidation/trunk/validation-api/src/main/java/javax/validation/ConstraintDefinitionException.java 2009-02-24 15:52:58 UTC (rev 16024)
@@ -0,0 +1,24 @@
+package javax.validation;
+
+/**
+ * Exception raised if a constraint definition is not legal
+ *
+ * @author Emmanuel Bernard
+ */
+public class ConstraintDefinitionException extends ValidationException {
+ public ConstraintDefinitionException(String message) {
+ super( message );
+ }
+
+ public ConstraintDefinitionException() {
+ super();
+ }
+
+ public ConstraintDefinitionException(String message, Throwable cause) {
+ super( message, cause );
+ }
+
+ public ConstraintDefinitionException(Throwable cause) {
+ super( cause );
+ }
+}
\ No newline at end of file
Added: beanvalidation/trunk/validation-api/src/main/java/javax/validation/GroupDefinitionException.java
===================================================================
--- beanvalidation/trunk/validation-api/src/main/java/javax/validation/GroupDefinitionException.java (rev 0)
+++ beanvalidation/trunk/validation-api/src/main/java/javax/validation/GroupDefinitionException.java 2009-02-24 15:52:58 UTC (rev 16024)
@@ -0,0 +1,24 @@
+package javax.validation;
+
+/**
+ * Exception raised if a group definition is not legal
+ *
+ * @author Emmanuel Bernard
+ */
+public class GroupDefinitionException extends ValidationException {
+ public GroupDefinitionException(String message) {
+ super( message );
+ }
+
+ public GroupDefinitionException() {
+ super();
+ }
+
+ public GroupDefinitionException(String message, Throwable cause) {
+ super( message, cause );
+ }
+
+ public GroupDefinitionException(Throwable cause) {
+ super( cause );
+ }
+}
\ No newline at end of file
Copied: beanvalidation/trunk/validation-api/src/main/java/javax/validation/UnexpectedTypeException.java (from rev 16021, beanvalidation/trunk/validation-api/src/main/java/javax/validation/UnexpectedTypeForConstraintException.java)
===================================================================
--- beanvalidation/trunk/validation-api/src/main/java/javax/validation/UnexpectedTypeException.java (rev 0)
+++ beanvalidation/trunk/validation-api/src/main/java/javax/validation/UnexpectedTypeException.java 2009-02-24 15:52:58 UTC (rev 16024)
@@ -0,0 +1,44 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* 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 javax.validation;
+
+import javax.validation.ValidationException;
+
+/**
+ * Exception raised in the case that the constraint validator resolution
+ * cannot determine a suitable validators for a given type.
+ *
+ * @author Hardy Ferentschik
+ */
+public class UnexpectedTypeException extends ConstraintDeclarationException {
+ public UnexpectedTypeException(String message) {
+ super( message );
+ }
+
+ public UnexpectedTypeException() {
+ super();
+ }
+
+ public UnexpectedTypeException(String message, Throwable cause) {
+ super( message, cause );
+ }
+
+ public UnexpectedTypeException(Throwable cause) {
+ super( cause );
+ }
+}
\ No newline at end of file
Property changes on: beanvalidation/trunk/validation-api/src/main/java/javax/validation/UnexpectedTypeException.java
___________________________________________________________________
Name: svn:keywords
+ Id
Deleted: beanvalidation/trunk/validation-api/src/main/java/javax/validation/UnexpectedTypeForConstraintException.java
===================================================================
--- beanvalidation/trunk/validation-api/src/main/java/javax/validation/UnexpectedTypeForConstraintException.java 2009-02-24 15:19:02 UTC (rev 16023)
+++ beanvalidation/trunk/validation-api/src/main/java/javax/validation/UnexpectedTypeForConstraintException.java 2009-02-24 15:52:58 UTC (rev 16024)
@@ -1,44 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* 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 javax.validation;
-
-import javax.validation.ValidationException;
-
-/**
- * Exception raised in the case that the constraint validator resolution cannot determine a suitable validators for
- * a given type.
- *
- * @author Hardy Ferentschik
- */
-public class UnexpectedTypeForConstraintException extends ValidationException {
- public UnexpectedTypeForConstraintException(String message) {
- super( message );
- }
-
- public UnexpectedTypeForConstraintException() {
- super();
- }
-
- public UnexpectedTypeForConstraintException(String message, Throwable cause) {
- super( message, cause );
- }
-
- public UnexpectedTypeForConstraintException(Throwable cause) {
- super( cause );
- }
-}
\ No newline at end of file
Added: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/AmbiguousConstraintUsageException.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/AmbiguousConstraintUsageException.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/AmbiguousConstraintUsageException.java 2009-02-24 15:52:58 UTC (rev 16024)
@@ -0,0 +1,45 @@
+// $Id: AmbiguousConstraintUsageException.java 15902 2009-02-05 11:53:49Z hardy.ferentschik $
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* 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.hibernate.validation;
+
+import javax.validation.ValidationException;
+import javax.validation.UnexpectedTypeException;
+
+/**
+ * Exception raised in the case that the constraint validator resolution returns more than one possible validators for
+ * a given type.
+ *
+ * @author Hardy Ferentschik
+ */
+public class AmbiguousConstraintUsageException extends UnexpectedTypeException {
+ public AmbiguousConstraintUsageException(String message) {
+ super( message );
+ }
+
+ public AmbiguousConstraintUsageException() {
+ super();
+ }
+
+ public AmbiguousConstraintUsageException(String message, Throwable cause) {
+ super( message, cause );
+ }
+
+ public AmbiguousConstraintUsageException(Throwable cause) {
+ super( cause );
+ }
+}
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/GroupTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/GroupTest.java 2009-02-24 15:19:02 UTC (rev 16023)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/GroupTest.java 2009-02-24 15:52:58 UTC (rev 16024)
@@ -174,16 +174,6 @@
1,
constraintViolations.size()
);
-
- ConstraintViolation constraintViolation = constraintViolations.iterator().next();
- Set<Class<?>> expected = new HashSet<Class<?>>();
- expected.add( First.class );
- expected.add( Second.class );
- assertEquals(
- "The constraint should be invalid for both groups",
- expected,
- constraintViolation.getGroups()
- );
}
@Test
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/validatorresolution/Bar.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/validatorresolution/Bar.java 2009-02-24 15:19:02 UTC (rev 16023)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/validatorresolution/Bar.java 2009-02-24 15:52:58 UTC (rev 16024)
@@ -23,7 +23,7 @@
* @author Hardy Ferentschik
*/
public class Bar {
- // validating Bar actually raises an UnexpectedTypeForConstraintException - @Size is not defined for Integer
+ // validating Bar actually raises an UnexpectedTypeException - @Size is not defined for Integer
@Size
private Integer value = 0;
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/validatorresolution/ValidatorResolutionTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/validatorresolution/ValidatorResolutionTest.java 2009-02-24 15:19:02 UTC (rev 16023)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/validatorresolution/ValidatorResolutionTest.java 2009-02-24 15:52:58 UTC (rev 16024)
@@ -18,10 +18,10 @@
package org.hibernate.validation.engine.validatorresolution;
import java.util.Set;
-import javax.validation.AmbiguousConstraintUsageException;
+import org.hibernate.validation.AmbiguousConstraintUsageException;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
-import javax.validation.UnexpectedTypeForConstraintException;
+import javax.validation.UnexpectedTypeException;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
@@ -72,7 +72,7 @@
validator.validate( bar );
fail();
}
- catch ( UnexpectedTypeForConstraintException e ) {
+ catch ( UnexpectedTypeException e ) {
assertEquals( "No validator could be found for type: java.lang.Integer", e.getMessage() );
}
}
15 years, 9 months
Hibernate SVN: r16023 - validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2009-02-24 10:19:02 -0500 (Tue, 24 Feb 2009)
New Revision: 16023
Modified:
beanvalidation/trunk/validation-api/src/main/java/javax/validation/ConstraintViolation.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintViolationImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ExecutionContext.java
Log:
BVAL-127 remove ConstraintViolation.getGroups()
Modified: beanvalidation/trunk/validation-api/src/main/java/javax/validation/ConstraintViolation.java
===================================================================
--- beanvalidation/trunk/validation-api/src/main/java/javax/validation/ConstraintViolation.java 2009-02-24 14:58:57 UTC (rev 16022)
+++ beanvalidation/trunk/validation-api/src/main/java/javax/validation/ConstraintViolation.java 2009-02-24 15:19:02 UTC (rev 16023)
@@ -66,14 +66,6 @@
Object getInvalidValue();
/**
- * @return the list of groups that the triggered constraint applies on and which also are
- * within the list of groups requested for validation.
- *
- * TODO: considering removal, if you think it's important, speak up
- */
- Set<Class<?>> getGroups();
-
- /**
* Constraint metadata reported to fail.
* The returned instance is immutable.
*
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java 2009-02-24 14:58:57 UTC (rev 16022)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java 2009-02-24 15:19:02 UTC (rev 16023)
@@ -22,11 +22,11 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-import javax.validation.AmbiguousConstraintUsageException;
+import org.hibernate.validation.AmbiguousConstraintUsageException;
import javax.validation.ConstraintDescriptor;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorFactory;
-import javax.validation.UnexpectedTypeForConstraintException;
+import javax.validation.UnexpectedTypeException;
import javax.validation.ValidationException;
import org.slf4j.Logger;
@@ -138,7 +138,6 @@
leafBeanInstance,
value,
executionContext.peekPropertyPath(), //FIXME use error.getProperty()
- executionContext.getCurrentGroup(),
descriptor
);
constraintViolations.add( failingConstraintViolation );
@@ -187,7 +186,7 @@
private void verifyResolveWasUnique(Class valueClass, List<Class> assignableClasses) {
if ( assignableClasses.size() == 0 ) {
- throw new UnexpectedTypeForConstraintException( "No validator could be found for type: " + valueClass.getName() );
+ throw new UnexpectedTypeException( "No validator could be found for type: " + valueClass.getName() );
}
else if ( assignableClasses.size() > 1 ) {
StringBuilder builder = new StringBuilder();
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintViolationImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintViolationImpl.java 2009-02-24 14:58:57 UTC (rev 16022)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintViolationImpl.java 2009-02-24 15:19:02 UTC (rev 16023)
@@ -32,7 +32,6 @@
private Class<T> beanClass;
private Object value;
private String propertyPath;
- private Set<Class<?>> groups;
private Object leafBeanInstance;
private final ConstraintDescriptor constraintDescriptor;
private String rawMessage;
@@ -40,15 +39,13 @@
public ConstraintViolationImpl(String messageTemplate, String interpolatedMessage, T rootBean, Class<T> beanClass,
Object leafBeanInstance, Object value,
- String propertyPath, Class<?> group, ConstraintDescriptor constraintDescriptor) {
+ String propertyPath, ConstraintDescriptor constraintDescriptor) {
this.rawMessage = messageTemplate;
this.interpolatedMessage = interpolatedMessage;
this.rootBean = rootBean;
this.beanClass = beanClass;
this.value = value;
this.propertyPath = propertyPath;
- groups = new HashSet<Class<?>>();
- groups.add( group );
this.leafBeanInstance = leafBeanInstance;
this.constraintDescriptor = constraintDescriptor;
}
@@ -89,21 +86,10 @@
return propertyPath;
}
- /**
- * {@inheritDoc}
- */
- public Set<Class<?>> getGroups() {
- return groups;
- }
-
public ConstraintDescriptor getConstraintDescriptor() {
return this.constraintDescriptor;
}
- public void addGroups(Set<Class<?>> groupSet) {
- groups.addAll( groupSet );
- }
-
@Override
public boolean equals(Object o) {
if ( this == o ) {
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ExecutionContext.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ExecutionContext.java 2009-02-24 14:58:57 UTC (rev 16022)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ExecutionContext.java 2009-02-24 15:19:02 UTC (rev 16023)
@@ -155,9 +155,6 @@
if ( i == -1 ) {
failingConstraintViolations.add( failingConstraintViolation );
}
- else {
- failingConstraintViolations.get( i ).addGroups( failingConstraintViolation.getGroups() );
- }
}
public void addConstraintFailures(List<ConstraintViolationImpl<T>> failingConstraintViolations) {
15 years, 9 months
Hibernate SVN: r16022 - in validator/trunk/hibernate-validator/src: test/java/org/hibernate/validation/eg and 2 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-02-24 09:58:57 -0500 (Tue, 24 Feb 2009)
New Revision: 16022
Added:
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/AddressWithInvalidGroupSequence.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/ZipCodeCoherenceValidator.java
Removed:
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/ZipCode.java
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaData.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ExecutionContext.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/eg/Dictonary.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolatorTest.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/Address.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/GroupTest.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/ZipCodeCoherenceChecker.java
Log:
HV-113 Implemented redefining of default group for validate()
HV-123 Fixed typo
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaData.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaData.java 2009-02-23 10:17:40 UTC (rev 16021)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaData.java 2009-02-24 14:58:57 UTC (rev 16022)
@@ -61,7 +61,7 @@
/**
* @return A map mapping defined group sequences to a list of groups.
*/
- List<Class<?>> getDefaultGroupList();
+ List<Class<?>> getDefaultGroupSequence();
/**
* @return A list of <code>MetaConstraint</code> instances encapsulating the information of all the constraints
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataImpl.java 2009-02-23 10:17:40 UTC (rev 16021)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataImpl.java 2009-02-24 14:58:57 UTC (rev 16022)
@@ -22,10 +22,10 @@
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.Arrays;
import javax.validation.BeanDescriptor;
import javax.validation.GroupSequence;
import javax.validation.PropertyDescriptor;
@@ -77,14 +77,13 @@
/**
* Maps field and method names to their <code>ElementDescriptorImpl</code>.
- * FIXME This model is problematic as you can have conflicting names for fields and methods
*/
private Map<String, PropertyDescriptor> propertyDescriptors = new HashMap<String, PropertyDescriptor>();
/**
* Maps group sequences to the list of group/sequences.
*/
- private List<Class<?>> defaultGroupList = new ArrayList<Class<?>>();
+ private List<Class<?>> defaultGroupSequence = new ArrayList<Class<?>>();
private final BuiltinConstraints builtinConstraints;
@@ -135,13 +134,37 @@
initFieldConstraints( clazz );
}
+ /**
+ * Checks whether there is a default group sequence defined for this class.
+ * See HV-113.
+ *
+ * @param clazz The class to check for the <code>GroupSequence</code> annotation.
+ */
private void initDefaultGroupSequence(Class<?> clazz) {
GroupSequence groupSequenceAnnotation = clazz.getAnnotation( GroupSequence.class );
if ( groupSequenceAnnotation == null ) {
- defaultGroupList.add( Default.class );
+ defaultGroupSequence.add( Default.class );
}
else {
- defaultGroupList.addAll( Arrays.asList( groupSequenceAnnotation.value() ) );
+ List<Class<?>> groupSequenceList = Arrays.asList( groupSequenceAnnotation.value() );
+ for ( Class<?> group : groupSequenceList ) {
+ if ( group.getName().equals( clazz.getName() ) ) {
+ defaultGroupSequence.add( Default.class );
+ }
+ else if ( group.getName().equals( Default.class.getName() ) ) {
+ throw new ValidationException( "'Default.class' cannot appear in default group sequence list." );
+ }
+ else {
+ defaultGroupSequence.add( group );
+ }
+ }
+ if ( log.isDebugEnabled() ) {
+ log.debug(
+ "Bean {} redefines the Default group. Members of the default group sequence are: {}",
+ clazz.getName(),
+ defaultGroupSequence
+ );
+ }
}
}
@@ -150,7 +173,7 @@
List<ConstraintDescriptorImpl> fieldMetadata = findFieldLevelConstraints( field );
for ( ConstraintDescriptorImpl constraintDescription : fieldMetadata ) {
ReflectionHelper.setAccessibility( field );
- MetaConstraint metaConstraint = new MetaConstraint( field, constraintDescription, new ArrayList<Class<?>>(defaultGroupList) );
+ MetaConstraint metaConstraint = new MetaConstraint( field, constraintDescription );
metaConstraintList.add( metaConstraint );
}
if ( field.isAnnotationPresent( Valid.class ) ) {
@@ -165,7 +188,7 @@
List<ConstraintDescriptorImpl> methodMetadata = findMethodLevelConstraints( method );
for ( ConstraintDescriptorImpl constraintDescription : methodMetadata ) {
ReflectionHelper.setAccessibility( method );
- MetaConstraint metaConstraint = new MetaConstraint( method, constraintDescription, new ArrayList<Class<?>>(defaultGroupList) );
+ MetaConstraint metaConstraint = new MetaConstraint( method, constraintDescription );
metaConstraintList.add( metaConstraint );
}
if ( method.isAnnotationPresent( Valid.class ) ) {
@@ -178,7 +201,7 @@
private void initClassConstraints(Class clazz) {
List<ConstraintDescriptorImpl> classMetadata = findClassLevelConstraints( clazz );
for ( ConstraintDescriptorImpl constraintDescription : classMetadata ) {
- MetaConstraint metaConstraint = new MetaConstraint( clazz, constraintDescription, new ArrayList<Class<?>>(defaultGroupList) );
+ MetaConstraint metaConstraint = new MetaConstraint( clazz, constraintDescription );
metaConstraintList.add( metaConstraint );
}
}
@@ -323,10 +346,6 @@
return cascadedMembers;
}
- public List<Class<?>> getDefaultGroupList() {
- return defaultGroupList;
- }
-
public List<MetaConstraint> geMetaConstraintList() {
return metaConstraintList;
}
@@ -338,4 +357,8 @@
public PropertyDescriptor getPropertyDescriptors(String property) {
return propertyDescriptors.get( property );
}
+
+ public List<Class<?>> getDefaultGroupSequence() {
+ return defaultGroupSequence;
+ }
}
\ No newline at end of file
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java 2009-02-23 10:17:40 UTC (rev 16021)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java 2009-02-24 14:58:57 UTC (rev 16022)
@@ -83,9 +83,9 @@
return descriptor;
}
- public void validateConstraints(Object value, Class beanClass, ExecutionContext executionContext) {
+ public <T> void validateConstraints(Object value, Class beanClass, ExecutionContext executionContext, List<ConstraintViolationImpl<T>> constraintViolations) {
for ( ConstraintTree tree : getChildren() ) {
- tree.validateConstraints( value, beanClass, executionContext );
+ tree.validateConstraints( value, beanClass, executionContext, constraintViolations );
}
final Object leafBeanInstance = executionContext.peekValidatedObject();
@@ -99,15 +99,22 @@
if ( !validator.isValid( value, constraintContext ) ) {
for ( ConstraintValidatorContextImpl.ErrorMessage error : constraintContext.getErrorMessages() ) {
final String message = error.getMessage();
- createConstraintViolation( value, beanClass, executionContext, leafBeanInstance, message, descriptor );
+ createConstraintViolation(
+ value, beanClass, executionContext, leafBeanInstance, message, descriptor, constraintViolations
+ );
}
}
- if ( reportAsSingleViolation()
- && executionContext.getFailingConstraints().size() > 0 ) {
- executionContext.clearFailingConstraints();
+ if ( reportAsSingleViolation() && constraintViolations.size() > 0 ) {
+ constraintViolations.clear();
final String message = ( String ) getParent().getDescriptor().getParameters().get( "message" );
createConstraintViolation(
- value, beanClass, executionContext, leafBeanInstance, message, getParent().descriptor
+ value,
+ beanClass,
+ executionContext,
+ leafBeanInstance,
+ message,
+ getParent().descriptor,
+ constraintViolations
);
}
}
@@ -117,7 +124,7 @@
&& getParent().getDescriptor().isReportAsSingleViolation();
}
- private <T> void createConstraintViolation(Object value, Class<T> beanClass, ExecutionContext<T> executionContext, Object leafBeanInstance, String messageTemplate, ConstraintDescriptor descriptor) {
+ private <T> void createConstraintViolation(Object value, Class<T> beanClass, ExecutionContext<T> executionContext, Object leafBeanInstance, String messageTemplate, ConstraintDescriptor descriptor, List<ConstraintViolationImpl<T>> constraintViolations) {
String interpolatedMessage = executionContext.getMessageResolver().interpolate(
messageTemplate,
descriptor,
@@ -134,7 +141,7 @@
executionContext.getCurrentGroup(),
descriptor
);
- executionContext.addConstraintFailure( failingConstraintViolation );
+ constraintViolations.add( failingConstraintViolation );
}
/**
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ExecutionContext.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ExecutionContext.java 2009-02-23 10:17:40 UTC (rev 16021)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ExecutionContext.java 2009-02-24 14:58:57 UTC (rev 16022)
@@ -71,8 +71,8 @@
/**
* Stack for keeping track of the currently validated object.
*/
- private Stack<ValidatedBean> validatedObjectStack = new Stack<ValidatedBean>();
-
+ private Stack<Object> validatedObjectStack = new Stack<Object>();
+
/**
* The message resolver which should be used in this context.
*/
@@ -92,7 +92,7 @@
this.rootBean = rootBean;
this.messageResolver = messageResolver;
this.constraintValidatorFactory = constraintValidatorFactory;
- validatedObjectStack.push( new ValidatedBean( object ) );
+ validatedObjectStack.push( object );
processedObjects = new HashMap<Class<?>, IdentitySet>();
propertyPath = "";
failingConstraintViolations = new ArrayList<ConstraintViolationImpl<T>>();
@@ -107,15 +107,15 @@
}
public Object peekValidatedObject() {
- return validatedObjectStack.peek().bean;
+ return validatedObjectStack.peek();
}
public Class<?> peekValidatedObjectType() {
- return validatedObjectStack.peek().beanType;
+ return validatedObjectStack.peek().getClass();
}
public void pushValidatedObject(Object validatedObject) {
- validatedObjectStack.push( new ValidatedBean( validatedObject ) );
+ validatedObjectStack.push( validatedObject );
}
public void popValidatedObject() {
@@ -136,11 +136,11 @@
public void markProcessedForCurrentGroup() {
if ( processedObjects.containsKey( currentGroup ) ) {
- processedObjects.get( currentGroup ).add( validatedObjectStack.peek().bean );
+ processedObjects.get( currentGroup ).add( validatedObjectStack.peek() );
}
else {
IdentitySet set = new IdentitySet();
- set.add( validatedObjectStack.peek().bean );
+ set.add( validatedObjectStack.peek() );
processedObjects.put( currentGroup, set );
}
}
@@ -160,6 +160,12 @@
}
}
+ public void addConstraintFailures(List<ConstraintViolationImpl<T>> failingConstraintViolations) {
+ for(ConstraintViolationImpl<T> violation : failingConstraintViolations) {
+ addConstraintFailure( violation );
+ }
+ }
+
public List<ConstraintViolationImpl<T>> getFailingConstraints() {
return failingConstraintViolations;
}
@@ -207,26 +213,7 @@
return propertyPath;
}
- public boolean needsValidation(Collection<Class<?>> groups) {
+ public boolean checkValidationRequired(Collection<Class<?>> groups) {
return groups.contains( currentGroup );
}
-
- /**
- * @todo Is it useful to cache the object class?
- */
- private static class ValidatedBean {
-
- final Object bean;
- final Class<?> beanType;
-
- private ValidatedBean(Object bean) {
- this.bean = bean;
- if ( bean == null ) {
- this.beanType = null;
- }
- else {
- this.beanType = bean.getClass();
- }
- }
- }
}
\ No newline at end of file
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java 2009-02-23 10:17:40 UTC (rev 16021)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java 2009-02-24 14:58:57 UTC (rev 16022)
@@ -23,9 +23,9 @@
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
+import java.util.Set;
import javax.validation.ConstraintDescriptor;
import javax.validation.ValidationException;
-import javax.validation.groups.Default;
import org.hibernate.validation.util.ReflectionHelper;
@@ -71,54 +71,41 @@
*/
private final ElementType elementType;
- private final List<Class<?>> groupList;
-
- public MetaConstraint(Type t, ConstraintDescriptor constraintDescriptor, List<Class<?>> defaultGroupList) {
- this( t, null, null, ElementType.FIELD, constraintDescriptor, "", defaultGroupList );
+ public MetaConstraint(Type t, ConstraintDescriptor constraintDescriptor) {
+ this( t, null, null, ElementType.TYPE, constraintDescriptor, "" );
}
- public MetaConstraint(Method m, ConstraintDescriptor constraintDescriptor, List<Class<?>> defaultGroupList) {
+ public MetaConstraint(Method m, ConstraintDescriptor constraintDescriptor) {
this(
null,
m,
null,
ElementType.METHOD,
constraintDescriptor,
- ReflectionHelper.getPropertyName( m ),
- defaultGroupList
+ ReflectionHelper.getPropertyName( m )
);
}
- public MetaConstraint(Field f, ConstraintDescriptor constraintDescriptor, List<Class<?>> defaultGroupList) {
- this( null, null, f, ElementType.FIELD, constraintDescriptor, f.getName(), defaultGroupList );
+ public MetaConstraint(Field f, ConstraintDescriptor constraintDescriptor) {
+ this( null, null, f, ElementType.FIELD, constraintDescriptor, f.getName());
}
- private MetaConstraint(Type t, Method m, Field f, ElementType elementType, ConstraintDescriptor constraintDescriptor, String property, List<Class<?>> defaultGroupList) {
+ private MetaConstraint(Type t, Method m, Field f, ElementType elementType, ConstraintDescriptor constraintDescriptor, String property) {
this.type = t;
this.method = m;
this.field = f;
this.elementType = elementType;
this.propertyName = property;
constraintTree = new ConstraintTree( constraintDescriptor );
- this.groupList = new ArrayList<Class<?>>( constraintDescriptor.getGroups() );
- checkIfPartOfDefaultGroup( defaultGroupList );
}
- private void checkIfPartOfDefaultGroup(List<Class<?>> defaultGroupList) {
- for ( Class<?> clazz : defaultGroupList ) {
- if ( groupList.contains( clazz ) ) {
- groupList.add( Default.class );
- break;
- }
- }
- }
/**
* @return Returns the list of groups this constraint is part of. This might include the default group even when
- * it is not explicitly specified, but part of the redefined default group list of the hosting bean.
+ * it is not explicitly specified, but part of the redefined default group list of the hosting bean.
*/
- public List<Class<?>> getGroupList() {
- return groupList;
+ public Set<Class<?>> getGroupList() {
+ return constraintTree.getDescriptor().getGroups();
}
/**
@@ -192,14 +179,26 @@
return constraintTree;
}
- public <T> void validateConstraint(Class beanClass, ExecutionContext<T> executionContext) {
+ public <T> boolean validateConstraint(Class beanClass, ExecutionContext<T> executionContext) {
final Object leafBeanInstance = executionContext.peekValidatedObject();
Object value = getValue( leafBeanInstance );
- constraintTree.validateConstraints( value, beanClass, executionContext );
+ List<ConstraintViolationImpl<T>> constraintViolations = new ArrayList<ConstraintViolationImpl<T>>();
+ constraintTree.validateConstraints( value, beanClass, executionContext, constraintViolations );
+ if ( constraintViolations.size() > 0 ) {
+ executionContext.addConstraintFailures( constraintViolations );
+ return false;
+ }
+ return true;
}
- public <T> void validateConstraint(Class beanClass, Object value, ExecutionContext<T> executionContext) {
- constraintTree.validateConstraints( value, beanClass, executionContext );
+ public <T> boolean validateConstraint(Class beanClass, Object value, ExecutionContext<T> executionContext) {
+ List<ConstraintViolationImpl<T>> constraintViolations = new ArrayList<ConstraintViolationImpl<T>>();
+ constraintTree.validateConstraints( value, beanClass, executionContext, constraintViolations );
+ if ( constraintViolations.size() > 0 ) {
+ executionContext.addConstraintFailures( constraintViolations );
+ return false;
+ }
+ return true;
}
private Type typeOfAnnoatedElement() {
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java 2009-02-23 10:17:40 UTC (rev 16021)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java 2009-02-24 14:58:57 UTC (rev 16022)
@@ -35,9 +35,12 @@
import javax.validation.Validator;
import javax.validation.groups.Default;
+import org.slf4j.Logger;
+
import org.hibernate.validation.engine.groups.Group;
import org.hibernate.validation.engine.groups.GroupChain;
import org.hibernate.validation.engine.groups.GroupChainGenerator;
+import org.hibernate.validation.util.LoggerFactory;
import org.hibernate.validation.util.PropertyIterator;
import org.hibernate.validation.util.ReflectionHelper;
@@ -49,6 +52,8 @@
* @todo Make all properties transient for serializability.
*/
public class ValidatorImpl implements Validator {
+ private static final Logger log = LoggerFactory.make();
+
/**
* Set of classes which can be used as index in a map.
*/
@@ -163,13 +168,14 @@
GroupChain groupChain = groupChainGenerator.getGroupChainFor( groups );
while ( groupChain.hasNext() ) {
+ int numberOfViolations = context.getFailingConstraints().size();
Group group = groupChain.next();
context.setCurrentGroup( group.getGroup() );
validateConstraints( context );
validateCascadedConstraints( context );
- if ( groupChain.inSequence() && context.getFailingConstraints().size() > 0 ) {
+ if ( groupChain.inSequence() && context.getFailingConstraints().size() > numberOfViolations ) {
groupChain.moveToLastInCurrentSequence();
}
}
@@ -186,19 +192,46 @@
@SuppressWarnings("unchecked")
BeanMetaData<T> beanMetaData =
( BeanMetaData<T> ) getBeanMetaData( executionContext.peekValidatedObjectType() );
+ if ( executionContext.getCurrentGroup().getName().equals( Default.class.getName() ) ) {
+ List<Class<?>> defaultGroupSequence = beanMetaData.getDefaultGroupSequence();
+ if ( log.isDebugEnabled() && defaultGroupSequence.size() > 0 ) {
+ log.debug(
+ "Executing redefined Default group for bean {} as sequence {}",
+ beanMetaData.getBeanClass().getName(),
+ defaultGroupSequence
+ );
+ }
+ for ( Class<?> defaultSequenceMember : defaultGroupSequence ) {
+ executionContext.setCurrentGroup( defaultSequenceMember );
+ boolean validationSuccessful = validateConstraintsForBean( executionContext, beanMetaData );
+ if ( !validationSuccessful ) {
+ if ( log.isDebugEnabled() ) {
+ log.debug(
+ "Aborting validation of Default group sequence for {} due to constraint violation.",
+ beanMetaData.getBeanClass().getName()
+ );
+ }
+ break;
+ }
+ }
+ }
+ else {
+ validateConstraintsForBean( executionContext, beanMetaData );
+ }
+ }
+
+ private <T> boolean validateConstraintsForBean(ExecutionContext<T> executionContext, BeanMetaData<T> beanMetaData) {
+ boolean validationSuccessful = true;
for ( MetaConstraint metaConstraint : beanMetaData.geMetaConstraintList() ) {
-
executionContext.pushProperty( metaConstraint.getPropertyName() );
-
- if ( !executionContext.needsValidation( metaConstraint.getGroupList() ) ) {
- executionContext.popProperty();
- continue;
+ if ( executionContext.checkValidationRequired( metaConstraint.getGroupList() ) ) {
+ boolean tmp = metaConstraint.validateConstraint( beanMetaData.getBeanClass(), executionContext );
+ validationSuccessful = validationSuccessful && tmp;
}
-
- metaConstraint.validateConstraint( beanMetaData.getBeanClass(), executionContext );
executionContext.popProperty();
}
executionContext.markProcessedForCurrentGroup();
+ return validationSuccessful;
}
private <T> void validateCascadedConstraints(ExecutionContext<T> context) {
@@ -306,6 +339,7 @@
ExecutionContext<T> context = new ExecutionContext<T>(
object, messageInterpolator, constraintValidatorFactory
);
+ context.pushProperty( propertyIter.getOriginalProperty() );
metaConstraint.validateConstraint( object.getClass(), context );
failingConstraintViolations.addAll( context.getFailingConstraints() );
}
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/eg/Dictonary.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/eg/Dictonary.java 2009-02-23 10:17:40 UTC (rev 16021)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/eg/Dictonary.java 2009-02-24 14:58:57 UTC (rev 16022)
@@ -26,7 +26,6 @@
/**
* @author Hardy Ferentschik
*/
-@GroupSequence(value = { Default.class })
public class Dictonary extends Book {
@NotNull(groups = Translate.class)
@NotEmpty(groups = Translate.class)
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolatorTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolatorTest.java 2009-02-23 10:17:40 UTC (rev 16021)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolatorTest.java 2009-02-24 14:58:57 UTC (rev 16022)
@@ -115,7 +115,7 @@
ConstraintDescriptorImpl<Size> sizeDescriptor = new ConstraintDescriptorImpl<Size>(
size, new Class<?>[] { }, new BuiltinConstraints()
);
- expected = "size must be between -2147483648 and 2147483647"; // unkown token {}
+ expected = "size must be between 0 and 2147483647"; // unkown token {}
actual = interpolator.interpolate( size.message(), sizeDescriptor, null );
assertEquals( "Wrong substitution", expected, actual );
}
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java 2009-02-23 10:17:40 UTC (rev 16021)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java 2009-02-24 14:58:57 UTC (rev 16022)
@@ -102,6 +102,7 @@
}
@Test
+ @SuppressWarnings( "NullArgumentToVariableArgMethod")
public void testPassingNullAsGroup() {
Validator validator = TestUtil.getValidator();
Customer customer = new Customer();
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/Address.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/Address.java 2009-02-23 10:17:40 UTC (rev 16021)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/Address.java 2009-02-24 14:58:57 UTC (rev 16022)
@@ -1,35 +1,64 @@
package org.hibernate.validation.engine.groups;
+import javax.validation.GroupSequence;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
-import javax.validation.GroupSequence;
import javax.validation.groups.Default;
/**
* @author Emmanuel Bernard
*/
+@GroupSequence({ Address.class, Address.HighLevelCoherence.class })
@ZipCodeCoherenceChecker(groups = Address.HighLevelCoherence.class)
public class Address {
- @NotNull @Size(max = 50)
- private String street1;
+ @NotNull
+ @Size(max = 50)
+ private String street;
- @ZipCode
+ @NotNull
+ @Size(max = 5)
private String zipcode;
@NotNull
@Size(max = 30)
private String city;
+ public String getStreet() {
+ return street;
+ }
+
+ public void setStreet(String street) {
+ this.street = street;
+ }
+
+ public String getZipcode() {
+ return zipcode;
+ }
+
+ public void setZipcode(String zipcode) {
+ this.zipcode = zipcode;
+ }
+
+ public String getCity() {
+ return city;
+ }
+
+ public void setCity(String city) {
+ this.city = city;
+ }
+
/**
* Check conherence on the overall object
* Needs basic checking to be green first
*/
- public interface HighLevelCoherence {}
+ public interface HighLevelCoherence {
+ }
/**
* Check both basic constraints and high level ones.
* High level constraints are not checked if basic constraints fail.
*/
- @GroupSequence(value = {Default.class, HighLevelCoherence.class})
- public interface Complete {}
+ @GroupSequence(value = { Default.class, HighLevelCoherence.class })
+ public interface Complete {
+ }
}
\ No newline at end of file
Copied: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/AddressWithInvalidGroupSequence.java (from rev 16021, validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/Address.java)
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/AddressWithInvalidGroupSequence.java (rev 0)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/AddressWithInvalidGroupSequence.java 2009-02-24 14:58:57 UTC (rev 16022)
@@ -0,0 +1,12 @@
+package org.hibernate.validation.engine.groups;
+
+import javax.validation.GroupSequence;
+import javax.validation.groups.Default;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@GroupSequence({ Default.class, AddressWithInvalidGroupSequence.HighLevelCoherence.class })
+public class AddressWithInvalidGroupSequence extends Address {
+
+}
\ No newline at end of file
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/GroupTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/GroupTest.java 2009-02-23 10:17:40 UTC (rev 16021)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/GroupTest.java 2009-02-24 14:58:57 UTC (rev 16022)
@@ -18,12 +18,13 @@
package org.hibernate.validation.engine.groups;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.Set;
import javax.validation.ConstraintViolation;
+import javax.validation.ValidationException;
import javax.validation.Validator;
import javax.validation.groups.Default;
+import static junit.framework.Assert.fail;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
@@ -38,8 +39,6 @@
import org.hibernate.validation.util.TestUtil;
import static org.hibernate.validation.util.TestUtil.assertConstraintViolation;
-import static junit.framework.Assert.fail;
-
/**
* Tests for the group and group sequence feature.
*
@@ -78,8 +77,8 @@
book.setSubtitle( "Revised Edition of Hibernate in Action" );
constraintViolations = validator.validate( book, First.class, Second.class, Last.class );
+ assertEquals( "Wrong number of constraints", 1, constraintViolations.size() );
constraintViolation = constraintViolations.iterator().next();
- assertEquals( "Wrong number of constraints", 1, constraintViolations.size() );
assertEquals( "Wrong message", "length must be between 0 and 30", constraintViolation.getMessage() );
assertEquals( "Wrong root entity", book, constraintViolation.getRootBean() );
assertEquals( "Wrong value", book.getSubtitle(), constraintViolation.getInvalidValue() );
@@ -280,21 +279,19 @@
constraintViolations.size()
);
- Iterator<ConstraintViolation<User>> iter = constraintViolations.iterator();
- while ( iter.hasNext() ) {
- ConstraintViolation<User> violation = iter.next();
- if ( violation.getPropertyPath().equals( "defaultCreditCard" ) ) {
+ for ( ConstraintViolation<User> constraintViolation : constraintViolations ) {
+ if ( constraintViolation.getPropertyPath().equals( "defaultCreditCard" ) ) {
assertConstraintViolation(
- violation,
+ constraintViolation,
"may not be null",
User.class,
null,
"defaultCreditCard"
);
}
- else if ( violation.getPropertyPath().equals( "phoneNumber" ) ) {
+ else if ( constraintViolation.getPropertyPath().equals( "phoneNumber" ) ) {
assertConstraintViolation(
- violation,
+ constraintViolation,
"must match \"[0-9 -]?\"",
User.class,
"+46 123-456",
@@ -306,4 +303,57 @@
}
}
}
+
+ /**
+ * HV-113
+ */
+ @Test
+ public void testRedefiningDefaultGroup() {
+ Address address = new Address();
+ address.setStreet( "Guldmyntgatan" );
+ address.setCity( "Gothenborg" );
+
+ Validator validator = TestUtil.getValidator();
+
+ Set<ConstraintViolation<Address>> constraintViolations = validator.validate( address );
+ assertEquals(
+ "There should only be one violation for zipcode",
+ 1,
+ constraintViolations.size()
+ );
+
+ ConstraintViolation<Address> violation = constraintViolations.iterator().next();
+ assertConstraintViolation( violation, "may not be null", address.getClass(), null, "zipcode" );
+
+ address.setZipcode( "41841" );
+
+ // now the second group in the re-defined default group causes an error
+ constraintViolations = validator.validate( address );
+ assertEquals(
+ "There should only be one violation for zipcode",
+ 1,
+ constraintViolations.size()
+ );
+
+ violation = constraintViolations.iterator().next();
+ assertConstraintViolation( violation, "{validator.zipCodeCoherenceChecker}", address.getClass(), address, "" );
+ }
+
+ /**
+ * HV-113
+ */
+ @Test
+ public void testInvalidRedefinitionOfDefaultGroup() {
+ Address address = new AddressWithInvalidGroupSequence();
+ Validator validator = TestUtil.getValidator();
+ try {
+ validator.validate( address );
+ fail( "It shoud not be allowed to have Default.class in the group sequence of a class." );
+ }
+ catch ( ValidationException e ) {
+ assertEquals(
+ "Wrong message", "'Default.class' cannot appear in default group sequence list.", e.getMessage()
+ );
+ }
+ }
}
\ No newline at end of file
Deleted: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/ZipCode.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/ZipCode.java 2009-02-23 10:17:40 UTC (rev 16021)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/ZipCode.java 2009-02-24 14:58:57 UTC (rev 16022)
@@ -1,7 +0,0 @@
-package org.hibernate.validation.engine.groups;
-
-/**
- * @author Emmanuel Bernard
- */
-public @interface ZipCode {
-}
\ No newline at end of file
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/ZipCodeCoherenceChecker.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/ZipCodeCoherenceChecker.java 2009-02-23 10:17:40 UTC (rev 16021)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/ZipCodeCoherenceChecker.java 2009-02-24 14:58:57 UTC (rev 16022)
@@ -6,13 +6,17 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
+import javax.validation.Constraint;
+import org.hibernate.validation.constraints.PatternValidator;
+
/**
* @author Emmanuel Bernard
*/
@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Documented
+@Constraint(validatedBy = ZipCodeCoherenceValidator.class)
public @interface ZipCodeCoherenceChecker {
public abstract String message() default "{validator.zipCodeCoherenceChecker}";
public abstract Class<?>[] groups() default {};
Added: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/ZipCodeCoherenceValidator.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/ZipCodeCoherenceValidator.java (rev 0)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/groups/ZipCodeCoherenceValidator.java 2009-02-24 14:58:57 UTC (rev 16022)
@@ -0,0 +1,34 @@
+// $Id:$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* 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.hibernate.validation.engine.groups;
+
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class ZipCodeCoherenceValidator implements ConstraintValidator<ZipCodeCoherenceChecker, Address> {
+
+ public void initialize(ZipCodeCoherenceChecker parameters) {
+ }
+
+ public boolean isValid(Address value, ConstraintValidatorContext constraintValidatorContext) {
+ return false;
+ }
+}
15 years, 9 months