Hibernate SVN: r16803 - beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-06-16 15:18:53 -0400 (Tue, 16 Jun 2009)
New Revision: 16803
Modified:
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/GraphNavigationTest.java
Log:
Added group navigation tests
Modified: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/GraphNavigationTest.java
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/GraphNavigationTest.java 2009-06-16 19:17:22 UTC (rev 16802)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/GraphNavigationTest.java 2009-06-16 19:18:53 UTC (rev 16803)
@@ -27,6 +27,10 @@
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.testng.annotations.Test;
+import org.jboss.testharness.impl.packaging.Artifact;
+import org.jboss.testharness.impl.packaging.ArtifactType;
+import org.jboss.testharness.impl.packaging.Classes;
+import org.jboss.testharness.AbstractTest;
import org.hibernate.jsr303.tck.util.TestUtil;
@@ -34,7 +38,9 @@
/**
* @author Hardy Ferentschik
*/
-public class GraphNavigationTest {
+@Artifact(artifactType = ArtifactType.JSR303)
+(a)Classes(TestUtil.class)
+public class GraphNavigationTest extends AbstractTest {
@Test
public void testGraphNavigationDeterminism() {
15 years, 5 months
Hibernate SVN: r16802 - in validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation: engine and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-06-16 15:17:22 -0400 (Tue, 16 Jun 2009)
New Revision: 16802
Added:
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/BoundariesConstraintValidator.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/Positive.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/PositiveConstraintValidator.java
Removed:
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/custom/
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/graphnavigation/
Modified:
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/ValidatorTypeTest.java
Log:
Moved tests into the TCK
Added: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/BoundariesConstraintValidator.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/BoundariesConstraintValidator.java (rev 0)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/BoundariesConstraintValidator.java 2009-06-16 19:17:22 UTC (rev 16802)
@@ -0,0 +1,39 @@
+// $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.util;
+
+import java.lang.annotation.Annotation;
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public abstract class BoundariesConstraintValidator<T extends Annotation> implements ConstraintValidator<T, Integer> {
+ private int low;
+ private int high;
+
+ protected void initialize(int low, int high) {
+ this.low = low;
+ this.high = high;
+ }
+
+ public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {
+ return value >= low && value <= high;
+ }
+}
\ No newline at end of file
Property changes on: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/BoundariesConstraintValidator.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Added: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/Positive.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/Positive.java (rev 0)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/Positive.java 2009-06-16 19:17:22 UTC (rev 16802)
@@ -0,0 +1,39 @@
+// $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.util;
+
+import java.lang.annotation.Target;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Documented;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
+import javax.validation.Constraint;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Constraint( validatedBy = { PositiveConstraintValidator.class })
+@Target({ METHOD, FIELD, ANNOTATION_TYPE })
+@Retention(RUNTIME)
+@Documented
+public @interface Positive {
+ public abstract String message() default "{validation.positive}";
+ public abstract Class<?>[] groups() default {};
+}
\ No newline at end of file
Property changes on: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/Positive.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Added: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/PositiveConstraintValidator.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/PositiveConstraintValidator.java (rev 0)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/PositiveConstraintValidator.java 2009-06-16 19:17:22 UTC (rev 16802)
@@ -0,0 +1,27 @@
+// $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.util;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class PositiveConstraintValidator extends BoundariesConstraintValidator<Positive> {
+ public void initialize(Positive constraintAnnotation) {
+ super.initialize( 0, Integer.MAX_VALUE );
+ }
+}
\ No newline at end of file
Property changes on: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/PositiveConstraintValidator.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/ValidatorTypeTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/ValidatorTypeTest.java 2009-06-16 19:17:00 UTC (rev 16801)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/ValidatorTypeTest.java 2009-06-16 19:17:22 UTC (rev 16802)
@@ -27,9 +27,6 @@
import static org.testng.AssertJUnit.assertNull;
import org.testng.annotations.Test;
-import org.hibernate.validation.constraints.custom.Positive;
-import org.hibernate.validation.constraints.custom.PositiveConstraintValidator;
-
/**
* Tests for message resolution.
*
15 years, 5 months
Hibernate SVN: r16801 - in beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests: constraints/customconstraint and 2 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-06-16 15:17:00 -0400 (Tue, 16 Jun 2009)
New Revision: 16801
Added:
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/constraints/customconstraint/
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/constraints/customconstraint/BoundariesConstraintValidator.java
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/constraints/customconstraint/CustomConstraintValidatorTest.java
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/constraints/customconstraint/Positive.java
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/constraints/customconstraint/PositiveConstraintValidator.java
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Address.java
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Child.java
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/ChildFirst.java
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/GraphNavigationTest.java
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Order.java
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/OrderLine.java
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Parent.java
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/ParentSecond.java
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/ProperOrder.java
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/User.java
Log:
Added group navigation tests
Added: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/constraints/customconstraint/BoundariesConstraintValidator.java
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/constraints/customconstraint/BoundariesConstraintValidator.java (rev 0)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/constraints/customconstraint/BoundariesConstraintValidator.java 2009-06-16 19:17:00 UTC (rev 16801)
@@ -0,0 +1,39 @@
+// $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.jsr303.tck.tests.constraints.customconstraint;
+
+import java.lang.annotation.Annotation;
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public abstract class BoundariesConstraintValidator<T extends Annotation> implements ConstraintValidator<T, Integer> {
+ private int low;
+ private int high;
+
+ protected void initialize(int low, int high) {
+ this.low = low;
+ this.high = high;
+ }
+
+ public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {
+ return value >= low && value <= high;
+ }
+}
\ No newline at end of file
Property changes on: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/constraints/customconstraint/BoundariesConstraintValidator.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Added: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/constraints/customconstraint/CustomConstraintValidatorTest.java
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/constraints/customconstraint/CustomConstraintValidatorTest.java (rev 0)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/constraints/customconstraint/CustomConstraintValidatorTest.java 2009-06-16 19:17:00 UTC (rev 16801)
@@ -0,0 +1,57 @@
+// $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.jsr303.tck.tests.constraints.customconstraint;
+
+import java.util.Set;
+import javax.validation.Validation;
+import javax.validation.Validator;
+import javax.validation.ConstraintViolation;
+import javax.validation.metadata.PropertyDescriptor;
+
+import org.testng.annotations.Test;
+import static org.testng.Assert.*;
+import org.jboss.testharness.impl.packaging.Artifact;
+import org.jboss.testharness.impl.packaging.ArtifactType;
+import org.jboss.testharness.impl.packaging.Classes;
+import org.jboss.testharness.AbstractTest;
+
+import org.hibernate.jsr303.tck.util.TestUtil;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Artifact(artifactType = ArtifactType.JSR303)
+(a)Classes(TestUtil.class)
+public class CustomConstraintValidatorTest extends AbstractTest {
+
+ @Test
+ public void testInheritedConstraintValidationImpl() {
+ Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
+ Phone p = new Phone();
+ p.size = -2;
+ final PropertyDescriptor propertyDescriptor = validator.getConstraintsForClass( Phone.class )
+ .getConstraintsForProperty( "size" );
+ assertNotNull( propertyDescriptor );
+ final Set<ConstraintViolation<Phone>> constraintViolations = validator.validate( p );
+ assertEquals( 1, constraintViolations.size() );
+ }
+
+ public static class Phone {
+ @Positive public int size;
+ }
+}
\ No newline at end of file
Property changes on: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/constraints/customconstraint/CustomConstraintValidatorTest.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Added: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/constraints/customconstraint/Positive.java
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/constraints/customconstraint/Positive.java (rev 0)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/constraints/customconstraint/Positive.java 2009-06-16 19:17:00 UTC (rev 16801)
@@ -0,0 +1,39 @@
+// $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.jsr303.tck.tests.constraints.customconstraint;
+
+import java.lang.annotation.Target;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Documented;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
+import javax.validation.Constraint;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Constraint( validatedBy = { PositiveConstraintValidator.class })
+@Target({ METHOD, FIELD, ANNOTATION_TYPE })
+@Retention(RUNTIME)
+@Documented
+public @interface Positive {
+ public abstract String message() default "{validation.positive}";
+ public abstract Class<?>[] groups() default {};
+}
\ No newline at end of file
Property changes on: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/constraints/customconstraint/Positive.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Added: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/constraints/customconstraint/PositiveConstraintValidator.java
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/constraints/customconstraint/PositiveConstraintValidator.java (rev 0)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/constraints/customconstraint/PositiveConstraintValidator.java 2009-06-16 19:17:00 UTC (rev 16801)
@@ -0,0 +1,27 @@
+// $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.jsr303.tck.tests.constraints.customconstraint;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class PositiveConstraintValidator extends BoundariesConstraintValidator<Positive> {
+ public void initialize(Positive constraintAnnotation) {
+ super.initialize( 0, Integer.MAX_VALUE );
+ }
+}
\ No newline at end of file
Property changes on: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/constraints/customconstraint/PositiveConstraintValidator.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Added: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Address.java
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Address.java (rev 0)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Address.java 2009-06-16 19:17:00 UTC (rev 16801)
@@ -0,0 +1,82 @@
+// $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.jsr303.tck.tests.validation.graphnavigation;
+
+import javax.validation.Valid;
+import javax.validation.constraints.NotNull;
+import javax.validation.constraints.Size;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class Address {
+
+ @NotNull
+ @Size(max = 30)
+ private String addressline1;
+
+ private String zipCode;
+
+ @Size(max = 30)
+ @NotNull
+ private String city;
+
+ @Valid
+ private User inhabitant;
+
+ public Address() {
+ }
+
+ public Address(String addressline1, String zipCode, String city) {
+ this.addressline1 = addressline1;
+ this.zipCode = zipCode;
+ this.city = city;
+ }
+
+ public String getAddressline1() {
+ return addressline1;
+ }
+
+ public void setAddressline1(String addressline1) {
+ this.addressline1 = addressline1;
+ }
+
+ 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;
+ }
+
+ public User getInhabitant() {
+ return inhabitant;
+ }
+
+ public void setInhabitant(User inhabitant) {
+ this.inhabitant = inhabitant;
+ }
+}
\ No newline at end of file
Property changes on: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Address.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Added: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Child.java
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Child.java (rev 0)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Child.java 2009-06-16 19:17:00 UTC (rev 16801)
@@ -0,0 +1,36 @@
+// $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.jsr303.tck.tests.validation.graphnavigation;
+
+import javax.validation.constraints.NotNull;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class Child {
+ private String name;
+
+ @NotNull(groups = ChildFirst.class)
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
\ No newline at end of file
Property changes on: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Child.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Added: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/ChildFirst.java
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/ChildFirst.java (rev 0)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/ChildFirst.java 2009-06-16 19:17:00 UTC (rev 16801)
@@ -0,0 +1,24 @@
+// $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.jsr303.tck.tests.validation.graphnavigation;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public interface ChildFirst {
+}
\ No newline at end of file
Property changes on: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/ChildFirst.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Added: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/GraphNavigationTest.java
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/GraphNavigationTest.java (rev 0)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/GraphNavigationTest.java 2009-06-16 19:17:00 UTC (rev 16801)
@@ -0,0 +1,126 @@
+// $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.jsr303.tck.tests.validation.graphnavigation;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+import javax.validation.ConstraintViolation;
+import javax.validation.Validator;
+import javax.validation.Validation;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+import org.testng.annotations.Test;
+
+import org.hibernate.jsr303.tck.util.TestUtil;
+
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class GraphNavigationTest {
+
+ @Test
+ public void testGraphNavigationDeterminism() {
+ // build the test object graph
+ User user = new User( "John", "Doe" );
+
+ Address address1 = new Address( null, "11122", "Stockholm" );
+ address1.setInhabitant( user );
+
+ Address address2 = new Address( "Kungsgatan 5", "11122", "Stockholm" );
+ address2.setInhabitant( user );
+
+ user.addAddress( address1 );
+ user.addAddress( address2 );
+
+ Order order = new Order( 1 );
+ order.setShippingAddress( address1 );
+ order.setBillingAddress( address2 );
+ order.setCustomer( user );
+
+ OrderLine line1 = new OrderLine( order, 42 );
+ OrderLine line2 = new OrderLine( order, 101 );
+ order.addOrderLine( line1 );
+ order.addOrderLine( line2 );
+
+ Validator validator = TestUtil.getDefaultValidator();
+
+ Set<ConstraintViolation<Order>> constraintViolations = validator.validate( order );
+ assertEquals( constraintViolations.size(), 3, "Wrong number of constraints" );
+
+ List<String> expectedErrorMessages = new ArrayList<String>();
+ expectedErrorMessages.add( "shippingAddress.addressline1" );
+ expectedErrorMessages.add( "customer.addresses[0].addressline1" );
+ expectedErrorMessages.add( "billingAddress.inhabitant.addresses[0].addressline1" );
+
+ for ( ConstraintViolation<Order> violation : constraintViolations ) {
+ if ( expectedErrorMessages.contains( violation.getPropertyPath() ) ) {
+ expectedErrorMessages.remove( violation.getPropertyPath() );
+ }
+ }
+
+ assertTrue( expectedErrorMessages.size() == 0, "All error messages should have occured once" );
+ }
+
+ @Test
+ public void testNoEndlessLoop() {
+ User john = new User( "John", null );
+ john.knows( john );
+
+ Validator validator = TestUtil.getDefaultValidator();
+
+ Set<ConstraintViolation<User>> constraintViolations = validator.validate( john );
+ assertEquals( constraintViolations.size(), 1, "Wrong number of constraints" );
+ TestUtil.assertConstraintViolation(
+ constraintViolations.iterator().next(), User.class, null, "lastName"
+ );
+
+
+ User jane = new User( "Jane", "Doe" );
+ jane.knows( john );
+ john.knows( jane );
+
+ constraintViolations = validator.validate( john );
+ assertEquals( constraintViolations.size(), 1, "Wrong number of constraints" );
+ TestUtil.assertConstraintViolation(
+ constraintViolations.iterator().next(), User.class, null, "lastName"
+ );
+
+ constraintViolations = validator.validate( jane );
+ assertEquals( constraintViolations.size(), 1, "Wrong number of constraints" );
+ TestUtil.assertConstraintViolation(
+ constraintViolations.iterator().next(), User.class, null, "knowsUser[0].lastName"
+ );
+
+ john.setLastName( "Doe" );
+ constraintViolations = validator.validate( john );
+ assertEquals( constraintViolations.size(), 0, "Wrong number of constraints" );
+ }
+
+ @Test
+ public void testFullGraphValidationBeforeNextGroupInSequence() {
+ Parent p = new Parent();
+ p.setChild( new Child() );
+ Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
+ Set<ConstraintViolation<Parent>> errors = validator.validate( p, ProperOrder.class );
+ assertEquals( 1, errors.size() );
+ assertEquals( "child.name", errors.iterator().next().getPropertyPath() );
+ }
+}
\ No newline at end of file
Property changes on: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/GraphNavigationTest.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Added: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Order.java
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Order.java (rev 0)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Order.java 2009-06-16 19:17:00 UTC (rev 16801)
@@ -0,0 +1,80 @@
+// $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.jsr303.tck.tests.validation.graphnavigation;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import javax.validation.Valid;
+import javax.validation.constraints.NotNull;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class Order {
+ @NotNull
+ Integer orderId;
+
+ @Valid
+ private List<OrderLine> orderLines = new ArrayList<OrderLine>();
+
+ @Valid
+ private User customer;
+
+ @Valid
+ private Address shippingAddress;
+
+ @Valid
+ private Address billingAddress;
+
+ public Order(Integer id) {
+ orderId = id;
+ }
+
+ public void addOrderLine(OrderLine orderLine) {
+ orderLines.add( orderLine );
+ }
+
+ public List<OrderLine> getOrderLines() {
+ return Collections.unmodifiableList( orderLines );
+ }
+
+ public User getCustomer() {
+ return customer;
+ }
+
+ public void setCustomer(User customer) {
+ this.customer = customer;
+ }
+
+ public Address getShippingAddress() {
+ return shippingAddress;
+ }
+
+ public void setShippingAddress(Address shippingAddress) {
+ this.shippingAddress = shippingAddress;
+ }
+
+ public Address getBillingAddress() {
+ return billingAddress;
+ }
+
+ public void setBillingAddress(Address billingAddress) {
+ this.billingAddress = billingAddress;
+ }
+}
\ No newline at end of file
Property changes on: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Order.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Added: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/OrderLine.java
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/OrderLine.java (rev 0)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/OrderLine.java 2009-06-16 19:17:00 UTC (rev 16801)
@@ -0,0 +1,45 @@
+// $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.jsr303.tck.tests.validation.graphnavigation;
+
+import javax.validation.Valid;
+import javax.validation.constraints.NotNull;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class OrderLine {
+ @NotNull
+ Integer articleNumber;
+
+ @Valid
+ Order order;
+
+ public OrderLine(Order order, Integer articleNumber) {
+ this.articleNumber = articleNumber;
+ this.order = order;
+ }
+
+ public Integer getArticleNumber() {
+ return articleNumber;
+ }
+
+ public void setArticleNumber(Integer articleNumber) {
+ this.articleNumber = articleNumber;
+ }
+}
\ No newline at end of file
Property changes on: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/OrderLine.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Added: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Parent.java
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Parent.java (rev 0)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Parent.java 2009-06-16 19:17:00 UTC (rev 16801)
@@ -0,0 +1,47 @@
+// $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.jsr303.tck.tests.validation.graphnavigation;
+
+import javax.validation.constraints.NotNull;
+import javax.validation.Valid;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class Parent {
+ private String name;
+ private Child child;
+
+ @NotNull(groups = ParentSecond.class)
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Valid
+ public Child getChild() {
+ return child;
+ }
+
+ public void setChild(Child child) {
+ this.child = child;
+ }
+}
\ No newline at end of file
Property changes on: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Parent.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Added: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/ParentSecond.java
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/ParentSecond.java (rev 0)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/ParentSecond.java 2009-06-16 19:17:00 UTC (rev 16801)
@@ -0,0 +1,24 @@
+// $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.jsr303.tck.tests.validation.graphnavigation;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public interface ParentSecond {
+}
\ No newline at end of file
Property changes on: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/ParentSecond.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Added: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/ProperOrder.java
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/ProperOrder.java (rev 0)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/ProperOrder.java 2009-06-16 19:17:00 UTC (rev 16801)
@@ -0,0 +1,27 @@
+// $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.jsr303.tck.tests.validation.graphnavigation;
+
+import javax.validation.GroupSequence;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@GroupSequence( {ChildFirst.class, ParentSecond.class } )
+public interface ProperOrder {
+}
\ No newline at end of file
Property changes on: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/ProperOrder.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Added: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/User.java
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/User.java (rev 0)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/User.java 2009-06-16 19:17:00 UTC (rev 16801)
@@ -0,0 +1,82 @@
+// $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.jsr303.tck.tests.validation.graphnavigation;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.validation.Valid;
+import javax.validation.constraints.NotNull;
+import javax.validation.groups.Default;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class User {
+
+ @NotNull
+ private String firstName;
+
+ @NotNull(groups = Default.class)
+ private String lastName;
+
+ @Valid
+ private List<Address> addresses = new ArrayList<Address>();
+
+ @Valid
+ private List<User> knowsUser = new ArrayList<User>();
+
+ public User() {
+ }
+
+ public User(String firstName, String lastName) {
+ this.firstName = firstName;
+ this.lastName = lastName;
+ }
+
+ public List<Address> getAddresses() {
+ return addresses;
+ }
+
+ public void addAddress(Address address) {
+ addresses.add( address );
+ }
+
+ public void knows(User user) {
+ knowsUser.add( user );
+ }
+
+ public List<User> getKnowsUser() {
+ return knowsUser;
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+}
\ No newline at end of file
Property changes on: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/User.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
15 years, 5 months
Hibernate SVN: r16799 - beanvalidation/trunk/validation-tck/src.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-06-16 15:00:50 -0400 (Tue, 16 Jun 2009)
New Revision: 16799
Removed:
beanvalidation/trunk/validation-tck/src/test/
Log:
deleted obsolete directories. There are no tests in the tck module
15 years, 5 months
Hibernate SVN: r16798 - in validator/trunk/hibernate-validator/src: main/java/org/hibernate/validation/engine and 4 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-06-16 12:16:48 -0400 (Tue, 16 Jun 2009)
New Revision: 16798
Added:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/AnnotationIgnores.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/BeanDescriptorImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/BeanMetaData.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/BeanMetaDataCache.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/BeanMetaDataImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/ConstraintDescriptorImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/ConstraintHelper.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/ElementDescriptorImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/MetaConstraint.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/PropertyDescriptorImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/xml/
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/xml/ValidationBootstrapParameters.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/xml/ValidationXmlParser.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/xml/XmlMappingParser.java
Removed:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanDescriptorImpl.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/BeanMetaDataCache.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/ConstraintHelper.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ElementDescriptorImpl.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/PropertyDescriptorImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/metadata/
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConfigurationImpl.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/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/test/java/org/hibernate/validation/engine/ConstraintHelperTest.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolatorTest.java
validator/trunk/hibernate-validator/src/test/suite/unit-tests.xml
Log:
Also introduced metadata package in validator implementation (mirrowring the api)
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanDescriptorImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanDescriptorImpl.java 2009-06-16 15:29:59 UTC (rev 16797)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanDescriptorImpl.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -1,30 +0,0 @@
-package org.hibernate.validation.engine;
-
-import java.util.Set;
-import javax.validation.metadata.BeanDescriptor;
-import javax.validation.metadata.PropertyDescriptor;
-
-/**
- * @author Emmanuel Bernard
- * @author Hardy Ferentschik
- */
-public class BeanDescriptorImpl<T> extends ElementDescriptorImpl implements BeanDescriptor {
- private final BeanMetaData<T> metadataBean;
-
- public BeanDescriptorImpl(BeanMetaData<T> metadataBean) {
- super( metadataBean.getBeanClass() );
- this.metadataBean = metadataBean;
- }
-
- public boolean isBeanConstrained() {
- return metadataBean.getConstrainedProperties().size() > 0;
- }
-
- public PropertyDescriptor getConstraintsForProperty(String propertyName) {
- return metadataBean.getPropertyDescriptor( propertyName );
- }
-
- public Set<PropertyDescriptor> getConstrainedProperties() {
- return metadataBean.getConstrainedProperties();
- }
-}
Deleted: 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-06-16 15:29:59 UTC (rev 16797)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaData.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -1,75 +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.lang.reflect.Member;
-import java.util.List;
-import java.util.Set;
-import javax.validation.metadata.BeanDescriptor;
-import javax.validation.metadata.PropertyDescriptor;
-
-/**
- * Interface defining the meta data about the constraints defined in a given bean.
- *
- * @author Hardy Ferentschik
- */
-public interface BeanMetaData<T> {
-
- /**
- * @return the class of the bean.
- */
- Class<T> getBeanClass();
-
- /**
- * @return an instance of <code>ElementDescriptor</code> describing the bean this meta data applies for.
- */
- BeanDescriptor getBeanDescriptor();
-
- /**
- * @return A list of all cascaded methods and fields (methods/fields annotated with @Valid).
- */
- List<Member> getCascadedMembers();
-
- /**
- * @return A map mapping defined group sequences to a list of groups.
- */
- List<Class<?>> getDefaultGroupSequence();
-
- /**
- * @return A list of <code>MetaConstraint</code> instances encapsulating the information of all the constraints
- * defined on the bean.
- */
- List<MetaConstraint<T, ? extends Annotation>> geMetaConstraintList();
-
- /**
- * Return <code>PropertyDescriptor</code> for the given property.
- *
- * @param property the property for which to retrieve the descriptor.
- *
- * @return Returns the <code>PropertyDescriptor</code> for the given property or <code>null</code> in case the
- * property does not have a descriptor.
- */
- PropertyDescriptor getPropertyDescriptor(String property);
-
- /**
- * @return the property descriptors having at least one constraint defined or which are marked
- * as cascaded (@Valid).
- */
- Set<PropertyDescriptor> getConstrainedProperties();
-}
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataCache.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataCache.java 2009-06-16 15:29:59 UTC (rev 16797)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataCache.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -1,48 +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.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * Cache for created instances of <code>BeanMetaData</code>.
- *
- * @author Hardy Ferentschik
- */
-public class BeanMetaDataCache {
- /**
- * A map for the meta data for each entity. The key is the class and the value the bean meta data for this
- * entity.
- */
- private Map<Class<?>, BeanMetaDataImpl<?>> metadataProviders = new ConcurrentHashMap<Class<?>, BeanMetaDataImpl<?>>(
- 10
- );
-
- @SuppressWarnings("unchecked")
- public <T> BeanMetaDataImpl<T> getBeanMetaData(Class<T> beanClass) {
- if ( beanClass == null ) {
- throw new IllegalArgumentException( "Class cannot be null" );
- }
- return ( BeanMetaDataImpl<T> ) metadataProviders.get( beanClass );
- }
-
- public <T> void addBeanMetaData(Class<T> beanClass, BeanMetaDataImpl<T> metaData) {
- metadataProviders.put( beanClass, metaData );
- }
-}
Deleted: 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-06-16 15:29:59 UTC (rev 16797)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataImpl.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -1,389 +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.lang.reflect.AnnotatedElement;
-import java.lang.reflect.Field;
-import java.lang.reflect.Member;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import javax.validation.GroupSequence;
-import javax.validation.Valid;
-import javax.validation.ValidationException;
-import javax.validation.groups.Default;
-import javax.validation.metadata.BeanDescriptor;
-import javax.validation.metadata.PropertyDescriptor;
-
-import org.slf4j.Logger;
-
-import org.hibernate.validation.engine.xml.AnnotationIgnores;
-import org.hibernate.validation.util.LoggerFactory;
-import org.hibernate.validation.util.ReflectionHelper;
-
-
-/**
- * This class encapsulates all meta data needed for validation. Implementations of {@code Validator} interface can
- * instantiate an instance of this class and delegate the metadata extraction to it.
- *
- * @author Hardy Ferentschik
- */
-
-public class BeanMetaDataImpl<T> implements BeanMetaData<T> {
-
- private static final Logger log = LoggerFactory.make();
-
- /**
- * The root bean class for this validator.
- */
- private final Class<T> beanClass;
-
- /**
- * The main element descriptor for <code>beanClass</code>.
- */
- private BeanDescriptorImpl<T> beanDescriptor;
-
- /**
- * List of constraints.
- */
- private List<MetaConstraint<T, ? extends Annotation>> metaConstraintList = new ArrayList<MetaConstraint<T, ? extends Annotation>>();
-
- /**
- * List of cascaded members.
- */
- private List<Member> cascadedMembers = new ArrayList<Member>();
-
- /**
- * Maps field and method names to their <code>ElementDescriptorImpl</code>.
- */
- private Map<String, PropertyDescriptor> propertyDescriptors = new HashMap<String, PropertyDescriptor>();
-
- /**
- * Maps group sequences to the list of group/sequences.
- */
- private List<Class<?>> defaultGroupSequence = new ArrayList<Class<?>>();
-
- /**
- * Object keeping track of all constraints.
- */
- private final ConstraintHelper constraintHelper;
-
-
- public BeanMetaDataImpl(Class<T> beanClass, ConstraintHelper constraintHelper) {
- this(
- beanClass,
- constraintHelper,
- new AnnotationIgnores()
- );
- }
-
- public BeanMetaDataImpl(Class<T> beanClass, ConstraintHelper constraintHelper, AnnotationIgnores annotationIgnores) {
- this.beanClass = beanClass;
- this.constraintHelper = constraintHelper;
- createMetaData( annotationIgnores );
- }
-
- public Class<T> getBeanClass() {
- return beanClass;
- }
-
- public BeanDescriptor getBeanDescriptor() {
- return beanDescriptor;
- }
-
- public List<Member> getCascadedMembers() {
- return Collections.unmodifiableList( cascadedMembers );
- }
-
- public List<MetaConstraint<T, ? extends Annotation>> geMetaConstraintList() {
- return Collections.unmodifiableList( metaConstraintList );
- }
-
- public void addMetaConstraint(MetaConstraint<T, ? extends Annotation> metaConstraint) {
- metaConstraintList.add( metaConstraint );
- }
-
- public void addCascadedMember(Member member) {
- cascadedMembers.add( member );
- }
-
- public PropertyDescriptor getPropertyDescriptor(String property) {
- return propertyDescriptors.get( property );
- }
-
- public List<Class<?>> getDefaultGroupSequence() {
- return Collections.unmodifiableList( defaultGroupSequence );
- }
-
- public void setDefaultGroupSequence(List<Class<?>> groupSequence) {
- defaultGroupSequence = new ArrayList<Class<?>>();
- for ( Class<?> group : groupSequence ) {
- if ( group.getName().equals( beanClass.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.isTraceEnabled() ) {
- log.trace(
- "Members of the default group sequence for bean {} are: {}",
- beanClass.getName(),
- defaultGroupSequence
- );
- }
- }
-
- public Set<PropertyDescriptor> getConstrainedProperties() {
- return Collections.unmodifiableSet( new HashSet<PropertyDescriptor>( propertyDescriptors.values() ) );
- }
-
- /**
- * Create bean desciptor, find all classes/subclasses/interfaces which have to be taken in consideration
- * for this validator and create meta data.
- *
- * @param annotationIgnores Datastructure keeping track on which annotation should be ignored.
- */
- private void createMetaData(AnnotationIgnores annotationIgnores) {
- beanDescriptor = new BeanDescriptorImpl<T>( this );
- initDefaultGroupSequence();
- List<Class> classes = new ArrayList<Class>();
- computeClassHierarchy( beanClass, classes );
- for ( Class current : classes ) {
- initClass( current, annotationIgnores );
- }
- }
-
- /**
- * Get all superclasses and interfaces recursively.
- *
- * @param clazz The class to start the search with.
- * @param classes List of classes to which to add all found super classes and interfaces.
- */
- private void computeClassHierarchy(Class clazz, List<Class> classes) {
- if ( log.isTraceEnabled() ) {
- log.trace( "Processing: {}", clazz );
- }
- for ( Class current = clazz; current != null; current = current.getSuperclass() ) {
- if ( classes.contains( current ) ) {
- return;
- }
- classes.add( current );
- for ( Class currentInterface : current.getInterfaces() ) {
- computeClassHierarchy( currentInterface, classes );
- }
- }
- }
-
- private void initClass(Class clazz, AnnotationIgnores annotationIgnores) {
- initClassConstraints( clazz, annotationIgnores );
- initMethodConstraints( clazz, annotationIgnores );
- initFieldConstraints( clazz, annotationIgnores );
- }
-
- /**
- * Checks whether there is a default group sequence defined for this class.
- * See HV-113.
- */
- private void initDefaultGroupSequence() {
- List<Class<?>> groupSequence = new ArrayList<Class<?>>();
- GroupSequence groupSequenceAnnotation = beanClass.getAnnotation( GroupSequence.class );
- if ( groupSequenceAnnotation == null ) {
- groupSequence.add( beanClass );
- }
- else {
- groupSequence.addAll( Arrays.asList( groupSequenceAnnotation.value() ) );
- }
- setDefaultGroupSequence( groupSequence );
- }
-
- private void initFieldConstraints(Class clazz, AnnotationIgnores annotationIgnores) {
- for ( Field field : clazz.getDeclaredFields() ) {
- List<ConstraintDescriptorImpl<?>> fieldMetadata = findConstraints( field );
- for ( ConstraintDescriptorImpl<?> constraintDescription : fieldMetadata ) {
- if ( annotationIgnores.isIgnoreAnnotations( field ) ) {
- break;
- }
- ReflectionHelper.setAccessibility( field );
- MetaConstraint<T, ?> metaConstraint = createMetaConstraint( field, constraintDescription );
- metaConstraintList.add( metaConstraint );
- }
- if ( field.isAnnotationPresent( Valid.class ) ) {
- ReflectionHelper.setAccessibility( field );
- cascadedMembers.add( field );
- addPropertyDescriptorForMember( field );
- }
- }
- }
-
- private void initMethodConstraints(Class clazz, AnnotationIgnores annotationIgnores) {
- for ( Method method : clazz.getDeclaredMethods() ) {
- List<ConstraintDescriptorImpl<?>> methodMetadata = findConstraints( method );
- for ( ConstraintDescriptorImpl<?> constraintDescription : methodMetadata ) {
- if ( annotationIgnores.isIgnoreAnnotations( method ) ) {
- break;
- }
- ReflectionHelper.setAccessibility( method );
- MetaConstraint<T, ?> metaConstraint = createMetaConstraint( method, constraintDescription );
- metaConstraintList.add( metaConstraint );
- }
- if ( method.isAnnotationPresent( Valid.class ) ) {
- ReflectionHelper.setAccessibility( method );
- cascadedMembers.add( method );
- addPropertyDescriptorForMember( method );
- }
- }
- }
-
- private PropertyDescriptorImpl addPropertyDescriptorForMember(Member member) {
- String name = ReflectionHelper.getPropertyName( member );
- PropertyDescriptorImpl propertyDescriptor = ( PropertyDescriptorImpl ) propertyDescriptors.get(
- name
- );
- if ( propertyDescriptor == null ) {
- propertyDescriptor = new PropertyDescriptorImpl(
- ReflectionHelper.getType( member ),
- ( ( AnnotatedElement ) member ).isAnnotationPresent( Valid.class ),
- name
- );
- propertyDescriptors.put( name, propertyDescriptor );
- }
- return propertyDescriptor;
- }
-
- private void initClassConstraints(Class<?> clazz, AnnotationIgnores annotationIgnores) {
- if ( annotationIgnores.isIgnoreAnnotations( clazz ) ) {
- return;
- }
- List<ConstraintDescriptorImpl<?>> classMetadata = findClassLevelConstraints( clazz );
- for ( ConstraintDescriptorImpl<?> constraintDescription : classMetadata ) {
- MetaConstraint<T, ?> metaConstraint = createMetaConstraint( constraintDescription );
- metaConstraintList.add( metaConstraint );
- }
- }
-
- private <A extends Annotation> MetaConstraint<T, ?> createMetaConstraint(ConstraintDescriptorImpl<A> descriptor) {
- return new MetaConstraint<T, A>( beanClass, descriptor );
- }
-
- private <A extends Annotation> MetaConstraint<T, ?> createMetaConstraint(Member m, ConstraintDescriptorImpl<A> descriptor) {
- return new MetaConstraint<T, A>( m, beanClass, descriptor );
- }
-
- /**
- * Examines the given annotation to see whether it is a single or multi valued constraint annotation.
- *
- * @param clazz the class we are currently processing.
- * @param annotation The annotation to examine.
- *
- * @return A list of constraint descriptors or the empty list in case <code>annotation</code> is neither a
- * single nor multi value annotation.
- */
- private <A extends Annotation> List<ConstraintDescriptorImpl<?>> findConstraintAnnotations(Class<?> clazz, A annotation) {
- List<ConstraintDescriptorImpl<?>> constraintDescriptors = new ArrayList<ConstraintDescriptorImpl<?>>();
-
- List<Annotation> constraints = new ArrayList<Annotation>();
- if ( constraintHelper.isConstraintAnnotation( annotation ) ||
- constraintHelper.isBuiltinConstraint( annotation.annotationType() ) ) {
- constraints.add( annotation );
- }
-
- // check if we have a multi value constraint
- constraints.addAll( constraintHelper.getMultiValueConstraints( annotation ) );
-
- for ( Annotation constraint : constraints ) {
- final ConstraintDescriptorImpl constraintDescriptor = buildConstraintDescriptor( clazz, constraint );
- constraintDescriptors.add( constraintDescriptor );
- }
- return constraintDescriptors;
- }
-
- @SuppressWarnings("unchecked")
- private <A extends Annotation> ConstraintDescriptorImpl buildConstraintDescriptor(Class<?> clazz, A annotation) {
- ConstraintDescriptorImpl constraintDescriptor;
- if ( clazz.isInterface() ) {
- constraintDescriptor = new ConstraintDescriptorImpl( annotation, constraintHelper, clazz );
- }
- else {
- constraintDescriptor = new ConstraintDescriptorImpl( annotation, constraintHelper );
- }
- return constraintDescriptor;
- }
-
- /**
- * Finds all constraint annotations defined for the given class and returns them in a list of
- * constraint descriptors.
- *
- * @param beanClass The class to check for constraints annotations.
- *
- * @return A list of constraint descriptors for all constraint specified on the given class.
- */
- private List<ConstraintDescriptorImpl<?>> findClassLevelConstraints(Class<?> beanClass) {
- List<ConstraintDescriptorImpl<?>> metadata = new ArrayList<ConstraintDescriptorImpl<?>>();
- for ( Annotation annotation : beanClass.getAnnotations() ) {
- metadata.addAll( findConstraintAnnotations( beanClass, annotation ) );
- }
- for ( ConstraintDescriptorImpl constraintDescriptor : metadata ) {
- beanDescriptor.addConstraintDescriptor( constraintDescriptor );
- }
- return metadata;
- }
-
-
- /**
- * Finds all constraint annotations defined for the given field/method and returns them in a list of
- * constraint descriptors.
- *
- * @param member The fiels or method to check for constraints annotations.
- *
- * @return A list of constraint descriptors for all constraint specified for the given field or method.
- */
- private List<ConstraintDescriptorImpl<?>> findConstraints(Member member) {
- assert member instanceof Field || member instanceof Method;
-
- List<ConstraintDescriptorImpl<?>> metadata = new ArrayList<ConstraintDescriptorImpl<?>>();
- for ( Annotation annotation : ( ( AnnotatedElement ) member ).getAnnotations() ) {
- metadata.addAll( findConstraintAnnotations( member.getDeclaringClass(), annotation ) );
- }
-
- String name = ReflectionHelper.getPropertyName( member );
- for ( ConstraintDescriptorImpl constraintDescriptor : metadata ) {
- if ( member instanceof Method && name == null ) { // can happen if member is a Method which does not follow the bean convention
- throw new ValidationException(
- "Annotated methods must follow the JavaBeans naming convention. " + member.getName() + "() does not."
- );
- }
- PropertyDescriptorImpl propertyDescriptor = ( PropertyDescriptorImpl ) propertyDescriptors.get( name );
- if ( propertyDescriptor == null ) {
- propertyDescriptor = addPropertyDescriptorForMember( member );
- }
- propertyDescriptor.addConstraintDescriptor( constraintDescriptor );
- }
- return metadata;
- }
-}
\ No newline at end of file
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConfigurationImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConfigurationImpl.java 2009-06-16 15:29:59 UTC (rev 16797)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConfigurationImpl.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -34,8 +34,8 @@
import org.slf4j.Logger;
import org.hibernate.validation.engine.resolver.DefaultTraversableResolver;
-import org.hibernate.validation.engine.xml.ValidationBootstrapParameters;
-import org.hibernate.validation.engine.xml.ValidationXmlParser;
+import org.hibernate.validation.xml.ValidationBootstrapParameters;
+import org.hibernate.validation.xml.ValidationXmlParser;
import org.hibernate.validation.util.LoggerFactory;
import org.hibernate.validation.util.Version;
Deleted: 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-06-16 15:29:59 UTC (rev 16797)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintDescriptorImpl.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -1,384 +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.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import javax.validation.Constraint;
-import javax.validation.ConstraintDefinitionException;
-import javax.validation.metadata.ConstraintDescriptor;
-import javax.validation.ConstraintValidator;
-import javax.validation.OverridesAttribute;
-import javax.validation.ReportAsSingleViolation;
-import javax.validation.ValidationException;
-import javax.validation.groups.Default;
-
-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;
-
-/**
- * Describe a single constraint (including it's composing constraints).
- *
- * @author Emmanuel Bernard
- * @author Hardy Ferentschik
- */
-public class ConstraintDescriptorImpl<T extends Annotation> implements ConstraintDescriptor<T> {
- private static final Logger log = LoggerFactory.make();
- private static final int OVERRIDES_PARAMETER_DEFAULT_INDEX = -1;
-
- /**
- * The actual constraint annotation.
- */
- private final T annotation;
-
- /**
- * The set of classes implementing the validation for this constraint. See also
- * <code>ConstraintValidator</code> resolution algorithm.
- */
- private final List<Class<? extends ConstraintValidator<T, ?>>> constraintValidatorDefinitonClasses = new ArrayList<Class<? extends ConstraintValidator<T, ?>>>();
-
- /**
- * The groups for which to apply this constraint.
- */
- private final Set<Class<?>> groups = new HashSet<Class<?>>();
-
- /**
- * The constraint parameters as map. The key is the paramter name and the value the
- * parameter value as specified in the constraint.
- */
- private final Map<String, Object> attributes;
-
- /**
- * The composing constraints for this constraints.
- */
- private final Set<ConstraintDescriptor<?>> composingConstraints = new HashSet<ConstraintDescriptor<?>>();
-
- /**
- * Flag indicating if in case of a composing constraint a single error or multiple errors should be raised.
- */
- private final boolean isReportAsSingleInvalidConstraint;
-
- /**
- * Handle to the builtin constraint implementations.
- */
- private final ConstraintHelper constraintHelper;
-
- public ConstraintDescriptorImpl(T annotation, ConstraintHelper constraintHelper, Class<?> implicitGroup) {
- this( annotation, constraintHelper );
- this.groups.add( implicitGroup );
- }
-
-
- public ConstraintDescriptorImpl(T annotation, ConstraintHelper constraintHelper) {
- this.annotation = annotation;
- this.attributes = getAnnotationParameters( annotation );
- this.constraintHelper = constraintHelper;
-
- this.isReportAsSingleInvalidConstraint = annotation.annotationType().isAnnotationPresent(
- ReportAsSingleViolation.class
- );
-
- Class<?>[] groupsFromAnnotation = ReflectionHelper.getAnnotationParameter(
- annotation, "groups", Class[].class
- );
- if ( groupsFromAnnotation.length == 0 ) {
- groups.add( Default.class );
- }
- else {
- this.groups.addAll( Arrays.asList( groupsFromAnnotation ) );
- }
-
- findConstraintValidatorClasses();
- Map<ClassIndexWrapper, Map<String, Object>> overrideParameters = parseOverrideParameters();
- parseComposingConstraints( overrideParameters );
- }
-
- private void findConstraintValidatorClasses() {
- if ( constraintHelper.containsConstraintValidatorDefinition( annotation.annotationType() ) ) {
- for ( Class<? extends ConstraintValidator<? extends Annotation, ?>> validator : constraintHelper
- .getConstraintValidatorDefinition( annotation.annotationType() ) ) {
- constraintValidatorDefinitonClasses.add( ( Class<? extends ConstraintValidator<T, ?>> ) validator );
- }
- return;
- }
-
- List<Class<? extends ConstraintValidator<? extends Annotation, ?>>> constraintDefinitonClasses = new ArrayList<Class<? extends ConstraintValidator<? extends Annotation, ?>>>();
- if ( constraintHelper.isBuiltinConstraint( annotation.annotationType() ) ) {
- constraintDefinitonClasses.addAll( constraintHelper.getBuiltInConstraints( annotation.annotationType() ) );
- }
- else {
- final Class<? extends Annotation> annotationType = annotation.annotationType();
- Class<? extends ConstraintValidator<?, ?>>[] validatedBy = annotationType
- .getAnnotation( Constraint.class )
- .validatedBy();
- constraintDefinitonClasses.addAll( Arrays.asList( validatedBy ) );
- }
-
- constraintHelper.addConstraintValidatorDefinition(
- annotation.annotationType(), constraintDefinitonClasses
- );
-
- for ( Class<? extends ConstraintValidator<? extends Annotation, ?>> validator : constraintDefinitonClasses ) {
- @SuppressWarnings("unchecked")
- Class<? extends ConstraintValidator<T, ?>> safeValidator = ( Class<? extends ConstraintValidator<T, ?>> ) validator;
- constraintValidatorDefinitonClasses.add( safeValidator );
- }
- }
-
- public T getAnnotation() {
- return annotation;
- }
-
- public Set<Class<?>> getGroups() {
- return Collections.unmodifiableSet( groups );
- }
-
- public List<Class<? extends ConstraintValidator<T, ?>>> getConstraintValidatorClasses() {
- return Collections.unmodifiableList( constraintValidatorDefinitonClasses );
- }
-
- public Map<String, Object> getAttributes() {
- return Collections.unmodifiableMap( attributes );
- }
-
- public Set<ConstraintDescriptor<?>> getComposingConstraints() {
- return Collections.unmodifiableSet( composingConstraints );
- }
-
- public boolean isReportAsSingleViolation() {
- return isReportAsSingleInvalidConstraint;
- }
-
- @Override
- public String toString() {
- return "ConstraintDescriptorImpl{" +
- "annotation=" + annotation +
- ", constraintValidatorDefinitonClasses=" + constraintValidatorDefinitonClasses.toString() +
- ", groups=" + groups +
- ", attributes=" + attributes +
- ", composingConstraints=" + composingConstraints +
- ", isReportAsSingleInvalidConstraint=" + isReportAsSingleInvalidConstraint +
- '}';
- }
-
- private Map<String, Object> getAnnotationParameters(Annotation annotation) {
- Method[] declaredMethods = annotation.annotationType().getDeclaredMethods();
- Map<String, Object> parameters = new HashMap<String, Object>( declaredMethods.length );
- for ( Method m : declaredMethods ) {
- try {
- parameters.put( m.getName(), m.invoke( annotation ) );
- }
- catch ( IllegalAccessException e ) {
- throw new ValidationException( "Unable to read annotation attributes: " + annotation.getClass(), e );
- }
- catch ( InvocationTargetException e ) {
- throw new ValidationException( "Unable to read annotation attributes: " + annotation.getClass(), e );
- }
- }
- return Collections.unmodifiableMap( parameters );
- }
-
- private Object getMethodValue(Annotation annotation, Method m) {
- Object value;
- try {
- value = m.invoke( annotation );
- }
- // should never happen
- catch ( IllegalAccessException e ) {
- throw new ValidationException( "Unable to retrieve annotation parameter value." );
- }
- catch ( InvocationTargetException e ) {
- throw new ValidationException( "Unable to retrieve annotation parameter value." );
- }
- return value;
- }
-
- private Map<ClassIndexWrapper, Map<String, Object>> parseOverrideParameters() {
- Map<ClassIndexWrapper, Map<String, Object>> overrideParameters = new HashMap<ClassIndexWrapper, Map<String, Object>>();
- for ( Method m : annotation.annotationType().getMethods() ) {
- if ( m.getAnnotation( OverridesAttribute.class ) != null ) {
- addOverrideAttributes(
- overrideParameters, m, m.getAnnotation( OverridesAttribute.class )
- );
- }
- else if ( m.getAnnotation( OverridesAttribute.List.class ) != null ) {
- addOverrideAttributes(
- overrideParameters,
- m,
- m.getAnnotation( OverridesAttribute.List.class ).value()
- );
- }
- }
- return overrideParameters;
- }
-
- private void addOverrideAttributes(Map<ClassIndexWrapper, Map<String, Object>> overrideParameters, Method m, OverridesAttribute... attributes) {
-
- Object value = getMethodValue( annotation, m );
- for ( OverridesAttribute overridesAttribute : attributes ) {
- ensureAttributeIsOverridable( m, overridesAttribute );
-
- ClassIndexWrapper wrapper = new ClassIndexWrapper(
- overridesAttribute.constraint(), overridesAttribute.constraintIndex()
- );
- Map<String, Object> map = overrideParameters.get( wrapper );
- if ( map == null ) {
- map = new HashMap<String, Object>();
- overrideParameters.put( wrapper, map );
- }
- map.put( overridesAttribute.name(), value );
- }
- }
-
- private void ensureAttributeIsOverridable(Method m, OverridesAttribute overridesAttribute) {
- try {
- Class<?> returnTypeOfOverridenConstraint = overridesAttribute.constraint()
- .getMethod( overridesAttribute.name() )
- .getReturnType();
- if ( !returnTypeOfOverridenConstraint.equals( m.getReturnType() ) ) {
- String message = "The overiding type of a composite constraint must be identical to the overwridden one. Expected " + returnTypeOfOverridenConstraint
- .getName() + " found " + m.getReturnType();
- throw new ConstraintDefinitionException( message );
- }
- }
- catch ( NoSuchMethodException nsme ) {
- throw new ConstraintDefinitionException(
- "Overriden constraint does not define an attribute with name " + overridesAttribute.name()
- );
- }
- }
-
- private void parseComposingConstraints(Map<ClassIndexWrapper, Map<String, Object>> overrideParameters) {
- for ( Annotation declaredAnnotation : annotation.annotationType().getDeclaredAnnotations() ) {
- if ( constraintHelper.isConstraintAnnotation( declaredAnnotation )
- || constraintHelper.isBuiltinConstraint( declaredAnnotation.annotationType() ) ) {
- ConstraintDescriptorImpl<?> descriptor = createComposingConstraintDescriptor(
- declaredAnnotation, overrideParameters, OVERRIDES_PARAMETER_DEFAULT_INDEX
- );
- composingConstraints.add( descriptor );
- log.debug( "Adding composing constraint: " + descriptor );
- }
- else if ( constraintHelper.isMultiValueConstraint( declaredAnnotation ) ) {
- List<Annotation> multiValueConstraints = constraintHelper.getMultiValueConstraints( declaredAnnotation );
- int index = 1;
- for ( Annotation constraintAnnotation : multiValueConstraints ) {
- ConstraintDescriptorImpl<?> descriptor = createComposingConstraintDescriptor(
- constraintAnnotation, overrideParameters, index
- );
- composingConstraints.add( descriptor );
- log.debug( "Adding composing constraint: " + descriptor );
- index++;
- }
- }
- }
- }
-
- private <U extends Annotation> ConstraintDescriptorImpl<U> createComposingConstraintDescriptor(U declaredAnnotation, Map<ClassIndexWrapper, Map<String, Object>> overrideParameters, int index) {
- //TODO don't quite understand this warning
- //TODO assuming U.getClass() returns Class<U>
- @SuppressWarnings("unchecked")
- final Class<U> annotationType = ( Class<U> ) declaredAnnotation.annotationType();
- return createComposingConstraintDescriptor(
- overrideParameters,
- index,
- declaredAnnotation,
- annotationType
- );
- }
-
- private <U extends Annotation> ConstraintDescriptorImpl<U> createComposingConstraintDescriptor(Map<ClassIndexWrapper, Map<String, Object>> overrideParameters, int index, U constraintAnnotation, Class<U> annotationType) {
- // use a annotation proxy
- AnnotationDescriptor<U> annotationDescriptor = new AnnotationDescriptor<U>(
- annotationType, getAnnotationParameters( constraintAnnotation )
- );
-
- // get the right override parameters
- Map<String, Object> overrides = overrideParameters.get(
- new ClassIndexWrapper(
- annotationType, index
- )
- );
- if ( overrides != null ) {
- for ( Map.Entry<String, Object> entry : overrides.entrySet() ) {
- annotationDescriptor.setValue( entry.getKey(), entry.getValue() );
- }
- }
-
- // groups get inherited from the parent
- annotationDescriptor.setValue( "groups", groups.toArray( new Class<?>[] { } ) );
-
- U annotationProxy = AnnotationFactory.create( annotationDescriptor );
- return new ConstraintDescriptorImpl<U>(
- annotationProxy, constraintHelper
- );
- }
-
- /**
- * A wrapper class to keep track for which compposing constraints (class and index) a given attribute override applies to.
- */
- private class ClassIndexWrapper {
- final Class<?> clazz;
- final int index;
-
- ClassIndexWrapper(Class<?> clazz, int index) {
- this.clazz = clazz;
- this.index = index;
- }
-
- @Override
- public boolean equals(Object o) {
- if ( this == o ) {
- return true;
- }
- if ( o == null || getClass() != o.getClass() ) {
- return false;
- }
-
- ClassIndexWrapper that = ( ClassIndexWrapper ) o;
-
- if ( index != that.index ) {
- return false;
- }
- if ( clazz != null ? !clazz.equals( that.clazz ) : that.clazz != null ) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = clazz != null ? clazz.hashCode() : 0;
- result = 31 * result + index;
- return result;
- }
- }
-}
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintHelper.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintHelper.java 2009-06-16 15:29:59 UTC (rev 16797)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintHelper.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -1,335 +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.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import javax.validation.Constraint;
-import javax.validation.ConstraintDefinitionException;
-import javax.validation.ConstraintValidator;
-import javax.validation.ValidationException;
-import javax.validation.constraints.AssertFalse;
-import javax.validation.constraints.AssertTrue;
-import javax.validation.constraints.DecimalMax;
-import javax.validation.constraints.DecimalMin;
-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.hibernate.validation.constraints.impl.AssertFalseValidator;
-import org.hibernate.validation.constraints.impl.AssertTrueValidator;
-import org.hibernate.validation.constraints.impl.DecimalMaxValidatorForNumber;
-import org.hibernate.validation.constraints.impl.DecimalMaxValidatorForString;
-import org.hibernate.validation.constraints.impl.DecimalMinValidatorForNumber;
-import org.hibernate.validation.constraints.impl.DecimalMinValidatorForString;
-import org.hibernate.validation.constraints.impl.DigitsValidatorForNumber;
-import org.hibernate.validation.constraints.impl.DigitsValidatorForString;
-import org.hibernate.validation.constraints.impl.FutureValidatorForCalendar;
-import org.hibernate.validation.constraints.impl.FutureValidatorForDate;
-import org.hibernate.validation.constraints.impl.MaxValidatorForNumber;
-import org.hibernate.validation.constraints.impl.MaxValidatorForString;
-import org.hibernate.validation.constraints.impl.MinValidatorForNumber;
-import org.hibernate.validation.constraints.impl.MinValidatorForString;
-import org.hibernate.validation.constraints.impl.NotNullValidator;
-import org.hibernate.validation.constraints.impl.NullValidator;
-import org.hibernate.validation.constraints.impl.PastValidatorForCalendar;
-import org.hibernate.validation.constraints.impl.PastValidatorForDate;
-import org.hibernate.validation.constraints.impl.PatternValidator;
-import org.hibernate.validation.constraints.impl.SizeValidatorForArray;
-import org.hibernate.validation.constraints.impl.SizeValidatorForArraysOfBoolean;
-import org.hibernate.validation.constraints.impl.SizeValidatorForArraysOfByte;
-import org.hibernate.validation.constraints.impl.SizeValidatorForArraysOfChar;
-import org.hibernate.validation.constraints.impl.SizeValidatorForArraysOfDouble;
-import org.hibernate.validation.constraints.impl.SizeValidatorForArraysOfFloat;
-import org.hibernate.validation.constraints.impl.SizeValidatorForArraysOfInt;
-import org.hibernate.validation.constraints.impl.SizeValidatorForArraysOfLong;
-import org.hibernate.validation.constraints.impl.SizeValidatorForCollection;
-import org.hibernate.validation.constraints.impl.SizeValidatorForMap;
-import org.hibernate.validation.constraints.impl.SizeValidatorForString;
-import org.hibernate.validation.util.ReflectionHelper;
-
-/**
- * Keeps track of builtin constraints and their validator implementations, as well as already resolved validator definitions.
- *
- * @author Hardy Ferentschik
- * @author Alaa Nassef
- */
-public class ConstraintHelper {
-
- private final static Map<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<?, ?>>>> builtinConstraints =
- new ConcurrentHashMap<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<?, ?>>>>();
-
- static {
- 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( DecimalMaxValidatorForNumber.class );
- constraintList.add( DecimalMaxValidatorForString.class );
- builtinConstraints.put( DecimalMax.class, constraintList );
-
- constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
- constraintList.add( DecimalMinValidatorForNumber.class );
- constraintList.add( DecimalMinValidatorForString.class );
- builtinConstraints.put( DecimalMin.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( 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( PatternValidator.class );
- builtinConstraints.put( Pattern.class, constraintList );
-
- constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
- constraintList.add( SizeValidatorForString.class );
- constraintList.add( SizeValidatorForCollection.class );
- constraintList.add( SizeValidatorForArray.class );
- constraintList.add( SizeValidatorForMap.class );
- constraintList.add( SizeValidatorForArraysOfBoolean.class );
- constraintList.add( SizeValidatorForArraysOfByte.class );
- constraintList.add( SizeValidatorForArraysOfChar.class );
- constraintList.add( SizeValidatorForArraysOfDouble.class );
- constraintList.add( SizeValidatorForArraysOfFloat.class );
- constraintList.add( SizeValidatorForArraysOfInt.class );
- constraintList.add( SizeValidatorForArraysOfLong.class );
- builtinConstraints.put( Size.class, constraintList );
- }
-
- private final Map<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<? extends Annotation, ?>>>> constraintValidatorDefinitons =
- new ConcurrentHashMap<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<? extends Annotation, ?>>>>();
-
- public List<Class<? extends ConstraintValidator<? extends Annotation, ?>>> getBuiltInConstraints(Class<? extends Annotation> annotationType) {
- final List<Class<? extends ConstraintValidator<?, ?>>> builtInList = getBuiltInFromAnnotationType(
- annotationType
- );
-
- if ( builtInList == null || builtInList.size() == 0 ) {
- throw new ValidationException( "Unable to find constraints for " + annotationType );
- }
- List<Class<? extends ConstraintValidator<? extends Annotation, ?>>> constraints =
- new ArrayList<Class<? extends ConstraintValidator<? extends Annotation, ?>>>( builtInList.size() );
- for ( Class<? extends ConstraintValidator<?, ?>> validatorClass : builtInList ) {
- //safe cause all CV for a given annotation A are CV<A, ?>
- @SuppressWarnings("unchecked")
- Class<ConstraintValidator<? extends Annotation, ?>> safeValdiatorClass = ( Class<ConstraintValidator<? extends Annotation, ?>> ) validatorClass;
- constraints.add( safeValdiatorClass );
- }
-
- return constraints;
- }
-
- private List<Class<? extends ConstraintValidator<?, ?>>> getBuiltInFromAnnotationType(Class<? extends Annotation> annotationType) {
- return builtinConstraints.get( annotationType );
- }
-
- public boolean isBuiltinConstraint(Class<? extends Annotation> annotationType) {
- return builtinConstraints.containsKey( 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.annotationType() ) ) {
- 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.annotationType() ) ) {
- annotationList.add( a );
- }
- }
- }
- }
- catch ( NoSuchMethodException nsme ) {
- // ignore
- }
- catch ( IllegalAccessException iae ) {
- // ignore
- }
- catch ( InvocationTargetException ite ) {
- // ignore
- }
- return annotationList;
- }
-
- /**
- * Checks whether 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.";
- throw new ConstraintDefinitionException( msg );
- }
-
- try {
- Class<?>[] defaultGroups = ( Class<?>[] ) annotation.annotationType()
- .getMethod( "groups" )
- .getDefaultValue();
- if ( defaultGroups.length != 0 ) {
- String msg = annotation.annotationType()
- .getName() + " contains Constraint annotation, but the groups " +
- "paramter default value is not empty.";
- throw new ConstraintDefinitionException( msg );
- }
- }
- catch ( NoSuchMethodException nsme ) {
- String msg = annotation.annotationType().getName() + " contains Constraint annotation, but does " +
- "not contain a groups parameter.";
- throw new ConstraintDefinitionException( msg );
- }
-
- 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.";
- throw new ConstraintDefinitionException( msg );
- }
- }
- return true;
- }
-
- public List<Class<? extends ConstraintValidator<? extends Annotation, ?>>> getConstraintValidatorDefinition(Class<? extends Annotation> annotationClass) {
- if ( annotationClass == null ) {
- throw new IllegalArgumentException( "Class cannot be null" );
- }
- return constraintValidatorDefinitons.get( annotationClass );
- }
-
- public <A extends Annotation> void addConstraintValidatorDefinition(Class<A> annotationClass, List<Class<? extends ConstraintValidator<? extends Annotation, ?>>> definitionClasses) {
- constraintValidatorDefinitons.put( annotationClass, definitionClasses );
- }
-
- public boolean containsConstraintValidatorDefinition(Class<? extends Annotation> annotationClass) {
- return constraintValidatorDefinitons.containsKey( annotationClass );
- }
-}
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-06-16 15:29:59 UTC (rev 16797)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -36,6 +36,8 @@
import org.hibernate.validation.util.LoggerFactory;
import org.hibernate.validation.util.ValidatorTypeHelper;
+import org.hibernate.validation.engine.ExecutionContext;
+import org.hibernate.validation.engine.ConstraintValidatorContextImpl;
/**
* Due to constraint conposition a single constraint annotation can lead to a whole constraint tree beeing validated.
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ElementDescriptorImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ElementDescriptorImpl.java 2009-06-16 15:29:59 UTC (rev 16797)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ElementDescriptorImpl.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -1,64 +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.util.Collections;
-import java.util.HashSet;
-import java.util.Set;
-import javax.validation.metadata.ConstraintDescriptor;
-import javax.validation.metadata.ElementDescriptor;
-
-/**
- * Describe a validated element (class, field or property).
- *
- * @author Emmanuel Bernard
- * @author Hardy Ferentschik
- */
-public class ElementDescriptorImpl implements ElementDescriptor {
- private final Class<?> type;
- private final Set<ConstraintDescriptor<?>> constraintDescriptors = new HashSet<ConstraintDescriptor<?>>();
-
- public ElementDescriptorImpl(Class<?> type) {
- this.type = type;
- }
-
- public void addConstraintDescriptor(ConstraintDescriptorImpl constraintDescriptor) {
- constraintDescriptors.add( constraintDescriptor );
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean hasConstraints() {
- return constraintDescriptors.size() != 0;
- }
-
- /**
- * {@inheritDoc}
- */
- public Class<?> getType() {
- return type;
- }
-
- /**
- * {@inheritDoc}
- */
- public Set<ConstraintDescriptor<?>> getConstraintDescriptors() {
- return Collections.unmodifiableSet( constraintDescriptors );
- }
-}
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-06-16 15:29:59 UTC (rev 16797)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ExecutionContext.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -35,6 +35,7 @@
import javax.validation.TraversableResolver;
import org.hibernate.validation.util.IdentitySet;
+import org.hibernate.validation.metadata.MetaConstraint;
/**
* Context object keeping track of all processed objects and failing constraints.
Deleted: 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-06-16 15:29:59 UTC (rev 16797)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -1,176 +0,0 @@
-// $Id$// $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.annotation.ElementType;
-import java.lang.reflect.Field;
-import java.lang.reflect.Member;
-import java.lang.reflect.Method;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-import javax.validation.metadata.ConstraintDescriptor;
-import javax.validation.ConstraintViolation;
-
-import org.hibernate.validation.util.ReflectionHelper;
-
-/**
- * Instances of this class abstract the constraint type (class, method or field constraint) and gives access to
- * meta data about the constraint. This allows a unified handling of constraints in the validator imlpementation.
- *
- * @author Hardy Ferentschik
- */
-public class MetaConstraint<T, A extends Annotation> {
-
- /**
- * The constraint tree created from the constraint annotation.
- */
- private final ConstraintTree<A> constraintTree;
-
- /**
- * The member the constraint was defined on.
- */
- private final Member member;
-
- /**
- * The JavaBeans name for this constraint.
- */
- private final String propertyName;
-
- /**
- * Describes on which level (<code>TYPE</code>, <code>METHOD</code>, <code>FIELD</code>) the constraint was
- * defined on.
- */
- private final ElementType elementType;
-
- /**
- * The class of the bean hosting this constraint.
- */
- private final Class<T> beanClass;
-
- public MetaConstraint(Class<T> beanClass, ConstraintDescriptor<A> constraintDescriptor) {
- this.elementType = ElementType.TYPE;
- this.member = null;
- this.propertyName = "";
- this.beanClass = beanClass;
- constraintTree = new ConstraintTree<A>( constraintDescriptor );
- }
-
- public MetaConstraint(Member member, Class<T> beanClass, ConstraintDescriptor<A> constraintDescriptor) {
- if ( member instanceof Method ) {
- this.elementType = ElementType.METHOD;
- }
- else if ( member instanceof Field ) {
- this.elementType = ElementType.FIELD;
- }
- else {
- throw new IllegalArgumentException( "Non allowed member type: " + member );
- }
- this.member = member;
- this.propertyName = ReflectionHelper.getPropertyName( member );
- this.beanClass = beanClass;
- constraintTree = new ConstraintTree<A>( constraintDescriptor );
- }
-
-
- /**
- * @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.
- */
- public Set<Class<?>> getGroupList() {
- return constraintTree.getDescriptor().getGroups();
- }
-
- public ConstraintDescriptor getDescriptor() {
- return constraintTree.getDescriptor();
- }
-
- public Class<T> getBeanClass() {
- return beanClass;
- }
-
- public String getPropertyName() {
- return propertyName;
- }
-
- public ElementType getElementType() {
- return elementType;
- }
-
- public ConstraintTree getConstraintTree() {
- return constraintTree;
- }
-
- public <T> boolean validateConstraint(ExecutionContext<T> executionContext) {
- final Object leafBeanInstance = executionContext.peekCurrentBean();
- Object value = getValue( leafBeanInstance );
- List<ConstraintViolation<T>> constraintViolations = new ArrayList<ConstraintViolation<T>>();
- constraintTree.validateConstraints( value, typeOfAnnoatedElement(), executionContext, constraintViolations );
- if ( constraintViolations.size() > 0 ) {
- executionContext.addConstraintFailures( constraintViolations );
- return false;
- }
- return true;
- }
-
- public <T> boolean validateConstraint(Object value, ExecutionContext<T> executionContext) {
- List<ConstraintViolation<T>> constraintViolations = new ArrayList<ConstraintViolation<T>>();
- constraintTree.validateConstraints( value, typeOfAnnoatedElement(), executionContext, constraintViolations );
- if ( constraintViolations.size() > 0 ) {
- executionContext.addConstraintFailures( constraintViolations );
- return false;
- }
- return true;
- }
-
- private Type typeOfAnnoatedElement() {
- Type t;
- switch ( elementType ) {
- case TYPE: {
- t = beanClass;
- break;
- }
- default: {
- t = ReflectionHelper.typeOf( member );
- if ( t instanceof Class && ((Class) t).isPrimitive()) {
- t = ReflectionHelper.boxedTyp( t );
- }
- }
- }
- return t;
- }
-
- /**
- * @param o the object from which to retrieve the value.
- *
- * @return Returns the value for this constraint from the specified object. Depending on the type either the value itself
- * is returned of method or field access is used to access the value.
- */
- private Object getValue(Object o) {
- switch ( elementType ) {
- case TYPE: {
- return o;
- }
- default: {
- return ReflectionHelper.getValue( member, o );
- }
- }
- }
-}
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/PropertyDescriptorImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/PropertyDescriptorImpl.java 2009-06-16 15:29:59 UTC (rev 16797)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/PropertyDescriptorImpl.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -1,52 +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 javax.validation.metadata.PropertyDescriptor;
-
-/**
- * Describe a validated element (class, field or property).
- *
- * @author Emmanuel Bernard
- * @author Hardy Ferentschik
- */
-public class PropertyDescriptorImpl extends ElementDescriptorImpl implements PropertyDescriptor {
- private final boolean cascaded;
- private final String property;
-
-
- public PropertyDescriptorImpl(Class<?> returnType, boolean cascaded, String property) {
- super( returnType );
- this.cascaded = cascaded;
- this.property = property;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isCascaded() {
- return cascaded;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getPropertyName() {
- return property;
- }
-}
\ No newline at end of file
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-06-16 15:29:59 UTC (rev 16797)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorContextImpl.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -6,6 +6,9 @@
import javax.validation.Validator;
import javax.validation.ValidatorContext;
+import org.hibernate.validation.metadata.BeanMetaDataCache;
+import org.hibernate.validation.metadata.ConstraintHelper;
+
/**
* @author Emmanuel Bernard
* @author Hardy Ferentschik
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-06-16 15:29:59 UTC (rev 16797)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorFactoryImpl.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -30,8 +30,12 @@
import javax.validation.ValidationException;
import javax.validation.spi.ConfigurationState;
-import org.hibernate.validation.engine.xml.AnnotationIgnores;
-import org.hibernate.validation.engine.xml.XmlMappingParser;
+import org.hibernate.validation.metadata.AnnotationIgnores;
+import org.hibernate.validation.xml.XmlMappingParser;
+import org.hibernate.validation.metadata.BeanMetaDataImpl;
+import org.hibernate.validation.metadata.BeanMetaDataCache;
+import org.hibernate.validation.metadata.MetaConstraint;
+import org.hibernate.validation.metadata.ConstraintHelper;
/**
* Factory returning initialized <code>Validator</code> instances.
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-06-16 15:29:59 UTC (rev 16797)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -47,6 +47,11 @@
import org.hibernate.validation.util.LoggerFactory;
import org.hibernate.validation.util.PropertyPath;
import org.hibernate.validation.util.ReflectionHelper;
+import org.hibernate.validation.metadata.BeanMetaData;
+import org.hibernate.validation.metadata.BeanMetaDataImpl;
+import org.hibernate.validation.metadata.BeanMetaDataCache;
+import org.hibernate.validation.metadata.MetaConstraint;
+import org.hibernate.validation.metadata.ConstraintHelper;
/**
* The main Bean Validation class. This is the core processing class of Hibernate Validator.
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/AnnotationIgnores.java (from rev 16797, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/AnnotationIgnores.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/AnnotationIgnores.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/AnnotationIgnores.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -0,0 +1,119 @@
+// $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.metadata;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Member;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.slf4j.Logger;
+
+import org.hibernate.validation.util.LoggerFactory;
+
+/**
+ * This class instantiated during the parsing of the XML configuration data and keeps
+ * track of the annotations which should be ignored.
+ *
+ * @author Hardy Ferentschik
+ */
+public class AnnotationIgnores {
+
+ private static final Logger log = LoggerFactory.make();
+
+ /**
+ * Keeps track whether the 'ignore-annotations' flag is set on bean level in the xml configuration. If 'ignore-annotations'
+ * is not specified <code>false</code> is the default.
+ */
+ private final Map<Class<?>, Boolean> ignoreAnnotationDefaults = new HashMap<Class<?>, Boolean>();
+
+ /**
+ * Keeps track of explicitly excluded members (fields and properties) for a given class. If a member appears in
+ * the list mapped to a given class 'ignore-annotations' was explicitly set to <code>true</code> in the configuration
+ * for this class.
+ */
+ private final Map<Class<?>, List<Member>> ignoreAnnotationOnMember = new HashMap<Class<?>, List<Member>>();
+
+ private final List<Class<?>> ignoreAnnotationOnClass = new ArrayList<Class<?>>();
+
+ public void setDefaultIgnoreAnnotation(Class<?> clazz, Boolean b) {
+ if ( b == null ) {
+ ignoreAnnotationDefaults.put( clazz, Boolean.FALSE );
+ }
+ else {
+ ignoreAnnotationDefaults.put( clazz, b );
+ }
+ }
+
+ public boolean getDefaultIgnoreAnnotation(Class<?> clazz) {
+ return ignoreAnnotationDefaults.containsKey( clazz ) && ignoreAnnotationDefaults.get( clazz );
+ }
+
+ public void setIgnoreAnnotationsOnMember(Member member) {
+ Class<?> beanClass = member.getDeclaringClass();
+ if ( ignoreAnnotationOnMember.get( beanClass ) == null ) {
+ List<Member> tmpList = new ArrayList<Member>();
+ tmpList.add( member );
+ ignoreAnnotationOnMember.put( beanClass, tmpList );
+ }
+ else {
+ ignoreAnnotationOnMember.get( beanClass ).add( member );
+ }
+ }
+
+ public boolean isIgnoreAnnotations(Member member) {
+ boolean ignoreAnnotation;
+ Class<?> clazz = member.getDeclaringClass();
+ List<Member> ignoreAnnotationForMembers = ignoreAnnotationOnMember.get( clazz );
+ if ( ignoreAnnotationForMembers == null || !ignoreAnnotationForMembers.contains( member ) ) {
+ ignoreAnnotation = getDefaultIgnoreAnnotation( clazz );
+ }
+ else {
+ ignoreAnnotation = ignoreAnnotationForMembers.contains( member );
+ }
+ if ( ignoreAnnotation ) {
+ logMessage( member, clazz );
+ }
+ return ignoreAnnotation;
+ }
+
+ private void logMessage(Member member, Class<?> clazz) {
+ String type;
+ if ( member instanceof Field ) {
+ type = "Field";
+ }
+ else {
+ type = "Property";
+ }
+ log.debug( type + " level annotations are getting ignored for " + clazz.getName() + "." + member.getName() );
+ }
+
+ public void setIgnoreAnnotationsOnClass(Class<?> clazz) {
+ ignoreAnnotationOnClass.add( clazz );
+ }
+
+ public boolean isIgnoreAnnotations(Class<?> clazz) {
+ boolean ignoreAnnotation = ignoreAnnotationOnClass.contains( clazz ) || getDefaultIgnoreAnnotation( clazz );
+ if ( log.isDebugEnabled() && ignoreAnnotation ) {
+ log.debug( "Class level annotation are getting ignored for " + clazz.getName() );
+ }
+ return ignoreAnnotation;
+ }
+}
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/BeanDescriptorImpl.java (from rev 16797, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanDescriptorImpl.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/BeanDescriptorImpl.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/BeanDescriptorImpl.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -0,0 +1,30 @@
+package org.hibernate.validation.metadata;
+
+import java.util.Set;
+import javax.validation.metadata.BeanDescriptor;
+import javax.validation.metadata.PropertyDescriptor;
+
+/**
+ * @author Emmanuel Bernard
+ * @author Hardy Ferentschik
+ */
+public class BeanDescriptorImpl<T> extends ElementDescriptorImpl implements BeanDescriptor {
+ private final BeanMetaData<T> metadataBean;
+
+ public BeanDescriptorImpl(BeanMetaData<T> metadataBean) {
+ super( metadataBean.getBeanClass() );
+ this.metadataBean = metadataBean;
+ }
+
+ public boolean isBeanConstrained() {
+ return metadataBean.getConstrainedProperties().size() > 0;
+ }
+
+ public PropertyDescriptor getConstraintsForProperty(String propertyName) {
+ return metadataBean.getPropertyDescriptor( propertyName );
+ }
+
+ public Set<PropertyDescriptor> getConstrainedProperties() {
+ return metadataBean.getConstrainedProperties();
+ }
+}
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/BeanMetaData.java (from rev 16797, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaData.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/BeanMetaData.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/BeanMetaData.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -0,0 +1,77 @@
+// $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.metadata;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Member;
+import java.util.List;
+import java.util.Set;
+import javax.validation.metadata.BeanDescriptor;
+import javax.validation.metadata.PropertyDescriptor;
+
+import org.hibernate.validation.metadata.MetaConstraint;
+
+/**
+ * Interface defining the meta data about the constraints defined in a given bean.
+ *
+ * @author Hardy Ferentschik
+ */
+public interface BeanMetaData<T> {
+
+ /**
+ * @return the class of the bean.
+ */
+ Class<T> getBeanClass();
+
+ /**
+ * @return an instance of <code>ElementDescriptor</code> describing the bean this meta data applies for.
+ */
+ BeanDescriptor getBeanDescriptor();
+
+ /**
+ * @return A list of all cascaded methods and fields (methods/fields annotated with @Valid).
+ */
+ List<Member> getCascadedMembers();
+
+ /**
+ * @return A map mapping defined group sequences to a list of groups.
+ */
+ List<Class<?>> getDefaultGroupSequence();
+
+ /**
+ * @return A list of <code>MetaConstraint</code> instances encapsulating the information of all the constraints
+ * defined on the bean.
+ */
+ List<MetaConstraint<T, ? extends Annotation>> geMetaConstraintList();
+
+ /**
+ * Return <code>PropertyDescriptor</code> for the given property.
+ *
+ * @param property the property for which to retrieve the descriptor.
+ *
+ * @return Returns the <code>PropertyDescriptor</code> for the given property or <code>null</code> in case the
+ * property does not have a descriptor.
+ */
+ PropertyDescriptor getPropertyDescriptor(String property);
+
+ /**
+ * @return the property descriptors having at least one constraint defined or which are marked
+ * as cascaded (@Valid).
+ */
+ Set<PropertyDescriptor> getConstrainedProperties();
+}
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/BeanMetaDataCache.java (from rev 16797, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataCache.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/BeanMetaDataCache.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/BeanMetaDataCache.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -0,0 +1,48 @@
+// $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.metadata;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * Cache for created instances of <code>BeanMetaData</code>.
+ *
+ * @author Hardy Ferentschik
+ */
+public class BeanMetaDataCache {
+ /**
+ * A map for the meta data for each entity. The key is the class and the value the bean meta data for this
+ * entity.
+ */
+ private Map<Class<?>, BeanMetaDataImpl<?>> metadataProviders = new ConcurrentHashMap<Class<?>, BeanMetaDataImpl<?>>(
+ 10
+ );
+
+ @SuppressWarnings("unchecked")
+ public <T> BeanMetaDataImpl<T> getBeanMetaData(Class<T> beanClass) {
+ if ( beanClass == null ) {
+ throw new IllegalArgumentException( "Class cannot be null" );
+ }
+ return ( BeanMetaDataImpl<T> ) metadataProviders.get( beanClass );
+ }
+
+ public <T> void addBeanMetaData(Class<T> beanClass, BeanMetaDataImpl<T> metaData) {
+ metadataProviders.put( beanClass, metaData );
+ }
+}
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/BeanMetaDataImpl.java (from rev 16797, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataImpl.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/BeanMetaDataImpl.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/BeanMetaDataImpl.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -0,0 +1,390 @@
+// $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.metadata;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.AnnotatedElement;
+import java.lang.reflect.Field;
+import java.lang.reflect.Member;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.validation.GroupSequence;
+import javax.validation.Valid;
+import javax.validation.ValidationException;
+import javax.validation.groups.Default;
+import javax.validation.metadata.BeanDescriptor;
+import javax.validation.metadata.PropertyDescriptor;
+
+import org.slf4j.Logger;
+
+import org.hibernate.validation.metadata.AnnotationIgnores;
+import org.hibernate.validation.util.LoggerFactory;
+import org.hibernate.validation.util.ReflectionHelper;
+import org.hibernate.validation.metadata.MetaConstraint;
+
+
+/**
+ * This class encapsulates all meta data needed for validation. Implementations of {@code Validator} interface can
+ * instantiate an instance of this class and delegate the metadata extraction to it.
+ *
+ * @author Hardy Ferentschik
+ */
+
+public class BeanMetaDataImpl<T> implements BeanMetaData<T> {
+
+ private static final Logger log = LoggerFactory.make();
+
+ /**
+ * The root bean class for this validator.
+ */
+ private final Class<T> beanClass;
+
+ /**
+ * The main element descriptor for <code>beanClass</code>.
+ */
+ private BeanDescriptorImpl<T> beanDescriptor;
+
+ /**
+ * List of constraints.
+ */
+ private List<MetaConstraint<T, ? extends Annotation>> metaConstraintList = new ArrayList<MetaConstraint<T, ? extends Annotation>>();
+
+ /**
+ * List of cascaded members.
+ */
+ private List<Member> cascadedMembers = new ArrayList<Member>();
+
+ /**
+ * Maps field and method names to their <code>ElementDescriptorImpl</code>.
+ */
+ private Map<String, PropertyDescriptor> propertyDescriptors = new HashMap<String, PropertyDescriptor>();
+
+ /**
+ * Maps group sequences to the list of group/sequences.
+ */
+ private List<Class<?>> defaultGroupSequence = new ArrayList<Class<?>>();
+
+ /**
+ * Object keeping track of all constraints.
+ */
+ private final ConstraintHelper constraintHelper;
+
+
+ public BeanMetaDataImpl(Class<T> beanClass, ConstraintHelper constraintHelper) {
+ this(
+ beanClass,
+ constraintHelper,
+ new AnnotationIgnores()
+ );
+ }
+
+ public BeanMetaDataImpl(Class<T> beanClass, ConstraintHelper constraintHelper, AnnotationIgnores annotationIgnores) {
+ this.beanClass = beanClass;
+ this.constraintHelper = constraintHelper;
+ createMetaData( annotationIgnores );
+ }
+
+ public Class<T> getBeanClass() {
+ return beanClass;
+ }
+
+ public BeanDescriptor getBeanDescriptor() {
+ return beanDescriptor;
+ }
+
+ public List<Member> getCascadedMembers() {
+ return Collections.unmodifiableList( cascadedMembers );
+ }
+
+ public List<MetaConstraint<T, ? extends Annotation>> geMetaConstraintList() {
+ return Collections.unmodifiableList( metaConstraintList );
+ }
+
+ public void addMetaConstraint(MetaConstraint<T, ? extends Annotation> metaConstraint) {
+ metaConstraintList.add( metaConstraint );
+ }
+
+ public void addCascadedMember(Member member) {
+ cascadedMembers.add( member );
+ }
+
+ public PropertyDescriptor getPropertyDescriptor(String property) {
+ return propertyDescriptors.get( property );
+ }
+
+ public List<Class<?>> getDefaultGroupSequence() {
+ return Collections.unmodifiableList( defaultGroupSequence );
+ }
+
+ public void setDefaultGroupSequence(List<Class<?>> groupSequence) {
+ defaultGroupSequence = new ArrayList<Class<?>>();
+ for ( Class<?> group : groupSequence ) {
+ if ( group.getName().equals( beanClass.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.isTraceEnabled() ) {
+ log.trace(
+ "Members of the default group sequence for bean {} are: {}",
+ beanClass.getName(),
+ defaultGroupSequence
+ );
+ }
+ }
+
+ public Set<PropertyDescriptor> getConstrainedProperties() {
+ return Collections.unmodifiableSet( new HashSet<PropertyDescriptor>( propertyDescriptors.values() ) );
+ }
+
+ /**
+ * Create bean desciptor, find all classes/subclasses/interfaces which have to be taken in consideration
+ * for this validator and create meta data.
+ *
+ * @param annotationIgnores Datastructure keeping track on which annotation should be ignored.
+ */
+ private void createMetaData(AnnotationIgnores annotationIgnores) {
+ beanDescriptor = new BeanDescriptorImpl<T>( this );
+ initDefaultGroupSequence();
+ List<Class> classes = new ArrayList<Class>();
+ computeClassHierarchy( beanClass, classes );
+ for ( Class current : classes ) {
+ initClass( current, annotationIgnores );
+ }
+ }
+
+ /**
+ * Get all superclasses and interfaces recursively.
+ *
+ * @param clazz The class to start the search with.
+ * @param classes List of classes to which to add all found super classes and interfaces.
+ */
+ private void computeClassHierarchy(Class clazz, List<Class> classes) {
+ if ( log.isTraceEnabled() ) {
+ log.trace( "Processing: {}", clazz );
+ }
+ for ( Class current = clazz; current != null; current = current.getSuperclass() ) {
+ if ( classes.contains( current ) ) {
+ return;
+ }
+ classes.add( current );
+ for ( Class currentInterface : current.getInterfaces() ) {
+ computeClassHierarchy( currentInterface, classes );
+ }
+ }
+ }
+
+ private void initClass(Class clazz, AnnotationIgnores annotationIgnores) {
+ initClassConstraints( clazz, annotationIgnores );
+ initMethodConstraints( clazz, annotationIgnores );
+ initFieldConstraints( clazz, annotationIgnores );
+ }
+
+ /**
+ * Checks whether there is a default group sequence defined for this class.
+ * See HV-113.
+ */
+ private void initDefaultGroupSequence() {
+ List<Class<?>> groupSequence = new ArrayList<Class<?>>();
+ GroupSequence groupSequenceAnnotation = beanClass.getAnnotation( GroupSequence.class );
+ if ( groupSequenceAnnotation == null ) {
+ groupSequence.add( beanClass );
+ }
+ else {
+ groupSequence.addAll( Arrays.asList( groupSequenceAnnotation.value() ) );
+ }
+ setDefaultGroupSequence( groupSequence );
+ }
+
+ private void initFieldConstraints(Class clazz, AnnotationIgnores annotationIgnores) {
+ for ( Field field : clazz.getDeclaredFields() ) {
+ List<ConstraintDescriptorImpl<?>> fieldMetadata = findConstraints( field );
+ for ( ConstraintDescriptorImpl<?> constraintDescription : fieldMetadata ) {
+ if ( annotationIgnores.isIgnoreAnnotations( field ) ) {
+ break;
+ }
+ ReflectionHelper.setAccessibility( field );
+ MetaConstraint<T, ?> metaConstraint = createMetaConstraint( field, constraintDescription );
+ metaConstraintList.add( metaConstraint );
+ }
+ if ( field.isAnnotationPresent( Valid.class ) ) {
+ ReflectionHelper.setAccessibility( field );
+ cascadedMembers.add( field );
+ addPropertyDescriptorForMember( field );
+ }
+ }
+ }
+
+ private void initMethodConstraints(Class clazz, AnnotationIgnores annotationIgnores) {
+ for ( Method method : clazz.getDeclaredMethods() ) {
+ List<ConstraintDescriptorImpl<?>> methodMetadata = findConstraints( method );
+ for ( ConstraintDescriptorImpl<?> constraintDescription : methodMetadata ) {
+ if ( annotationIgnores.isIgnoreAnnotations( method ) ) {
+ break;
+ }
+ ReflectionHelper.setAccessibility( method );
+ MetaConstraint<T, ?> metaConstraint = createMetaConstraint( method, constraintDescription );
+ metaConstraintList.add( metaConstraint );
+ }
+ if ( method.isAnnotationPresent( Valid.class ) ) {
+ ReflectionHelper.setAccessibility( method );
+ cascadedMembers.add( method );
+ addPropertyDescriptorForMember( method );
+ }
+ }
+ }
+
+ private PropertyDescriptorImpl addPropertyDescriptorForMember(Member member) {
+ String name = ReflectionHelper.getPropertyName( member );
+ PropertyDescriptorImpl propertyDescriptor = ( PropertyDescriptorImpl ) propertyDescriptors.get(
+ name
+ );
+ if ( propertyDescriptor == null ) {
+ propertyDescriptor = new PropertyDescriptorImpl(
+ ReflectionHelper.getType( member ),
+ ( ( AnnotatedElement ) member ).isAnnotationPresent( Valid.class ),
+ name
+ );
+ propertyDescriptors.put( name, propertyDescriptor );
+ }
+ return propertyDescriptor;
+ }
+
+ private void initClassConstraints(Class<?> clazz, AnnotationIgnores annotationIgnores) {
+ if ( annotationIgnores.isIgnoreAnnotations( clazz ) ) {
+ return;
+ }
+ List<ConstraintDescriptorImpl<?>> classMetadata = findClassLevelConstraints( clazz );
+ for ( ConstraintDescriptorImpl<?> constraintDescription : classMetadata ) {
+ MetaConstraint<T, ?> metaConstraint = createMetaConstraint( constraintDescription );
+ metaConstraintList.add( metaConstraint );
+ }
+ }
+
+ private <A extends Annotation> MetaConstraint<T, ?> createMetaConstraint(ConstraintDescriptorImpl<A> descriptor) {
+ return new MetaConstraint<T, A>( beanClass, descriptor );
+ }
+
+ private <A extends Annotation> MetaConstraint<T, ?> createMetaConstraint(Member m, ConstraintDescriptorImpl<A> descriptor) {
+ return new MetaConstraint<T, A>( m, beanClass, descriptor );
+ }
+
+ /**
+ * Examines the given annotation to see whether it is a single or multi valued constraint annotation.
+ *
+ * @param clazz the class we are currently processing.
+ * @param annotation The annotation to examine.
+ *
+ * @return A list of constraint descriptors or the empty list in case <code>annotation</code> is neither a
+ * single nor multi value annotation.
+ */
+ private <A extends Annotation> List<ConstraintDescriptorImpl<?>> findConstraintAnnotations(Class<?> clazz, A annotation) {
+ List<ConstraintDescriptorImpl<?>> constraintDescriptors = new ArrayList<ConstraintDescriptorImpl<?>>();
+
+ List<Annotation> constraints = new ArrayList<Annotation>();
+ if ( constraintHelper.isConstraintAnnotation( annotation ) ||
+ constraintHelper.isBuiltinConstraint( annotation.annotationType() ) ) {
+ constraints.add( annotation );
+ }
+
+ // check if we have a multi value constraint
+ constraints.addAll( constraintHelper.getMultiValueConstraints( annotation ) );
+
+ for ( Annotation constraint : constraints ) {
+ final ConstraintDescriptorImpl constraintDescriptor = buildConstraintDescriptor( clazz, constraint );
+ constraintDescriptors.add( constraintDescriptor );
+ }
+ return constraintDescriptors;
+ }
+
+ @SuppressWarnings("unchecked")
+ private <A extends Annotation> ConstraintDescriptorImpl buildConstraintDescriptor(Class<?> clazz, A annotation) {
+ ConstraintDescriptorImpl constraintDescriptor;
+ if ( clazz.isInterface() ) {
+ constraintDescriptor = new ConstraintDescriptorImpl( annotation, constraintHelper, clazz );
+ }
+ else {
+ constraintDescriptor = new ConstraintDescriptorImpl( annotation, constraintHelper );
+ }
+ return constraintDescriptor;
+ }
+
+ /**
+ * Finds all constraint annotations defined for the given class and returns them in a list of
+ * constraint descriptors.
+ *
+ * @param beanClass The class to check for constraints annotations.
+ *
+ * @return A list of constraint descriptors for all constraint specified on the given class.
+ */
+ private List<ConstraintDescriptorImpl<?>> findClassLevelConstraints(Class<?> beanClass) {
+ List<ConstraintDescriptorImpl<?>> metadata = new ArrayList<ConstraintDescriptorImpl<?>>();
+ for ( Annotation annotation : beanClass.getAnnotations() ) {
+ metadata.addAll( findConstraintAnnotations( beanClass, annotation ) );
+ }
+ for ( ConstraintDescriptorImpl constraintDescriptor : metadata ) {
+ beanDescriptor.addConstraintDescriptor( constraintDescriptor );
+ }
+ return metadata;
+ }
+
+
+ /**
+ * Finds all constraint annotations defined for the given field/method and returns them in a list of
+ * constraint descriptors.
+ *
+ * @param member The fiels or method to check for constraints annotations.
+ *
+ * @return A list of constraint descriptors for all constraint specified for the given field or method.
+ */
+ private List<ConstraintDescriptorImpl<?>> findConstraints(Member member) {
+ assert member instanceof Field || member instanceof Method;
+
+ List<ConstraintDescriptorImpl<?>> metadata = new ArrayList<ConstraintDescriptorImpl<?>>();
+ for ( Annotation annotation : ( ( AnnotatedElement ) member ).getAnnotations() ) {
+ metadata.addAll( findConstraintAnnotations( member.getDeclaringClass(), annotation ) );
+ }
+
+ String name = ReflectionHelper.getPropertyName( member );
+ for ( ConstraintDescriptorImpl constraintDescriptor : metadata ) {
+ if ( member instanceof Method && name == null ) { // can happen if member is a Method which does not follow the bean convention
+ throw new ValidationException(
+ "Annotated methods must follow the JavaBeans naming convention. " + member.getName() + "() does not."
+ );
+ }
+ PropertyDescriptorImpl propertyDescriptor = ( PropertyDescriptorImpl ) propertyDescriptors.get( name );
+ if ( propertyDescriptor == null ) {
+ propertyDescriptor = addPropertyDescriptorForMember( member );
+ }
+ propertyDescriptor.addConstraintDescriptor( constraintDescriptor );
+ }
+ return metadata;
+ }
+}
\ No newline at end of file
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/ConstraintDescriptorImpl.java (from rev 16797, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintDescriptorImpl.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/ConstraintDescriptorImpl.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/ConstraintDescriptorImpl.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -0,0 +1,384 @@
+// $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.metadata;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.validation.Constraint;
+import javax.validation.ConstraintDefinitionException;
+import javax.validation.ConstraintValidator;
+import javax.validation.OverridesAttribute;
+import javax.validation.ReportAsSingleViolation;
+import javax.validation.ValidationException;
+import javax.validation.groups.Default;
+import javax.validation.metadata.ConstraintDescriptor;
+
+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;
+
+/**
+ * Describe a single constraint (including it's composing constraints).
+ *
+ * @author Emmanuel Bernard
+ * @author Hardy Ferentschik
+ */
+public class ConstraintDescriptorImpl<T extends Annotation> implements ConstraintDescriptor<T> {
+ private static final Logger log = LoggerFactory.make();
+ private static final int OVERRIDES_PARAMETER_DEFAULT_INDEX = -1;
+
+ /**
+ * The actual constraint annotation.
+ */
+ private final T annotation;
+
+ /**
+ * The set of classes implementing the validation for this constraint. See also
+ * <code>ConstraintValidator</code> resolution algorithm.
+ */
+ private final List<Class<? extends ConstraintValidator<T, ?>>> constraintValidatorDefinitonClasses = new ArrayList<Class<? extends ConstraintValidator<T, ?>>>();
+
+ /**
+ * The groups for which to apply this constraint.
+ */
+ private final Set<Class<?>> groups = new HashSet<Class<?>>();
+
+ /**
+ * The constraint parameters as map. The key is the paramter name and the value the
+ * parameter value as specified in the constraint.
+ */
+ private final Map<String, Object> attributes;
+
+ /**
+ * The composing constraints for this constraints.
+ */
+ private final Set<ConstraintDescriptor<?>> composingConstraints = new HashSet<ConstraintDescriptor<?>>();
+
+ /**
+ * Flag indicating if in case of a composing constraint a single error or multiple errors should be raised.
+ */
+ private final boolean isReportAsSingleInvalidConstraint;
+
+ /**
+ * Handle to the builtin constraint implementations.
+ */
+ private final ConstraintHelper constraintHelper;
+
+ public ConstraintDescriptorImpl(T annotation, ConstraintHelper constraintHelper, Class<?> implicitGroup) {
+ this( annotation, constraintHelper );
+ this.groups.add( implicitGroup );
+ }
+
+
+ public ConstraintDescriptorImpl(T annotation, ConstraintHelper constraintHelper) {
+ this.annotation = annotation;
+ this.attributes = getAnnotationParameters( annotation );
+ this.constraintHelper = constraintHelper;
+
+ this.isReportAsSingleInvalidConstraint = annotation.annotationType().isAnnotationPresent(
+ ReportAsSingleViolation.class
+ );
+
+ Class<?>[] groupsFromAnnotation = ReflectionHelper.getAnnotationParameter(
+ annotation, "groups", Class[].class
+ );
+ if ( groupsFromAnnotation.length == 0 ) {
+ groups.add( Default.class );
+ }
+ else {
+ this.groups.addAll( Arrays.asList( groupsFromAnnotation ) );
+ }
+
+ findConstraintValidatorClasses();
+ Map<ClassIndexWrapper, Map<String, Object>> overrideParameters = parseOverrideParameters();
+ parseComposingConstraints( overrideParameters );
+ }
+
+ private void findConstraintValidatorClasses() {
+ if ( constraintHelper.containsConstraintValidatorDefinition( annotation.annotationType() ) ) {
+ for ( Class<? extends ConstraintValidator<? extends Annotation, ?>> validator : constraintHelper
+ .getConstraintValidatorDefinition( annotation.annotationType() ) ) {
+ constraintValidatorDefinitonClasses.add( ( Class<? extends ConstraintValidator<T, ?>> ) validator );
+ }
+ return;
+ }
+
+ List<Class<? extends ConstraintValidator<? extends Annotation, ?>>> constraintDefinitonClasses = new ArrayList<Class<? extends ConstraintValidator<? extends Annotation, ?>>>();
+ if ( constraintHelper.isBuiltinConstraint( annotation.annotationType() ) ) {
+ constraintDefinitonClasses.addAll( constraintHelper.getBuiltInConstraints( annotation.annotationType() ) );
+ }
+ else {
+ final Class<? extends Annotation> annotationType = annotation.annotationType();
+ Class<? extends ConstraintValidator<?, ?>>[] validatedBy = annotationType
+ .getAnnotation( Constraint.class )
+ .validatedBy();
+ constraintDefinitonClasses.addAll( Arrays.asList( validatedBy ) );
+ }
+
+ constraintHelper.addConstraintValidatorDefinition(
+ annotation.annotationType(), constraintDefinitonClasses
+ );
+
+ for ( Class<? extends ConstraintValidator<? extends Annotation, ?>> validator : constraintDefinitonClasses ) {
+ @SuppressWarnings("unchecked")
+ Class<? extends ConstraintValidator<T, ?>> safeValidator = ( Class<? extends ConstraintValidator<T, ?>> ) validator;
+ constraintValidatorDefinitonClasses.add( safeValidator );
+ }
+ }
+
+ public T getAnnotation() {
+ return annotation;
+ }
+
+ public Set<Class<?>> getGroups() {
+ return Collections.unmodifiableSet( groups );
+ }
+
+ public List<Class<? extends ConstraintValidator<T, ?>>> getConstraintValidatorClasses() {
+ return Collections.unmodifiableList( constraintValidatorDefinitonClasses );
+ }
+
+ public Map<String, Object> getAttributes() {
+ return Collections.unmodifiableMap( attributes );
+ }
+
+ public Set<ConstraintDescriptor<?>> getComposingConstraints() {
+ return Collections.unmodifiableSet( composingConstraints );
+ }
+
+ public boolean isReportAsSingleViolation() {
+ return isReportAsSingleInvalidConstraint;
+ }
+
+ @Override
+ public String toString() {
+ return "ConstraintDescriptorImpl{" +
+ "annotation=" + annotation +
+ ", constraintValidatorDefinitonClasses=" + constraintValidatorDefinitonClasses.toString() +
+ ", groups=" + groups +
+ ", attributes=" + attributes +
+ ", composingConstraints=" + composingConstraints +
+ ", isReportAsSingleInvalidConstraint=" + isReportAsSingleInvalidConstraint +
+ '}';
+ }
+
+ private Map<String, Object> getAnnotationParameters(Annotation annotation) {
+ Method[] declaredMethods = annotation.annotationType().getDeclaredMethods();
+ Map<String, Object> parameters = new HashMap<String, Object>( declaredMethods.length );
+ for ( Method m : declaredMethods ) {
+ try {
+ parameters.put( m.getName(), m.invoke( annotation ) );
+ }
+ catch ( IllegalAccessException e ) {
+ throw new ValidationException( "Unable to read annotation attributes: " + annotation.getClass(), e );
+ }
+ catch ( InvocationTargetException e ) {
+ throw new ValidationException( "Unable to read annotation attributes: " + annotation.getClass(), e );
+ }
+ }
+ return Collections.unmodifiableMap( parameters );
+ }
+
+ private Object getMethodValue(Annotation annotation, Method m) {
+ Object value;
+ try {
+ value = m.invoke( annotation );
+ }
+ // should never happen
+ catch ( IllegalAccessException e ) {
+ throw new ValidationException( "Unable to retrieve annotation parameter value." );
+ }
+ catch ( InvocationTargetException e ) {
+ throw new ValidationException( "Unable to retrieve annotation parameter value." );
+ }
+ return value;
+ }
+
+ private Map<ClassIndexWrapper, Map<String, Object>> parseOverrideParameters() {
+ Map<ClassIndexWrapper, Map<String, Object>> overrideParameters = new HashMap<ClassIndexWrapper, Map<String, Object>>();
+ for ( Method m : annotation.annotationType().getMethods() ) {
+ if ( m.getAnnotation( OverridesAttribute.class ) != null ) {
+ addOverrideAttributes(
+ overrideParameters, m, m.getAnnotation( OverridesAttribute.class )
+ );
+ }
+ else if ( m.getAnnotation( OverridesAttribute.List.class ) != null ) {
+ addOverrideAttributes(
+ overrideParameters,
+ m,
+ m.getAnnotation( OverridesAttribute.List.class ).value()
+ );
+ }
+ }
+ return overrideParameters;
+ }
+
+ private void addOverrideAttributes(Map<ClassIndexWrapper, Map<String, Object>> overrideParameters, Method m, OverridesAttribute... attributes) {
+
+ Object value = getMethodValue( annotation, m );
+ for ( OverridesAttribute overridesAttribute : attributes ) {
+ ensureAttributeIsOverridable( m, overridesAttribute );
+
+ ClassIndexWrapper wrapper = new ClassIndexWrapper(
+ overridesAttribute.constraint(), overridesAttribute.constraintIndex()
+ );
+ Map<String, Object> map = overrideParameters.get( wrapper );
+ if ( map == null ) {
+ map = new HashMap<String, Object>();
+ overrideParameters.put( wrapper, map );
+ }
+ map.put( overridesAttribute.name(), value );
+ }
+ }
+
+ private void ensureAttributeIsOverridable(Method m, OverridesAttribute overridesAttribute) {
+ try {
+ Class<?> returnTypeOfOverridenConstraint = overridesAttribute.constraint()
+ .getMethod( overridesAttribute.name() )
+ .getReturnType();
+ if ( !returnTypeOfOverridenConstraint.equals( m.getReturnType() ) ) {
+ String message = "The overiding type of a composite constraint must be identical to the overwridden one. Expected " + returnTypeOfOverridenConstraint
+ .getName() + " found " + m.getReturnType();
+ throw new ConstraintDefinitionException( message );
+ }
+ }
+ catch ( NoSuchMethodException nsme ) {
+ throw new ConstraintDefinitionException(
+ "Overriden constraint does not define an attribute with name " + overridesAttribute.name()
+ );
+ }
+ }
+
+ private void parseComposingConstraints(Map<ClassIndexWrapper, Map<String, Object>> overrideParameters) {
+ for ( Annotation declaredAnnotation : annotation.annotationType().getDeclaredAnnotations() ) {
+ if ( constraintHelper.isConstraintAnnotation( declaredAnnotation )
+ || constraintHelper.isBuiltinConstraint( declaredAnnotation.annotationType() ) ) {
+ ConstraintDescriptorImpl<?> descriptor = createComposingConstraintDescriptor(
+ declaredAnnotation, overrideParameters, OVERRIDES_PARAMETER_DEFAULT_INDEX
+ );
+ composingConstraints.add( descriptor );
+ log.debug( "Adding composing constraint: " + descriptor );
+ }
+ else if ( constraintHelper.isMultiValueConstraint( declaredAnnotation ) ) {
+ List<Annotation> multiValueConstraints = constraintHelper.getMultiValueConstraints( declaredAnnotation );
+ int index = 1;
+ for ( Annotation constraintAnnotation : multiValueConstraints ) {
+ ConstraintDescriptorImpl<?> descriptor = createComposingConstraintDescriptor(
+ constraintAnnotation, overrideParameters, index
+ );
+ composingConstraints.add( descriptor );
+ log.debug( "Adding composing constraint: " + descriptor );
+ index++;
+ }
+ }
+ }
+ }
+
+ private <U extends Annotation> ConstraintDescriptorImpl<U> createComposingConstraintDescriptor(U declaredAnnotation, Map<ClassIndexWrapper, Map<String, Object>> overrideParameters, int index) {
+ //TODO don't quite understand this warning
+ //TODO assuming U.getClass() returns Class<U>
+ @SuppressWarnings("unchecked")
+ final Class<U> annotationType = ( Class<U> ) declaredAnnotation.annotationType();
+ return createComposingConstraintDescriptor(
+ overrideParameters,
+ index,
+ declaredAnnotation,
+ annotationType
+ );
+ }
+
+ private <U extends Annotation> ConstraintDescriptorImpl<U> createComposingConstraintDescriptor(Map<ClassIndexWrapper, Map<String, Object>> overrideParameters, int index, U constraintAnnotation, Class<U> annotationType) {
+ // use a annotation proxy
+ AnnotationDescriptor<U> annotationDescriptor = new AnnotationDescriptor<U>(
+ annotationType, getAnnotationParameters( constraintAnnotation )
+ );
+
+ // get the right override parameters
+ Map<String, Object> overrides = overrideParameters.get(
+ new ClassIndexWrapper(
+ annotationType, index
+ )
+ );
+ if ( overrides != null ) {
+ for ( Map.Entry<String, Object> entry : overrides.entrySet() ) {
+ annotationDescriptor.setValue( entry.getKey(), entry.getValue() );
+ }
+ }
+
+ // groups get inherited from the parent
+ annotationDescriptor.setValue( "groups", groups.toArray( new Class<?>[] { } ) );
+
+ U annotationProxy = AnnotationFactory.create( annotationDescriptor );
+ return new ConstraintDescriptorImpl<U>(
+ annotationProxy, constraintHelper
+ );
+ }
+
+ /**
+ * A wrapper class to keep track for which compposing constraints (class and index) a given attribute override applies to.
+ */
+ private class ClassIndexWrapper {
+ final Class<?> clazz;
+ final int index;
+
+ ClassIndexWrapper(Class<?> clazz, int index) {
+ this.clazz = clazz;
+ this.index = index;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if ( this == o ) {
+ return true;
+ }
+ if ( o == null || getClass() != o.getClass() ) {
+ return false;
+ }
+
+ ClassIndexWrapper that = ( ClassIndexWrapper ) o;
+
+ if ( index != that.index ) {
+ return false;
+ }
+ if ( clazz != null ? !clazz.equals( that.clazz ) : that.clazz != null ) {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = clazz != null ? clazz.hashCode() : 0;
+ result = 31 * result + index;
+ return result;
+ }
+ }
+}
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/ConstraintHelper.java (from rev 16797, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintHelper.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/ConstraintHelper.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/ConstraintHelper.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -0,0 +1,335 @@
+// $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.metadata;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import javax.validation.Constraint;
+import javax.validation.ConstraintDefinitionException;
+import javax.validation.ConstraintValidator;
+import javax.validation.ValidationException;
+import javax.validation.constraints.AssertFalse;
+import javax.validation.constraints.AssertTrue;
+import javax.validation.constraints.DecimalMax;
+import javax.validation.constraints.DecimalMin;
+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.hibernate.validation.constraints.impl.AssertFalseValidator;
+import org.hibernate.validation.constraints.impl.AssertTrueValidator;
+import org.hibernate.validation.constraints.impl.DecimalMaxValidatorForNumber;
+import org.hibernate.validation.constraints.impl.DecimalMaxValidatorForString;
+import org.hibernate.validation.constraints.impl.DecimalMinValidatorForNumber;
+import org.hibernate.validation.constraints.impl.DecimalMinValidatorForString;
+import org.hibernate.validation.constraints.impl.DigitsValidatorForNumber;
+import org.hibernate.validation.constraints.impl.DigitsValidatorForString;
+import org.hibernate.validation.constraints.impl.FutureValidatorForCalendar;
+import org.hibernate.validation.constraints.impl.FutureValidatorForDate;
+import org.hibernate.validation.constraints.impl.MaxValidatorForNumber;
+import org.hibernate.validation.constraints.impl.MaxValidatorForString;
+import org.hibernate.validation.constraints.impl.MinValidatorForNumber;
+import org.hibernate.validation.constraints.impl.MinValidatorForString;
+import org.hibernate.validation.constraints.impl.NotNullValidator;
+import org.hibernate.validation.constraints.impl.NullValidator;
+import org.hibernate.validation.constraints.impl.PastValidatorForCalendar;
+import org.hibernate.validation.constraints.impl.PastValidatorForDate;
+import org.hibernate.validation.constraints.impl.PatternValidator;
+import org.hibernate.validation.constraints.impl.SizeValidatorForArray;
+import org.hibernate.validation.constraints.impl.SizeValidatorForArraysOfBoolean;
+import org.hibernate.validation.constraints.impl.SizeValidatorForArraysOfByte;
+import org.hibernate.validation.constraints.impl.SizeValidatorForArraysOfChar;
+import org.hibernate.validation.constraints.impl.SizeValidatorForArraysOfDouble;
+import org.hibernate.validation.constraints.impl.SizeValidatorForArraysOfFloat;
+import org.hibernate.validation.constraints.impl.SizeValidatorForArraysOfInt;
+import org.hibernate.validation.constraints.impl.SizeValidatorForArraysOfLong;
+import org.hibernate.validation.constraints.impl.SizeValidatorForCollection;
+import org.hibernate.validation.constraints.impl.SizeValidatorForMap;
+import org.hibernate.validation.constraints.impl.SizeValidatorForString;
+import org.hibernate.validation.util.ReflectionHelper;
+
+/**
+ * Keeps track of builtin constraints and their validator implementations, as well as already resolved validator definitions.
+ *
+ * @author Hardy Ferentschik
+ * @author Alaa Nassef
+ */
+public class ConstraintHelper {
+
+ private final static Map<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<?, ?>>>> builtinConstraints =
+ new ConcurrentHashMap<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<?, ?>>>>();
+
+ static {
+ 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( DecimalMaxValidatorForNumber.class );
+ constraintList.add( DecimalMaxValidatorForString.class );
+ builtinConstraints.put( DecimalMax.class, constraintList );
+
+ constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
+ constraintList.add( DecimalMinValidatorForNumber.class );
+ constraintList.add( DecimalMinValidatorForString.class );
+ builtinConstraints.put( DecimalMin.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( 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( PatternValidator.class );
+ builtinConstraints.put( Pattern.class, constraintList );
+
+ constraintList = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
+ constraintList.add( SizeValidatorForString.class );
+ constraintList.add( SizeValidatorForCollection.class );
+ constraintList.add( SizeValidatorForArray.class );
+ constraintList.add( SizeValidatorForMap.class );
+ constraintList.add( SizeValidatorForArraysOfBoolean.class );
+ constraintList.add( SizeValidatorForArraysOfByte.class );
+ constraintList.add( SizeValidatorForArraysOfChar.class );
+ constraintList.add( SizeValidatorForArraysOfDouble.class );
+ constraintList.add( SizeValidatorForArraysOfFloat.class );
+ constraintList.add( SizeValidatorForArraysOfInt.class );
+ constraintList.add( SizeValidatorForArraysOfLong.class );
+ builtinConstraints.put( Size.class, constraintList );
+ }
+
+ private final Map<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<? extends Annotation, ?>>>> constraintValidatorDefinitons =
+ new ConcurrentHashMap<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<? extends Annotation, ?>>>>();
+
+ public List<Class<? extends ConstraintValidator<? extends Annotation, ?>>> getBuiltInConstraints(Class<? extends Annotation> annotationType) {
+ final List<Class<? extends ConstraintValidator<?, ?>>> builtInList = getBuiltInFromAnnotationType(
+ annotationType
+ );
+
+ if ( builtInList == null || builtInList.size() == 0 ) {
+ throw new ValidationException( "Unable to find constraints for " + annotationType );
+ }
+ List<Class<? extends ConstraintValidator<? extends Annotation, ?>>> constraints =
+ new ArrayList<Class<? extends ConstraintValidator<? extends Annotation, ?>>>( builtInList.size() );
+ for ( Class<? extends ConstraintValidator<?, ?>> validatorClass : builtInList ) {
+ //safe cause all CV for a given annotation A are CV<A, ?>
+ @SuppressWarnings("unchecked")
+ Class<ConstraintValidator<? extends Annotation, ?>> safeValdiatorClass = ( Class<ConstraintValidator<? extends Annotation, ?>> ) validatorClass;
+ constraints.add( safeValdiatorClass );
+ }
+
+ return constraints;
+ }
+
+ private List<Class<? extends ConstraintValidator<?, ?>>> getBuiltInFromAnnotationType(Class<? extends Annotation> annotationType) {
+ return builtinConstraints.get( annotationType );
+ }
+
+ public boolean isBuiltinConstraint(Class<? extends Annotation> annotationType) {
+ return builtinConstraints.containsKey( 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.annotationType() ) ) {
+ 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.annotationType() ) ) {
+ annotationList.add( a );
+ }
+ }
+ }
+ }
+ catch ( NoSuchMethodException nsme ) {
+ // ignore
+ }
+ catch ( IllegalAccessException iae ) {
+ // ignore
+ }
+ catch ( InvocationTargetException ite ) {
+ // ignore
+ }
+ return annotationList;
+ }
+
+ /**
+ * Checks whether 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.";
+ throw new ConstraintDefinitionException( msg );
+ }
+
+ try {
+ Class<?>[] defaultGroups = ( Class<?>[] ) annotation.annotationType()
+ .getMethod( "groups" )
+ .getDefaultValue();
+ if ( defaultGroups.length != 0 ) {
+ String msg = annotation.annotationType()
+ .getName() + " contains Constraint annotation, but the groups " +
+ "paramter default value is not empty.";
+ throw new ConstraintDefinitionException( msg );
+ }
+ }
+ catch ( NoSuchMethodException nsme ) {
+ String msg = annotation.annotationType().getName() + " contains Constraint annotation, but does " +
+ "not contain a groups parameter.";
+ throw new ConstraintDefinitionException( msg );
+ }
+
+ 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.";
+ throw new ConstraintDefinitionException( msg );
+ }
+ }
+ return true;
+ }
+
+ public List<Class<? extends ConstraintValidator<? extends Annotation, ?>>> getConstraintValidatorDefinition(Class<? extends Annotation> annotationClass) {
+ if ( annotationClass == null ) {
+ throw new IllegalArgumentException( "Class cannot be null" );
+ }
+ return constraintValidatorDefinitons.get( annotationClass );
+ }
+
+ public <A extends Annotation> void addConstraintValidatorDefinition(Class<A> annotationClass, List<Class<? extends ConstraintValidator<? extends Annotation, ?>>> definitionClasses) {
+ constraintValidatorDefinitons.put( annotationClass, definitionClasses );
+ }
+
+ public boolean containsConstraintValidatorDefinition(Class<? extends Annotation> annotationClass) {
+ return constraintValidatorDefinitons.containsKey( annotationClass );
+ }
+}
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/ElementDescriptorImpl.java (from rev 16797, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ElementDescriptorImpl.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/ElementDescriptorImpl.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/ElementDescriptorImpl.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -0,0 +1,64 @@
+// $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.metadata;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import javax.validation.metadata.ConstraintDescriptor;
+import javax.validation.metadata.ElementDescriptor;
+
+/**
+ * Describe a validated element (class, field or property).
+ *
+ * @author Emmanuel Bernard
+ * @author Hardy Ferentschik
+ */
+public class ElementDescriptorImpl implements ElementDescriptor {
+ private final Class<?> type;
+ private final Set<ConstraintDescriptor<?>> constraintDescriptors = new HashSet<ConstraintDescriptor<?>>();
+
+ public ElementDescriptorImpl(Class<?> type) {
+ this.type = type;
+ }
+
+ public void addConstraintDescriptor(ConstraintDescriptorImpl constraintDescriptor) {
+ constraintDescriptors.add( constraintDescriptor );
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean hasConstraints() {
+ return constraintDescriptors.size() != 0;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Class<?> getType() {
+ return type;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Set<ConstraintDescriptor<?>> getConstraintDescriptors() {
+ return Collections.unmodifiableSet( constraintDescriptors );
+ }
+}
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/MetaConstraint.java (from rev 16797, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/MetaConstraint.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/MetaConstraint.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -0,0 +1,178 @@
+// $Id$// $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.metadata;
+
+import java.lang.annotation.Annotation;
+import java.lang.annotation.ElementType;
+import java.lang.reflect.Field;
+import java.lang.reflect.Member;
+import java.lang.reflect.Method;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+import javax.validation.metadata.ConstraintDescriptor;
+import javax.validation.ConstraintViolation;
+
+import org.hibernate.validation.util.ReflectionHelper;
+import org.hibernate.validation.engine.ConstraintTree;
+import org.hibernate.validation.engine.ExecutionContext;
+
+/**
+ * Instances of this class abstract the constraint type (class, method or field constraint) and gives access to
+ * meta data about the constraint. This allows a unified handling of constraints in the validator imlpementation.
+ *
+ * @author Hardy Ferentschik
+ */
+public class MetaConstraint<T, A extends Annotation> {
+
+ /**
+ * The constraint tree created from the constraint annotation.
+ */
+ private final ConstraintTree<A> constraintTree;
+
+ /**
+ * The member the constraint was defined on.
+ */
+ private final Member member;
+
+ /**
+ * The JavaBeans name for this constraint.
+ */
+ private final String propertyName;
+
+ /**
+ * Describes on which level (<code>TYPE</code>, <code>METHOD</code>, <code>FIELD</code>) the constraint was
+ * defined on.
+ */
+ private final ElementType elementType;
+
+ /**
+ * The class of the bean hosting this constraint.
+ */
+ private final Class<T> beanClass;
+
+ public MetaConstraint(Class<T> beanClass, ConstraintDescriptor<A> constraintDescriptor) {
+ this.elementType = ElementType.TYPE;
+ this.member = null;
+ this.propertyName = "";
+ this.beanClass = beanClass;
+ constraintTree = new ConstraintTree<A>( constraintDescriptor );
+ }
+
+ public MetaConstraint(Member member, Class<T> beanClass, ConstraintDescriptor<A> constraintDescriptor) {
+ if ( member instanceof Method ) {
+ this.elementType = ElementType.METHOD;
+ }
+ else if ( member instanceof Field ) {
+ this.elementType = ElementType.FIELD;
+ }
+ else {
+ throw new IllegalArgumentException( "Non allowed member type: " + member );
+ }
+ this.member = member;
+ this.propertyName = ReflectionHelper.getPropertyName( member );
+ this.beanClass = beanClass;
+ constraintTree = new ConstraintTree<A>( constraintDescriptor );
+ }
+
+
+ /**
+ * @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.
+ */
+ public Set<Class<?>> getGroupList() {
+ return constraintTree.getDescriptor().getGroups();
+ }
+
+ public ConstraintDescriptor getDescriptor() {
+ return constraintTree.getDescriptor();
+ }
+
+ public Class<T> getBeanClass() {
+ return beanClass;
+ }
+
+ public String getPropertyName() {
+ return propertyName;
+ }
+
+ public ElementType getElementType() {
+ return elementType;
+ }
+
+ public ConstraintTree getConstraintTree() {
+ return constraintTree;
+ }
+
+ public <T> boolean validateConstraint(ExecutionContext<T> executionContext) {
+ final Object leafBeanInstance = executionContext.peekCurrentBean();
+ Object value = getValue( leafBeanInstance );
+ List<ConstraintViolation<T>> constraintViolations = new ArrayList<ConstraintViolation<T>>();
+ constraintTree.validateConstraints( value, typeOfAnnoatedElement(), executionContext, constraintViolations );
+ if ( constraintViolations.size() > 0 ) {
+ executionContext.addConstraintFailures( constraintViolations );
+ return false;
+ }
+ return true;
+ }
+
+ public <T> boolean validateConstraint(Object value, ExecutionContext<T> executionContext) {
+ List<ConstraintViolation<T>> constraintViolations = new ArrayList<ConstraintViolation<T>>();
+ constraintTree.validateConstraints( value, typeOfAnnoatedElement(), executionContext, constraintViolations );
+ if ( constraintViolations.size() > 0 ) {
+ executionContext.addConstraintFailures( constraintViolations );
+ return false;
+ }
+ return true;
+ }
+
+ private Type typeOfAnnoatedElement() {
+ Type t;
+ switch ( elementType ) {
+ case TYPE: {
+ t = beanClass;
+ break;
+ }
+ default: {
+ t = ReflectionHelper.typeOf( member );
+ if ( t instanceof Class && ((Class) t).isPrimitive()) {
+ t = ReflectionHelper.boxedTyp( t );
+ }
+ }
+ }
+ return t;
+ }
+
+ /**
+ * @param o the object from which to retrieve the value.
+ *
+ * @return Returns the value for this constraint from the specified object. Depending on the type either the value itself
+ * is returned of method or field access is used to access the value.
+ */
+ private Object getValue(Object o) {
+ switch ( elementType ) {
+ case TYPE: {
+ return o;
+ }
+ default: {
+ return ReflectionHelper.getValue( member, o );
+ }
+ }
+ }
+}
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/PropertyDescriptorImpl.java (from rev 16797, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/PropertyDescriptorImpl.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/PropertyDescriptorImpl.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/PropertyDescriptorImpl.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -0,0 +1,52 @@
+// $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.metadata;
+
+import javax.validation.metadata.PropertyDescriptor;
+
+/**
+ * Describe a validated element (class, field or property).
+ *
+ * @author Emmanuel Bernard
+ * @author Hardy Ferentschik
+ */
+public class PropertyDescriptorImpl extends ElementDescriptorImpl implements PropertyDescriptor {
+ private final boolean cascaded;
+ private final String property;
+
+
+ public PropertyDescriptorImpl(Class<?> returnType, boolean cascaded, String property) {
+ super( returnType );
+ this.cascaded = cascaded;
+ this.property = property;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isCascaded() {
+ return cascaded;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String getPropertyName() {
+ return property;
+ }
+}
\ No newline at end of file
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/xml/ValidationBootstrapParameters.java (from rev 16797, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/ValidationBootstrapParameters.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/xml/ValidationBootstrapParameters.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/xml/ValidationBootstrapParameters.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -0,0 +1,41 @@
+// $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.xml;
+
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import javax.validation.ConstraintValidatorFactory;
+import javax.validation.MessageInterpolator;
+import javax.validation.TraversableResolver;
+import javax.validation.spi.ValidationProvider;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class ValidationBootstrapParameters {
+ public ConstraintValidatorFactory constraintValidatorFactory;
+ public MessageInterpolator messageInterpolator;
+ public TraversableResolver traversableResolver;
+ public ValidationProvider provider;
+ public Class<? extends ValidationProvider<?>> providerClass = null;
+ public final Map<String, String> configProperties = new HashMap<String, String>();
+ public final Set<InputStream> mappings = new HashSet<InputStream>();
+}
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/xml/ValidationXmlParser.java (from rev 16797, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/ValidationXmlParser.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/xml/ValidationXmlParser.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/xml/ValidationXmlParser.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -0,0 +1,255 @@
+// $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.xml;
+
+import java.io.InputStream;
+import java.net.URL;
+import javax.validation.ConstraintValidatorFactory;
+import javax.validation.MessageInterpolator;
+import javax.validation.TraversableResolver;
+import javax.validation.ValidationException;
+import javax.validation.spi.ValidationProvider;
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBElement;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Unmarshaller;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.validation.Schema;
+import javax.xml.validation.SchemaFactory;
+
+import org.slf4j.Logger;
+import org.xml.sax.SAXException;
+
+import org.hibernate.validation.util.LoggerFactory;
+import org.hibernate.validation.util.ReflectionHelper;
+import org.hibernate.validation.xml.PropertyType;
+import org.hibernate.validation.xml.ValidationConfigType;
+
+/**
+ * Parser for <i>validation.xml</i> using JAXB.
+ *
+ * @author Hardy Ferentschik
+ */
+public class ValidationXmlParser {
+
+ private static final Logger log = LoggerFactory.make();
+ private static final String VALIDATION_XML_FILE = "META-INF/validation.xml";
+ private static final String VALIDATION_CONFIGURATION_XSD = "META-INF/validation-configuration-1.0.xsd";
+
+
+ /**
+ * Tries to check whether a validation.xml file exists and parses it using JAXB.
+ *
+ * @return The parameters parsed out of <i>validation.xml</i> wrapped in an instance of <code>ConfigurationImpl.ValidationBootstrapParameters</code>.
+ */
+ public ValidationBootstrapParameters parseValidationXml() {
+ ValidationConfigType config = getValidationConfig();
+ ValidationBootstrapParameters xmlParameters = new ValidationBootstrapParameters();
+ if ( config != null ) {
+ // collect the paramters from the xml file
+ setProviderClassFromXml( config, xmlParameters );
+ setMessageInterpolatorFromXml( config, xmlParameters );
+ setTraversableResolverFromXml( config, xmlParameters );
+ setConstraintFactoryFromXml( config, xmlParameters );
+ setMappingStreamsFromXml( config, xmlParameters );
+ setPropertiesFromXml( config, xmlParameters );
+ }
+ return xmlParameters;
+ }
+
+ private void setConstraintFactoryFromXml(ValidationConfigType config, ValidationBootstrapParameters xmlParameters) {
+ String constraintFactoryClass = config.getConstraintValidatorFactory();
+ if ( constraintFactoryClass != null ) {
+ try {
+ @SuppressWarnings("unchecked")
+ Class<ConstraintValidatorFactory> clazz = ( Class<ConstraintValidatorFactory> ) ReflectionHelper.classForName(
+ constraintFactoryClass, this.getClass()
+ );
+ xmlParameters.constraintValidatorFactory = clazz.newInstance();
+ log.info( "Using {} as constraint factory.", constraintFactoryClass );
+ }
+ catch ( ClassNotFoundException e ) {
+ throw new ValidationException(
+ "Unable to instantiate constraint factory class " + constraintFactoryClass + ".", e
+ );
+ }
+ catch ( InstantiationException e ) {
+ throw new ValidationException(
+ "Unable to instantiate constraint factory class " + constraintFactoryClass + ".", e
+ );
+ }
+ catch ( IllegalAccessException e ) {
+ throw new ValidationException(
+ "Unable to instantiate constraint factory class " + constraintFactoryClass + ".", e
+ );
+ }
+ }
+ }
+
+ private void setPropertiesFromXml(ValidationConfigType config, ValidationBootstrapParameters xmlParameters) {
+ for ( PropertyType property : config.getProperty() ) {
+ if ( log.isDebugEnabled() ) {
+ log.debug(
+ "Found property '{}' with value '{}' in validation.xml.",
+ property.getName(),
+ property.getValue()
+ );
+ }
+ xmlParameters.configProperties.put( property.getName(), property.getValue() );
+ }
+ }
+
+ private void setMappingStreamsFromXml(ValidationConfigType config, ValidationBootstrapParameters xmlParameters) {
+ for ( JAXBElement<String> mappingFileName : config.getConstraintMapping() ) {
+ if ( log.isDebugEnabled() ) {
+ log.debug(
+ "Trying to open input stream for {}.", mappingFileName.getValue()
+ );
+ }
+ InputStream in = getInputStreamForPath( mappingFileName.getValue() );
+ if ( in == null ) {
+ throw new ValidationException( "Unable to open input stream for mapping file " + mappingFileName.getValue() + "." );
+ }
+ xmlParameters.mappings.add( in );
+ }
+ }
+
+ private void setMessageInterpolatorFromXml(ValidationConfigType config, ValidationBootstrapParameters xmlParameters) {
+ String messageInterpolatorClass = config.getMessageInterpolator();
+ if ( messageInterpolatorClass != null ) {
+ try {
+ @SuppressWarnings("unchecked")
+ Class<MessageInterpolator> clazz = ( Class<MessageInterpolator> ) ReflectionHelper.classForName(
+ messageInterpolatorClass, this.getClass()
+ );
+ xmlParameters.messageInterpolator = clazz.newInstance();
+ log.info( "Using {} as message interpolator.", messageInterpolatorClass );
+ }
+ catch ( ClassNotFoundException e ) {
+ throw new ValidationException(
+ "Unable to instantiate message interpolator class " + messageInterpolatorClass + ".", e
+ );
+ }
+ catch ( InstantiationException e ) {
+ throw new ValidationException(
+ "Unable to instantiate message interpolator class " + messageInterpolatorClass + ".", e
+ );
+ }
+ catch ( IllegalAccessException e ) {
+ throw new ValidationException(
+ "Unable to instantiate message interpolator class " + messageInterpolatorClass + ".", e
+ );
+ }
+ }
+ }
+
+ private void setTraversableResolverFromXml(ValidationConfigType config, ValidationBootstrapParameters xmlParameters) {
+ String traversableResolverClass = config.getTraversableResolver();
+ if ( traversableResolverClass != null ) {
+ try {
+ @SuppressWarnings("unchecked")
+ Class<TraversableResolver> clazz = ( Class<TraversableResolver> ) ReflectionHelper.classForName(
+ traversableResolverClass, this.getClass()
+ );
+ xmlParameters.traversableResolver = clazz.newInstance();
+ log.info( "Using {} as traversable resolver.", traversableResolverClass );
+ }
+ catch ( ClassNotFoundException e ) {
+ throw new ValidationException(
+ "Unable to instantiate traversable resolver class " + traversableResolverClass + ".", e
+ );
+ }
+ catch ( InstantiationException e ) {
+ throw new ValidationException(
+ "Unable to instantiate traversable resolver class " + traversableResolverClass + ".", e
+ );
+ }
+ catch ( IllegalAccessException e ) {
+ throw new ValidationException(
+ "Unable to instantiate traversable resolver class " + traversableResolverClass + ".", e
+ );
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private void setProviderClassFromXml(ValidationConfigType config, ValidationBootstrapParameters xmlParamters) {
+ String providerClassName = config.getDefaultProvider();
+ if ( providerClassName != null ) {
+ try {
+ xmlParamters.providerClass = ( Class<? extends ValidationProvider<?>> ) ReflectionHelper.classForName(
+ providerClassName, this.getClass()
+ );
+ log.info( "Using {} as validation provider.", providerClassName );
+ }
+ catch ( Exception e ) {
+ throw new ValidationException( "Unable to instantiate validation provider class " + providerClassName + "." );
+ }
+ }
+ }
+
+ private ValidationConfigType getValidationConfig() {
+ InputStream inputStream = getInputStreamForPath( VALIDATION_XML_FILE );
+ if ( inputStream == null ) {
+ log.info( "No {} found. Using annotation based configuration only!", VALIDATION_XML_FILE );
+ return null;
+ }
+
+ log.info( "{} found.", VALIDATION_XML_FILE );
+
+ ValidationConfigType validationConfig;
+ Schema schema = getValidationConfigurationSchema();
+ try {
+ JAXBContext jc = JAXBContext.newInstance( ValidationConfigType.class );
+ Unmarshaller unmarshaller = jc.createUnmarshaller();
+ unmarshaller.setSchema( schema );
+ StreamSource stream = new StreamSource( inputStream );
+ JAXBElement<ValidationConfigType> root = unmarshaller.unmarshal( stream, ValidationConfigType.class );
+ validationConfig = root.getValue();
+ }
+ catch ( JAXBException e ) {
+ log.error( "Error parsing validation.xml: {}", e.getMessage() );
+ throw new ValidationException( "Unable to parse " + VALIDATION_XML_FILE );
+ }
+ return validationConfig;
+ }
+
+ private InputStream getInputStreamForPath(String path) {
+ // try the context class loader first
+ InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream( path );
+
+ // try the current class loader
+ if ( inputStream == null ) {
+ inputStream = this.getClass().getResourceAsStream( path );
+ }
+ return inputStream;
+ }
+
+ private Schema getValidationConfigurationSchema() {
+ URL schemaUrl = this.getClass().getClassLoader().getResource( VALIDATION_CONFIGURATION_XSD );
+ SchemaFactory sf = SchemaFactory.newInstance( javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI );
+ Schema schema = null;
+ try {
+ schema = sf.newSchema( schemaUrl );
+ }
+ catch ( SAXException e ) {
+ log.warn( "Unable to create schema for {}: {}", VALIDATION_CONFIGURATION_XSD, e.getMessage() );
+ }
+ return schema;
+ }
+}
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/xml/XmlMappingParser.java (from rev 16797, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/XmlMappingParser.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/xml/XmlMappingParser.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/xml/XmlMappingParser.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -0,0 +1,620 @@
+// $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.xml;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Serializable;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Array;
+import java.lang.reflect.Field;
+import java.lang.reflect.Member;
+import java.lang.reflect.Method;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.validation.Constraint;
+import javax.validation.ConstraintValidator;
+import javax.validation.ValidationException;
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBElement;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Unmarshaller;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.validation.Schema;
+import javax.xml.validation.SchemaFactory;
+
+import org.slf4j.Logger;
+import org.xml.sax.SAXException;
+
+import org.hibernate.validation.metadata.ConstraintDescriptorImpl;
+import org.hibernate.validation.metadata.MetaConstraint;
+import org.hibernate.validation.metadata.ConstraintHelper;
+import org.hibernate.validation.metadata.AnnotationIgnores;
+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;
+import org.hibernate.validation.xml.AnnotationType;
+import org.hibernate.validation.xml.BeanType;
+import org.hibernate.validation.xml.ClassType;
+import org.hibernate.validation.xml.ConstraintDefinitionType;
+import org.hibernate.validation.xml.ConstraintMappingsType;
+import org.hibernate.validation.xml.ConstraintType;
+import org.hibernate.validation.xml.ElementType;
+import org.hibernate.validation.xml.FieldType;
+import org.hibernate.validation.xml.GetterType;
+import org.hibernate.validation.xml.GroupSequenceType;
+import org.hibernate.validation.xml.GroupsType;
+import org.hibernate.validation.xml.ValidatedByType;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class XmlMappingParser {
+
+ private static final Logger log = LoggerFactory.make();
+ private static final String VALIDATION_MAPPING_XSD = "META-INF/validation-mapping-1.0.xsd";
+ private static final String MESSAGE_PARAM = "message";
+ private static final String GROUPS_PARAM = "groups";
+ private static final String PACKAGE_SEPERATOR = ".";
+
+ private final Set<Class<?>> processedClasses = new HashSet<Class<?>>();
+ private final ConstraintHelper constraintHelper;
+ private final AnnotationIgnores annotationIgnores;
+ private final Map<Class<?>, List<MetaConstraint<?, ? extends Annotation>>> constraintMap;
+ private final Map<Class<?>, List<Member>> cascadedMembers;
+ private final Map<Class<?>, List<Class<?>>> defaultSequences;
+
+ public XmlMappingParser(ConstraintHelper constraintHelper) {
+ this.constraintHelper = constraintHelper;
+ this.annotationIgnores = new AnnotationIgnores();
+ this.constraintMap = new HashMap<Class<?>, List<MetaConstraint<?, ? extends Annotation>>>();
+ this.cascadedMembers = new HashMap<Class<?>, List<Member>>();
+ this.defaultSequences = new HashMap<Class<?>, List<Class<?>>>();
+ }
+
+ public void parse(Set<InputStream> mappingStreams) {
+ for ( InputStream in : mappingStreams ) {
+ try {
+ ConstraintMappingsType mapping = getValidationConfig( in );
+ parseConstraintDefinitions( mapping.getConstraintDefinition() );
+ String defaultPackage = mapping.getDefaultPackage();
+ for ( BeanType bean : mapping.getBean() ) {
+ Class<?> beanClass = getClass( bean.getClazz(), defaultPackage );
+ checkClassHasNotBeenProcessed( processedClasses, beanClass );
+ annotationIgnores.setDefaultIgnoreAnnotation( beanClass, bean.isIgnoreAnnotations() );
+ parseClassLevelOverrides( bean.getClassType(), beanClass, defaultPackage );
+ parseFieldLevelOverrides( bean.getField(), beanClass, defaultPackage );
+ parsePropertyLevelOverrides( bean.getGetter(), beanClass, defaultPackage );
+ processedClasses.add( beanClass );
+ }
+ }
+ finally {
+ try {
+ in.close();
+ }
+ catch ( IOException e ) {
+ log.warn( "Error closing input stream: {}", e.getMessage() );
+ }
+ }
+ }
+ }
+
+ public Set<Class<?>> getProcessedClasses() {
+ return processedClasses;
+ }
+
+ public AnnotationIgnores getAnnotationIgnores() {
+ return annotationIgnores;
+ }
+
+ public <T> List<MetaConstraint<T, ? extends Annotation>> getConstraintsForClass(Class<T> beanClass) {
+ List<MetaConstraint<T, ? extends Annotation>> list = new ArrayList<MetaConstraint<T, ? extends Annotation>>();
+ if ( constraintMap.containsKey( beanClass ) ) {
+ for ( MetaConstraint<?, ? extends Annotation> metaConstraint : constraintMap.get( beanClass ) ) {
+ @SuppressWarnings( "unchecked") // safe cast since the list of meta constraints is always specific to the bean type
+ MetaConstraint<T, ? extends Annotation> boundMetaConstraint = ( MetaConstraint<T, ? extends Annotation> ) metaConstraint;
+ list.add( boundMetaConstraint );
+ }
+ return list;
+ }
+ else {
+ return Collections.emptyList();
+ }
+ }
+
+ public List<Member> getCascadedMembersForClass(Class<?> beanClass) {
+ if ( cascadedMembers.containsKey( beanClass ) ) {
+ return cascadedMembers.get( beanClass );
+ }
+ else {
+ return Collections.emptyList();
+ }
+ }
+
+ public List<Class<?>> getDefaultSequenceForClass(Class<?> beanClass) {
+ if ( defaultSequences.containsKey( beanClass ) ) {
+ return defaultSequences.get( beanClass );
+ }
+ else {
+ return Collections.emptyList();
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private void parseConstraintDefinitions(List<ConstraintDefinitionType> constraintDefinitionList) {
+ for ( ConstraintDefinitionType constraintDefinition : constraintDefinitionList ) {
+ String annotationClassName = constraintDefinition.getAnnotation();
+ Class<? extends Annotation> annotationClass;
+ try {
+ annotationClass = ( Class<? extends Annotation> ) ReflectionHelper.classForName(
+ annotationClassName, this.getClass()
+ );
+ }
+ catch ( ClassNotFoundException e ) {
+ throw new ValidationException( "Unable to load class " + annotationClassName );
+ }
+
+ if ( !annotationClass.isAnnotation() ) {
+ throw new ValidationException( annotationClassName + " is not an annotation" );
+ }
+
+ ValidatedByType validatedByType = constraintDefinition.getValidatedBy();
+ List<Class<? extends ConstraintValidator<? extends Annotation, ?>>> constraintValidatorClasses = new ArrayList<Class<? extends ConstraintValidator<? extends Annotation, ?>>>();
+ if ( validatedByType.isIncludeExistingValidators() != null && validatedByType.isIncludeExistingValidators() ) {
+ constraintValidatorClasses.addAll( findConstraintValidatorClasses( annotationClass ) );
+ }
+ for ( JAXBElement<String> validatorClassName : validatedByType.getValue() ) {
+ Class<? extends ConstraintValidator<?, ?>> validatorClass;
+ try {
+ validatorClass = ( Class<? extends ConstraintValidator<?, ?>> ) ReflectionHelper.classForName(
+ validatorClassName.getValue(),
+ this.getClass()
+ );
+ }
+ catch ( ClassNotFoundException e ) {
+ throw new ValidationException( "Unable to load class " + validatorClassName );
+ }
+
+ if ( !ConstraintValidator.class.isAssignableFrom( validatorClass ) ) {
+ throw new ValidationException( validatorClass + " is not a constraint validator class" );
+ }
+
+ constraintValidatorClasses.add( validatorClass );
+ }
+ constraintHelper.addConstraintValidatorDefinition(
+ annotationClass, constraintValidatorClasses
+ );
+ }
+ }
+
+ private List<Class<? extends ConstraintValidator<? extends Annotation, ?>>> findConstraintValidatorClasses(Class<? extends Annotation> annotationType) {
+ List<Class<? extends ConstraintValidator<? extends Annotation, ?>>> constraintValidatorDefinitonClasses = new ArrayList<Class<? extends ConstraintValidator<? extends Annotation, ?>>>();
+ if ( constraintHelper.isBuiltinConstraint( annotationType ) ) {
+ constraintValidatorDefinitonClasses.addAll( constraintHelper.getBuiltInConstraints( annotationType ) );
+ }
+ else {
+ Class<? extends ConstraintValidator<?, ?>>[] validatedBy = annotationType
+ .getAnnotation( Constraint.class )
+ .validatedBy();
+ for ( Class<? extends ConstraintValidator<?, ?>> validator : validatedBy ) {
+ //FIXME does this create a CCE at runtime?
+ //FIXME if yes wrap into VE, if no we need to test the type here
+ //Once resolved,we can @SuppressWarning("unchecked") on the cast
+ Class<? extends ConstraintValidator<? extends Annotation, ?>> safeValidator = validator;
+ constraintValidatorDefinitonClasses.add( safeValidator );
+ }
+ }
+ return constraintValidatorDefinitonClasses;
+ }
+
+ private void checkClassHasNotBeenProcessed(Set<Class<?>> processedClasses, Class<?> beanClass) {
+ if ( processedClasses.contains( beanClass ) ) {
+ throw new ValidationException( beanClass.getName() + " has already be configured in xml." );
+ }
+ }
+
+ private void parseFieldLevelOverrides(List<FieldType> fields, Class<?> beanClass, String defaultPackage) {
+ for ( FieldType fieldType : fields ) {
+ String fieldName = fieldType.getName();
+ if ( !ReflectionHelper.containsField( beanClass, fieldName ) ) {
+ throw new ValidationException( beanClass.getName() + " does not contain the fieldType " + fieldName );
+ }
+ Field field = ReflectionHelper.getField( beanClass, fieldName );
+
+ // ignore annotations
+ boolean ignoreFieldAnnotation = fieldType.isIgnoreAnnotations() == null ? false : fieldType.isIgnoreAnnotations();
+ if ( ignoreFieldAnnotation ) {
+ annotationIgnores.setIgnoreAnnotationsOnMember( field );
+ }
+
+ // valid
+ if ( fieldType.getValid() != null ) {
+ addCascadedMember( beanClass, field );
+ }
+
+ // constraints
+ for ( ConstraintType constraint : fieldType.getConstraint() ) {
+ MetaConstraint<?, ?> metaConstraint = createMetaConstraint(
+ constraint, beanClass, field, defaultPackage
+ );
+ addMetaConstraint( beanClass, metaConstraint );
+ }
+ }
+ }
+
+ private void parsePropertyLevelOverrides(List<GetterType> getters, Class<?> beanClass, String defaultPackage) {
+ for ( GetterType getterType : getters ) {
+ String getterName = getterType.getName();
+ if ( !ReflectionHelper.containsMethod( beanClass, getterName ) ) {
+ throw new ValidationException( beanClass.getName() + " does not contain the property " + getterName );
+ }
+ Method method = ReflectionHelper.getMethod( beanClass, getterName );
+
+ // ignore annotations
+ boolean ignoreGetterAnnotation = getterType.isIgnoreAnnotations() == null ? false : getterType.isIgnoreAnnotations();
+ if ( ignoreGetterAnnotation ) {
+ annotationIgnores.setIgnoreAnnotationsOnMember( method );
+ }
+
+ // valid
+ if ( getterType.getValid() != null ) {
+ addCascadedMember( beanClass, method );
+ }
+
+ // constraints
+ for ( ConstraintType constraint : getterType.getConstraint() ) {
+ MetaConstraint<?, ?> metaConstraint = createMetaConstraint(
+ constraint, beanClass, method, defaultPackage
+ );
+ addMetaConstraint( beanClass, metaConstraint );
+ }
+ }
+ }
+
+ private void parseClassLevelOverrides(ClassType classType, Class<?> beanClass, String defaultPackage) {
+ if ( classType == null ) {
+ return;
+ }
+
+ // ignore annotation
+ boolean ignoreClassAnnotation = classType.isIgnoreAnnotations() == null ? false : classType.isIgnoreAnnotations();
+ if ( ignoreClassAnnotation ) {
+ annotationIgnores.setIgnoreAnnotationsOnClass( beanClass );
+ }
+
+ // group sequence
+ List<Class<?>> groupSequence = createGroupSequence( classType.getGroupSequence(), defaultPackage );
+ if ( !groupSequence.isEmpty() ) {
+ defaultSequences.put( beanClass, groupSequence );
+ }
+
+ // constraints
+ for ( ConstraintType constraint : classType.getConstraint() ) {
+ MetaConstraint<?, ?> metaConstraint = createMetaConstraint( constraint, beanClass, null, defaultPackage );
+ addMetaConstraint( beanClass, metaConstraint );
+ }
+ }
+
+ private void addMetaConstraint(Class<?> beanClass, MetaConstraint<?, ?> metaConstraint) {
+ if ( constraintMap.containsKey( beanClass ) ) {
+ constraintMap.get( beanClass ).add( metaConstraint );
+ }
+ else {
+ List<MetaConstraint<?, ? extends Annotation>> constraintList = new ArrayList<MetaConstraint<?, ? extends Annotation>>();
+ constraintList.add( metaConstraint );
+ constraintMap.put( beanClass, constraintList );
+ }
+ }
+
+ private void addCascadedMember(Class<?> beanClass, Member member) {
+ if ( cascadedMembers.containsKey( beanClass ) ) {
+ cascadedMembers.get( beanClass ).add( member );
+ }
+ else {
+ List<Member> tmpList = new ArrayList<Member>();
+ tmpList.add( member );
+ cascadedMembers.put( beanClass, tmpList );
+ }
+ }
+
+ private List<Class<?>> createGroupSequence(GroupSequenceType groupSequenceType, String defaultPackage) {
+ List<Class<?>> groupSequence = new ArrayList<Class<?>>();
+ for ( JAXBElement<String> groupName : groupSequenceType.getValue() ) {
+ Class<?> group = getClass( groupName.getValue(), defaultPackage );
+ groupSequence.add( group );
+ }
+ return groupSequence;
+ }
+
+ private <A extends Annotation, T> MetaConstraint<?, ?> createMetaConstraint(ConstraintType constraint, Class<T> beanClass, Member member, String defaultPackage) {
+ @SuppressWarnings("unchecked")
+ Class<A> annotationClass = ( Class<A> ) getClass( constraint.getAnnotation(), defaultPackage );
+ AnnotationDescriptor<A> annotationDescriptor = new AnnotationDescriptor<A>( annotationClass );
+
+ if ( constraint.getMessage() != null ) {
+ annotationDescriptor.setValue( MESSAGE_PARAM, constraint.getMessage() );
+ }
+ annotationDescriptor.setValue( GROUPS_PARAM, getGroups( constraint.getGroups(), defaultPackage ) );
+
+ for ( ElementType elementType : constraint.getElement() ) {
+ String name = elementType.getName();
+ checkNameIsValid( name );
+ Class<?> returnType = getAnnotationParamterType( annotationClass, name );
+ Object elementValue = getElementValue( elementType, returnType );
+ annotationDescriptor.setValue( name, elementValue );
+ }
+
+ A annotation = AnnotationFactory.create( annotationDescriptor );
+ ConstraintDescriptorImpl<A> constraintDescriptor = new ConstraintDescriptorImpl<A>(
+ annotation, constraintHelper
+ );
+
+ MetaConstraint<T, A> metaConstraint;
+ if ( member == null ) {
+ metaConstraint = new MetaConstraint<T, A>( beanClass, constraintDescriptor );
+ }
+ else {
+ metaConstraint = new MetaConstraint<T, A>( member, beanClass, constraintDescriptor );
+ }
+ return metaConstraint;
+ }
+
+ private <A extends Annotation> Class<?> getAnnotationParamterType(Class<A> annotationClass, String name) {
+ Method m;
+ try {
+ m = annotationClass.getMethod( name );
+ }
+ catch ( NoSuchMethodException e ) {
+ throw new ValidationException( "Annotation of type " + annotationClass.getName() + " does not contain a paramter " + name + "." );
+ }
+ return m.getReturnType();
+ }
+
+ private Object getElementValue(ElementType elementType, Class<?> returnType) {
+ removeEmptyContentElements( elementType );
+
+ boolean isArray = returnType.isArray();
+ if ( !isArray ) {
+ if ( elementType.getContent().size() != 1 ) {
+ throw new ValidationException( "Attempt to specify an array where single value is expected." );
+ }
+ return getSingleValue( elementType.getContent().get( 0 ), returnType );
+ }
+ else {
+ List<Object> values = new ArrayList<Object>();
+ for ( Serializable s : elementType.getContent() ) {
+ values.add( getSingleValue( s, returnType.getComponentType() ) );
+ }
+ return values.toArray( ( Object[] ) Array.newInstance( returnType.getComponentType(), values.size() ) );
+ }
+ }
+
+ private void removeEmptyContentElements(ElementType elementType) {
+ List<Serializable> contentToDelete = new ArrayList<Serializable>();
+ for ( Serializable content : elementType.getContent() ) {
+ if ( content instanceof String && ( ( String ) content ).matches( "[\\n ].*" ) ) {
+ contentToDelete.add( content );
+ }
+ }
+ elementType.getContent().removeAll( contentToDelete );
+ }
+
+ private Object getSingleValue(Serializable serializable, Class<?> returnType) {
+
+ Object returnValue;
+ if ( serializable instanceof String ) {
+ String value = ( String ) serializable;
+ returnValue = convertStringToReturnType( returnType, value );
+ }
+ else if ( serializable instanceof JAXBElement && ( ( JAXBElement ) serializable ).getDeclaredType()
+ .equals( String.class ) ) {
+ JAXBElement<?> elem = ( JAXBElement<?> ) serializable;
+ String value = ( String ) elem.getValue();
+ returnValue = convertStringToReturnType( returnType, value );
+ }
+ else if ( serializable instanceof JAXBElement && ( ( JAXBElement ) serializable ).getDeclaredType()
+ .equals( AnnotationType.class ) ) {
+ JAXBElement<?> elem = ( JAXBElement<?> ) serializable;
+ AnnotationType annotationType = ( AnnotationType ) elem.getValue();
+ try {
+ @SuppressWarnings("unchecked")
+ Class<Annotation> annotationClass = ( Class<Annotation> ) returnType;
+ returnValue = createAnnotation( annotationType, annotationClass );
+ }
+ catch ( ClassCastException e ) {
+ throw new ValidationException( "Unexpected paramter value" );
+ }
+ }
+ else {
+ throw new ValidationException( "Unexpected paramter value" );
+ }
+ return returnValue;
+
+ }
+
+ private <A extends Annotation> Annotation createAnnotation(AnnotationType annotationType, Class<A> returnType) {
+ AnnotationDescriptor<A> annotationDescriptor = new AnnotationDescriptor<A>( returnType );
+ for ( ElementType elementType : annotationType.getElement() ) {
+ String name = elementType.getName();
+ Class<?> paramterType = getAnnotationParamterType( returnType, name );
+ Object elementValue = getElementValue( elementType, paramterType );
+ annotationDescriptor.setValue( name, elementValue );
+ }
+ return AnnotationFactory.create( annotationDescriptor );
+ }
+
+ private Object convertStringToReturnType(Class<?> returnType, String value) {
+ Object returnValue;
+ if ( returnType.getName().equals( byte.class.getName() ) ) {
+ try {
+ returnValue = Byte.parseByte( value );
+ }
+ catch ( NumberFormatException e ) {
+ throw new ValidationException( "Invalid byte format", e );
+ }
+ }
+ else if ( returnType.getName().equals( short.class.getName() ) ) {
+ try {
+ returnValue = Short.parseShort( value );
+ }
+ catch ( NumberFormatException e ) {
+ throw new ValidationException( "Invalid short format", e );
+ }
+ }
+ else if ( returnType.getName().equals( int.class.getName() ) ) {
+ try {
+ returnValue = Integer.parseInt( value );
+ }
+ catch ( NumberFormatException e ) {
+ throw new ValidationException( "Invalid int format", e );
+ }
+ }
+ else if ( returnType.getName().equals( long.class.getName() ) ) {
+ try {
+ returnValue = Long.parseLong( value );
+ }
+ catch ( NumberFormatException e ) {
+ throw new ValidationException( "Invalid long format", e );
+ }
+ }
+ else if ( returnType.getName().equals( float.class.getName() ) ) {
+ try {
+ returnValue = Float.parseFloat( value );
+ }
+ catch ( NumberFormatException e ) {
+ throw new ValidationException( "Invalid float format", e );
+ }
+ }
+ else if ( returnType.getName().equals( double.class.getName() ) ) {
+ try {
+ returnValue = Double.parseDouble( value );
+ }
+ catch ( NumberFormatException e ) {
+ throw new ValidationException( "Invalid double format", e );
+ }
+ }
+ else if ( returnType.getName().equals( boolean.class.getName() ) ) {
+ returnValue = Boolean.parseBoolean( value );
+ }
+ else if ( returnType.getName().equals( char.class.getName() ) ) {
+ if ( value.length() != 1 ) {
+ throw new ValidationException( "Invalid char value: " + value );
+ }
+ returnValue = value.charAt( 0 );
+ }
+ else if ( returnType.getName().equals( String.class.getName() ) ) {
+ returnValue = value;
+ }
+ else if ( returnType.getName().equals( Class.class.getName() ) ) {
+ try {
+ returnValue = ReflectionHelper.classForName( value, this.getClass() );
+ }
+ catch ( ClassNotFoundException e ) {
+ throw new ValidationException( "Unable to instantiate class: " + value );
+ }
+ }
+ else {
+ try {
+ @SuppressWarnings("unchecked")
+ Class<Enum> enumClass = ( Class<Enum> ) returnType;
+ returnValue = Enum.valueOf( enumClass, value );
+ }
+ catch ( ClassCastException e ) {
+ throw new ValidationException( "Invalid return type: " + returnType + ". Should be a enumeration type." );
+ }
+ }
+ return returnValue;
+ }
+
+ private void checkNameIsValid(String name) {
+ if ( MESSAGE_PARAM.equals( name ) || GROUPS_PARAM.equals( name ) ) {
+ throw new ValidationException( MESSAGE_PARAM + " and " + GROUPS_PARAM + " are reserved paramter names." );
+ }
+ }
+
+ private Class<?>[] getGroups(GroupsType groupsType, String defaultPackage) {
+ if ( groupsType == null ) {
+ return new Class[] { };
+ }
+
+ List<Class<?>> groupList = new ArrayList<Class<?>>();
+ for ( JAXBElement<String> groupClass : groupsType.getValue() ) {
+ groupList.add( getClass( groupClass.getValue(), defaultPackage ) );
+ }
+ return groupList.toArray( new Class[groupList.size()] );
+ }
+
+ private Class<?> getClass(String clazz, String defaultPackage) {
+ String fullyQualifiedClass;
+ if ( isQualifiedClass( clazz ) ) {
+ fullyQualifiedClass = clazz;
+ }
+ else {
+ fullyQualifiedClass = defaultPackage + PACKAGE_SEPERATOR + clazz;
+ }
+ try {
+ return ReflectionHelper.classForName( fullyQualifiedClass, this.getClass() );
+ }
+ catch ( Exception e ) {
+ throw new ValidationException( "Unable to instantiate class " + fullyQualifiedClass );
+ }
+ }
+
+ private boolean isQualifiedClass(String clazz) {
+ return clazz.contains( PACKAGE_SEPERATOR );
+ }
+
+ private ConstraintMappingsType getValidationConfig(InputStream in) {
+ ConstraintMappingsType constraintMappings;
+ Schema schema = getMappingSchema();
+ try {
+ JAXBContext jc = JAXBContext.newInstance( ConstraintMappingsType.class );
+ Unmarshaller unmarshaller = jc.createUnmarshaller();
+ unmarshaller.setSchema( schema );
+ StreamSource stream = new StreamSource( in );
+ JAXBElement<ConstraintMappingsType> root = unmarshaller.unmarshal( stream, ConstraintMappingsType.class );
+ constraintMappings = root.getValue();
+ }
+ catch ( JAXBException e ) {
+ String msg = "Error parsing mapping file.";
+ log.error( msg );
+ throw new ValidationException( msg, e );
+ }
+ return constraintMappings;
+ }
+
+ private Schema getMappingSchema() {
+ URL schemaUrl = this.getClass().getClassLoader().getResource( VALIDATION_MAPPING_XSD );
+ SchemaFactory sf = SchemaFactory.newInstance( javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI );
+ Schema schema = null;
+ try {
+ schema = sf.newSchema( schemaUrl );
+ }
+ catch ( SAXException e ) {
+ log.warn( "Unable to create schema for {}: {}", VALIDATION_MAPPING_XSD, e.getMessage() );
+ }
+ return schema;
+ }
+}
Modified: 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 2009-06-16 15:29:59 UTC (rev 16797)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ConstraintHelperTest.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -29,6 +29,7 @@
import org.testng.annotations.Test;
import org.hibernate.validation.util.ReflectionHelper;
+import org.hibernate.validation.metadata.ConstraintHelper;
/**
* @author Hardy Ferentschik
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-06-16 15:29:59 UTC (rev 16797)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolatorTest.java 2009-06-16 16:16:48 UTC (rev 16798)
@@ -35,6 +35,8 @@
import org.hibernate.validation.util.annotationfactory.AnnotationDescriptor;
import org.hibernate.validation.util.annotationfactory.AnnotationFactory;
+import org.hibernate.validation.metadata.ConstraintDescriptorImpl;
+import org.hibernate.validation.metadata.ConstraintHelper;
/**
* Tests for message resolution.
Modified: validator/trunk/hibernate-validator/src/test/suite/unit-tests.xml
===================================================================
--- validator/trunk/hibernate-validator/src/test/suite/unit-tests.xml 2009-06-16 15:29:59 UTC (rev 16797)
+++ validator/trunk/hibernate-validator/src/test/suite/unit-tests.xml 2009-06-16 16:16:48 UTC (rev 16798)
@@ -10,10 +10,10 @@
<package name="org.hibernate.validation.engine.constraintcomposition"/>
<package name="org.hibernate.validation.engine.graphnavigation"/>
<package name="org.hibernate.validation.engine.groups"/>
- <package name="org.hibernate.validation.engine.metadata"/>
+ <package name="org.hibernate.validation.metadata"/>
<package name="org.hibernate.validation.engine.inheritance"/>
<package name="org.hibernate.validation.engine.resolver"/>
- <package name="org.hibernate.validation.engine.xml"/>
+ <package name="org.hibernate.validation.xml"/>
<package name="org.hibernate.validation.util"/>
<package name="org.hibernate.validation.util.annotationfactory"/>
</packages>
15 years, 5 months
Hibernate SVN: r16797 - in validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine: xml and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-06-16 11:29:59 -0400 (Tue, 16 Jun 2009)
New Revision: 16797
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/ConstraintHelper.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/xml/XmlMappingParser.java
Log:
HV-140 - removed some unchecked warnings
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-06-16 14:35:22 UTC (rev 16796)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataImpl.java 2009-06-16 15:29:59 UTC (rev 16797)
@@ -30,12 +30,12 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
-import javax.validation.metadata.BeanDescriptor;
-import javax.validation.metadata.PropertyDescriptor;
import javax.validation.GroupSequence;
import javax.validation.Valid;
import javax.validation.ValidationException;
import javax.validation.groups.Default;
+import javax.validation.metadata.BeanDescriptor;
+import javax.validation.metadata.PropertyDescriptor;
import org.slf4j.Logger;
@@ -45,11 +45,10 @@
/**
- * This class encapsulates all meta data needed for validation. Implementations of <code>Validator</code> interface can
+ * This class encapsulates all meta data needed for validation. Implementations of {@code Validator} interface can
* instantiate an instance of this class and delegate the metadata extraction to it.
*
* @author Hardy Ferentschik
- * @todo check the unchecked assignment warnings in this class
*/
public class BeanMetaDataImpl<T> implements BeanMetaData<T> {
@@ -122,8 +121,8 @@
return Collections.unmodifiableList( metaConstraintList );
}
- public void addMetaConstraint(MetaConstraint<?, ? extends Annotation> metaConstraint) {
- metaConstraintList.add( ( MetaConstraint<T, ?> ) metaConstraint );
+ public void addMetaConstraint(MetaConstraint<T, ? extends Annotation> metaConstraint) {
+ metaConstraintList.add( metaConstraint );
}
public void addCascadedMember(Member member) {
@@ -223,17 +222,15 @@
setDefaultGroupSequence( groupSequence );
}
- private <A extends Annotation> void initFieldConstraints(Class clazz, AnnotationIgnores annotationIgnores) {
+ private void initFieldConstraints(Class clazz, AnnotationIgnores annotationIgnores) {
for ( Field field : clazz.getDeclaredFields() ) {
- List<ConstraintDescriptorImpl> fieldMetadata = findConstraints( field );
- for ( ConstraintDescriptorImpl constraintDescription : fieldMetadata ) {
+ List<ConstraintDescriptorImpl<?>> fieldMetadata = findConstraints( field );
+ for ( ConstraintDescriptorImpl<?> constraintDescription : fieldMetadata ) {
if ( annotationIgnores.isIgnoreAnnotations( field ) ) {
break;
}
ReflectionHelper.setAccessibility( field );
- MetaConstraint<T, A> metaConstraint = new MetaConstraint<T, A>(
- field, beanClass, constraintDescription
- );
+ MetaConstraint<T, ?> metaConstraint = createMetaConstraint( field, constraintDescription );
metaConstraintList.add( metaConstraint );
}
if ( field.isAnnotationPresent( Valid.class ) ) {
@@ -244,17 +241,15 @@
}
}
- private <A extends Annotation> void initMethodConstraints(Class clazz, AnnotationIgnores annotationIgnores) {
+ private void initMethodConstraints(Class clazz, AnnotationIgnores annotationIgnores) {
for ( Method method : clazz.getDeclaredMethods() ) {
- List<ConstraintDescriptorImpl> methodMetadata = findConstraints( method );
- for ( ConstraintDescriptorImpl constraintDescription : methodMetadata ) {
+ List<ConstraintDescriptorImpl<?>> methodMetadata = findConstraints( method );
+ for ( ConstraintDescriptorImpl<?> constraintDescription : methodMetadata ) {
if ( annotationIgnores.isIgnoreAnnotations( method ) ) {
break;
}
ReflectionHelper.setAccessibility( method );
- MetaConstraint<T, A> metaConstraint = new MetaConstraint<T, A>(
- method, beanClass, constraintDescription
- );
+ MetaConstraint<T, ?> metaConstraint = createMetaConstraint( method, constraintDescription );
metaConstraintList.add( metaConstraint );
}
if ( method.isAnnotationPresent( Valid.class ) ) {
@@ -281,17 +276,25 @@
return propertyDescriptor;
}
- private <A extends Annotation> void initClassConstraints(Class<?> clazz, AnnotationIgnores annotationIgnores) {
+ private void initClassConstraints(Class<?> clazz, AnnotationIgnores annotationIgnores) {
if ( annotationIgnores.isIgnoreAnnotations( clazz ) ) {
return;
}
- List<ConstraintDescriptorImpl> classMetadata = findClassLevelConstraints( clazz );
- for ( ConstraintDescriptorImpl constraintDescription : classMetadata ) {
- MetaConstraint<T, A> metaConstraint = new MetaConstraint<T, A>( beanClass, constraintDescription );
+ List<ConstraintDescriptorImpl<?>> classMetadata = findClassLevelConstraints( clazz );
+ for ( ConstraintDescriptorImpl<?> constraintDescription : classMetadata ) {
+ MetaConstraint<T, ?> metaConstraint = createMetaConstraint( constraintDescription );
metaConstraintList.add( metaConstraint );
}
}
+ private <A extends Annotation> MetaConstraint<T, ?> createMetaConstraint(ConstraintDescriptorImpl<A> descriptor) {
+ return new MetaConstraint<T, A>( beanClass, descriptor );
+ }
+
+ private <A extends Annotation> MetaConstraint<T, ?> createMetaConstraint(Member m, ConstraintDescriptorImpl<A> descriptor) {
+ return new MetaConstraint<T, A>( m, beanClass, descriptor );
+ }
+
/**
* Examines the given annotation to see whether it is a single or multi valued constraint annotation.
*
@@ -301,8 +304,8 @@
* @return A list of constraint descriptors or the empty list in case <code>annotation</code> is neither a
* single nor multi value annotation.
*/
- private <A extends Annotation> List<ConstraintDescriptorImpl> findConstraintAnnotations(Class<?> clazz, A annotation) {
- List<ConstraintDescriptorImpl> constraintDescriptors = new ArrayList<ConstraintDescriptorImpl>();
+ private <A extends Annotation> List<ConstraintDescriptorImpl<?>> findConstraintAnnotations(Class<?> clazz, A annotation) {
+ List<ConstraintDescriptorImpl<?>> constraintDescriptors = new ArrayList<ConstraintDescriptorImpl<?>>();
List<Annotation> constraints = new ArrayList<Annotation>();
if ( constraintHelper.isConstraintAnnotation( annotation ) ||
@@ -322,7 +325,6 @@
@SuppressWarnings("unchecked")
private <A extends Annotation> ConstraintDescriptorImpl buildConstraintDescriptor(Class<?> clazz, A annotation) {
- Class<?>[] groups = ReflectionHelper.getAnnotationParameter( annotation, "groups", Class[].class );
ConstraintDescriptorImpl constraintDescriptor;
if ( clazz.isInterface() ) {
constraintDescriptor = new ConstraintDescriptorImpl( annotation, constraintHelper, clazz );
@@ -341,8 +343,8 @@
*
* @return A list of constraint descriptors for all constraint specified on the given class.
*/
- private List<ConstraintDescriptorImpl> findClassLevelConstraints(Class<?> beanClass) {
- List<ConstraintDescriptorImpl> metadata = new ArrayList<ConstraintDescriptorImpl>();
+ private List<ConstraintDescriptorImpl<?>> findClassLevelConstraints(Class<?> beanClass) {
+ List<ConstraintDescriptorImpl<?>> metadata = new ArrayList<ConstraintDescriptorImpl<?>>();
for ( Annotation annotation : beanClass.getAnnotations() ) {
metadata.addAll( findConstraintAnnotations( beanClass, annotation ) );
}
@@ -361,10 +363,10 @@
*
* @return A list of constraint descriptors for all constraint specified for the given field or method.
*/
- private List<ConstraintDescriptorImpl> findConstraints(Member member) {
+ private List<ConstraintDescriptorImpl<?>> findConstraints(Member member) {
assert member instanceof Field || member instanceof Method;
- List<ConstraintDescriptorImpl> metadata = new ArrayList<ConstraintDescriptorImpl>();
+ List<ConstraintDescriptorImpl<?>> metadata = new ArrayList<ConstraintDescriptorImpl<?>>();
for ( Annotation annotation : ( ( AnnotatedElement ) member ).getAnnotations() ) {
metadata.addAll( findConstraintAnnotations( member.getDeclaringClass(), annotation ) );
}
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintHelper.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintHelper.java 2009-06-16 14:35:22 UTC (rev 16796)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintHelper.java 2009-06-16 15:29:59 UTC (rev 16797)
@@ -21,7 +21,6 @@
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 java.util.concurrent.ConcurrentHashMap;
@@ -31,6 +30,8 @@
import javax.validation.ValidationException;
import javax.validation.constraints.AssertFalse;
import javax.validation.constraints.AssertTrue;
+import javax.validation.constraints.DecimalMax;
+import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Digits;
import javax.validation.constraints.Future;
import javax.validation.constraints.Max;
@@ -40,11 +41,13 @@
import javax.validation.constraints.Past;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
-import javax.validation.constraints.DecimalMax;
-import javax.validation.constraints.DecimalMin;
import org.hibernate.validation.constraints.impl.AssertFalseValidator;
import org.hibernate.validation.constraints.impl.AssertTrueValidator;
+import org.hibernate.validation.constraints.impl.DecimalMaxValidatorForNumber;
+import org.hibernate.validation.constraints.impl.DecimalMaxValidatorForString;
+import org.hibernate.validation.constraints.impl.DecimalMinValidatorForNumber;
+import org.hibernate.validation.constraints.impl.DecimalMinValidatorForString;
import org.hibernate.validation.constraints.impl.DigitsValidatorForNumber;
import org.hibernate.validation.constraints.impl.DigitsValidatorForString;
import org.hibernate.validation.constraints.impl.FutureValidatorForCalendar;
@@ -69,10 +72,6 @@
import org.hibernate.validation.constraints.impl.SizeValidatorForCollection;
import org.hibernate.validation.constraints.impl.SizeValidatorForMap;
import org.hibernate.validation.constraints.impl.SizeValidatorForString;
-import org.hibernate.validation.constraints.impl.DecimalMaxValidatorForNumber;
-import org.hibernate.validation.constraints.impl.DecimalMaxValidatorForString;
-import org.hibernate.validation.constraints.impl.DecimalMinValidatorForNumber;
-import org.hibernate.validation.constraints.impl.DecimalMinValidatorForString;
import org.hibernate.validation.util.ReflectionHelper;
/**
@@ -83,14 +82,10 @@
*/
public class ConstraintHelper {
- private final Map<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<?, ?>>>> builtinConstraints =
+ private final static Map<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<?, ?>>>> builtinConstraints =
new ConcurrentHashMap<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<?, ?>>>>();
- private final Map<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<? extends Annotation, ?>>>> constraintValidatorDefinitons =
- new ConcurrentHashMap<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<? extends Annotation, ?>>>>();
-
- public ConstraintHelper() {
-
+ static {
List<Class<? extends ConstraintValidator<?, ?>>> constraintList =
new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
constraintList.add( AssertFalseValidator.class );
@@ -162,6 +157,9 @@
builtinConstraints.put( Size.class, constraintList );
}
+ private final Map<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<? extends Annotation, ?>>>> constraintValidatorDefinitons =
+ new ConcurrentHashMap<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<? extends Annotation, ?>>>>();
+
public List<Class<? extends ConstraintValidator<? extends Annotation, ?>>> getBuiltInConstraints(Class<? extends Annotation> annotationType) {
final List<Class<? extends ConstraintValidator<?, ?>>> builtInList = getBuiltInFromAnnotationType(
annotationType
@@ -276,7 +274,7 @@
*
* @return <code>true</code> if the annotation fulfills the above condtions, <code>false</code> otherwise.
*/
- public static boolean isConstraintAnnotation(Annotation annotation) {
+ public boolean isConstraintAnnotation(Annotation annotation) {
Constraint constraint = annotation.annotationType()
.getAnnotation( Constraint.class );
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-06-16 14:35:22 UTC (rev 16796)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorFactoryImpl.java 2009-06-16 15:29:59 UTC (rev 16797)
@@ -57,16 +57,10 @@
initBeanMetaData( configurationState.getMappingStreams() );
}
- /**
- * {@inheritDoc}
- */
public Validator getValidator() {
return usingContext().getValidator();
}
- /**
- * {@inheritDoc}
- */
public MessageInterpolator getMessageInterpolator() {
return messageInterpolator;
}
@@ -75,9 +69,6 @@
throw new ValidationException( "Type " + type + " not supported");
}
- /**
- * {@inheritDoc}
- */
public ValidatorContext usingContext() {
return new ValidatorContextImpl(
constraintValidatorFactory,
@@ -95,11 +86,11 @@
AnnotationIgnores annotationIgnores = mappingParser.getAnnotationIgnores();
for ( Class<?> beanClass : mappingParser.getProcessedClasses() ) {
- BeanMetaDataImpl<?> metaData = new BeanMetaDataImpl<T>(
+ BeanMetaDataImpl<T> metaData = new BeanMetaDataImpl<T>(
( Class<T> ) beanClass, constraintHelper, annotationIgnores
);
- for ( MetaConstraint<?, ? extends Annotation> constraint : mappingParser.getConstraintsForClass( beanClass ) ) {
+ for ( MetaConstraint<T, ? extends Annotation> constraint : mappingParser.getConstraintsForClass( ( Class<T> ) beanClass ) ) {
metaData.addMetaConstraint( constraint );
}
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/XmlMappingParser.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/XmlMappingParser.java 2009-06-16 14:35:22 UTC (rev 16796)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/XmlMappingParser.java 2009-06-16 15:29:59 UTC (rev 16797)
@@ -128,9 +128,15 @@
return annotationIgnores;
}
- public List<MetaConstraint<?, ? extends Annotation>> getConstraintsForClass(Class<?> beanClass) {
+ public <T> List<MetaConstraint<T, ? extends Annotation>> getConstraintsForClass(Class<T> beanClass) {
+ List<MetaConstraint<T, ? extends Annotation>> list = new ArrayList<MetaConstraint<T, ? extends Annotation>>();
if ( constraintMap.containsKey( beanClass ) ) {
- return constraintMap.get( beanClass );
+ for ( MetaConstraint<?, ? extends Annotation> metaConstraint : constraintMap.get( beanClass ) ) {
+ @SuppressWarnings( "unchecked") // safe cast since the list of meta constraints is always specific to the bean type
+ MetaConstraint<T, ? extends Annotation> boundMetaConstraint = ( MetaConstraint<T, ? extends Annotation> ) metaConstraint;
+ list.add( boundMetaConstraint );
+ }
+ return list;
}
else {
return Collections.emptyList();
15 years, 5 months
Hibernate SVN: r16796 - in core/branches/INFINISPAN/cache-infinispan: src/main/java/org/hibernate/cache/infinispan and 7 other directories.
by hibernate-commits@lists.jboss.org
Author: cbredesen
Date: 2009-06-16 10:35:22 -0400 (Tue, 16 Jun 2009)
New Revision: 16796
Added:
core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/
core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseGeneralDataRegion.java
core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseRegion.java
core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseTransactionalDataRegion.java
core/branches/INFINISPAN/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/BasicCacheTest.java
Removed:
core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/BaseGeneralDataRegion.java
core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/BaseRegion.java
core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/BaseTransactionalDataRegion.java
core/branches/INFINISPAN/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/BasicEntityTest.java
Modified:
core/branches/INFINISPAN/cache-infinispan/pom.xml
core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/InfinispanCollectionRegion.java
core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/ReadOnlyAccess.java
core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/TransactionalAccess.java
core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/InfinispanEntityRegion.java
core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/query/InfinispanQueryResultsRegion.java
core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/InfinispanTimestampsRegion.java
core/branches/INFINISPAN/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/Item.hbm.xml
core/branches/INFINISPAN/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/Item.java
core/branches/INFINISPAN/cache-infinispan/src/test/resources/hibernate.properties
Log:
Refactoring, extra test coverage, fixes
Modified: core/branches/INFINISPAN/cache-infinispan/pom.xml
===================================================================
--- core/branches/INFINISPAN/cache-infinispan/pom.xml 2009-06-16 14:34:28 UTC (rev 16795)
+++ core/branches/INFINISPAN/cache-infinispan/pom.xml 2009-06-16 14:35:22 UTC (rev 16796)
@@ -25,7 +25,7 @@
<dependency>
<groupId>org.infinispan</groupId>
<artifactId>infinispan-core</artifactId>
- <version>4.0.0.ALPHA3</version>
+ <version>4.0.0.ALPHA5</version>
</dependency>
<!-- test dependencies -->
Deleted: core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/BaseGeneralDataRegion.java
===================================================================
--- core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/BaseGeneralDataRegion.java 2009-06-16 14:34:28 UTC (rev 16795)
+++ core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/BaseGeneralDataRegion.java 2009-06-16 14:35:22 UTC (rev 16796)
@@ -1,34 +0,0 @@
-package org.hibernate.cache.infinispan;
-
-import org.hibernate.cache.CacheException;
-import org.hibernate.cache.GeneralDataRegion;
-import org.infinispan.Cache;
-
-/**
- * Support for Infinispan {@link GeneralDataRegion} implementors.
- *
- * @author Chris Bredesen
- */
-public abstract class BaseGeneralDataRegion extends BaseRegion implements GeneralDataRegion {
-
- public BaseGeneralDataRegion( Cache<Object, Object> cache, String name ) {
- super( cache, name );
- }
-
- public void evict( Object key ) throws CacheException {
- getCache().evict( key );
- }
-
- public void evictAll() throws CacheException {
- getCache().clear();
- }
-
- public Object get( Object key ) throws CacheException {
- return getCache().get( key );
- }
-
- public void put( Object key, Object value ) throws CacheException {
- getCache().put( key, value );
- }
-
-}
\ No newline at end of file
Deleted: core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/BaseRegion.java
===================================================================
--- core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/BaseRegion.java 2009-06-16 14:34:28 UTC (rev 16795)
+++ core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/BaseRegion.java 2009-06-16 14:35:22 UTC (rev 16796)
@@ -1,76 +0,0 @@
-package org.hibernate.cache.infinispan;
-
-import java.util.Collections;
-import java.util.Map;
-
-import org.hibernate.cache.CacheException;
-import org.hibernate.cache.Region;
-import org.infinispan.Cache;
-
-/**
- * Support for Infinispan {@link Region}s. Handles common "utility" methods for
- * an underlying named Cache. In other words, this implementation doesn't
- * actually read or write data. Subclasses are expected to provide core cache
- * interaction appropriate to the semantics needed.
- *
- * @author Chris Bredesen
- */
-abstract class BaseRegion implements Region {
- private final Cache<Object, Object> cache;
- private final String name;
-
- public BaseRegion( Cache<Object, Object> cache, String name ) {
- this.cache = cache;
- this.name = name;
- }
-
- public Cache<Object, Object> getCache() {
- return cache;
- }
-
- public String getName() {
- return name;
- }
-
- public long getElementCountInMemory() {
- return cache.size();
- }
-
- /**
- * Not supported.
- *
- * @return -1
- */
- public long getElementCountOnDisk() {
- return -1;
- }
-
- /**
- * Not supported.
- *
- * @return -1
- */
- public long getSizeInMemory() {
- return -1;
- }
-
- public int getTimeout() {
- // TODO Auto-generated method stub
- return 0;
- }
-
- public long nextTimestamp() {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @SuppressWarnings("unchecked")
- public Map toMap() {
- return Collections.EMPTY_MAP;
- }
-
- public void destroy() throws CacheException {
- // TODO see if we need to do this even in spite of RF.shutdown()
- }
-
-}
\ No newline at end of file
Deleted: core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/BaseTransactionalDataRegion.java
===================================================================
--- core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/BaseTransactionalDataRegion.java 2009-06-16 14:34:28 UTC (rev 16795)
+++ core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/BaseTransactionalDataRegion.java 2009-06-16 14:35:22 UTC (rev 16796)
@@ -1,28 +0,0 @@
-package org.hibernate.cache.infinispan;
-
-import org.hibernate.cache.CacheDataDescription;
-import org.hibernate.cache.TransactionalDataRegion;
-import org.infinispan.Cache;
-
-/**
- * Support for Inifinispan {@link TransactionalDataRegion} implementors.
- *
- * @author Chris Bredesen
- */
-public abstract class BaseTransactionalDataRegion extends BaseRegion implements TransactionalDataRegion {
- private final CacheDataDescription metadata;
-
- public BaseTransactionalDataRegion( Cache<Object, Object> cache, String name, CacheDataDescription metadata ) {
- super( cache, name );
- this.metadata = metadata;
- }
-
- public CacheDataDescription getCacheDataDescription() {
- return metadata;
- }
-
- public boolean isTransactionAware() {
- return true;
- }
-
-}
\ No newline at end of file
Modified: core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/InfinispanCollectionRegion.java
===================================================================
--- core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/InfinispanCollectionRegion.java 2009-06-16 14:34:28 UTC (rev 16795)
+++ core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/InfinispanCollectionRegion.java 2009-06-16 14:35:22 UTC (rev 16796)
@@ -5,7 +5,7 @@
import org.hibernate.cache.CollectionRegion;
import org.hibernate.cache.access.AccessType;
import org.hibernate.cache.access.CollectionRegionAccessStrategy;
-import org.hibernate.cache.infinispan.BaseTransactionalDataRegion;
+import org.hibernate.cache.infinispan.impl.BaseTransactionalDataRegion;
import org.infinispan.Cache;
public class InfinispanCollectionRegion extends BaseTransactionalDataRegion implements CollectionRegion {
Modified: core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/ReadOnlyAccess.java
===================================================================
--- core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/ReadOnlyAccess.java 2009-06-16 14:34:28 UTC (rev 16795)
+++ core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/ReadOnlyAccess.java 2009-06-16 14:35:22 UTC (rev 16796)
@@ -2,25 +2,23 @@
import org.hibernate.cache.CacheException;
import org.hibernate.cache.CollectionRegion;
-import org.hibernate.cache.Region;
import org.hibernate.cache.access.CollectionRegionAccessStrategy;
import org.hibernate.cache.access.SoftLock;
public class ReadOnlyAccess implements CollectionRegionAccessStrategy {
- private final Region region;
+ private final InfinispanCollectionRegion region;
- public ReadOnlyAccess( Region region ) {
+ public ReadOnlyAccess( InfinispanCollectionRegion region ) {
this.region = region;
}
public void evict( Object key ) throws CacheException {
- // TODO Auto-generated method stub
-
+ region.getCache().evict( key );
}
public void evictAll() throws CacheException {
- // TODO Auto-generated method stub
-
+ // TODO ensure proper clustering semantics here
+ region.getCache().clear();
}
public Object get( Object key, long txTimestamp ) throws CacheException {
@@ -29,8 +27,7 @@
}
public CollectionRegion getRegion() {
- // TODO Auto-generated method stub
- return null;
+ return region;
}
public SoftLock lockItem( Object key, Object version ) throws CacheException {
Modified: core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/TransactionalAccess.java
===================================================================
--- core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/TransactionalAccess.java 2009-06-16 14:34:28 UTC (rev 16795)
+++ core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/TransactionalAccess.java 2009-06-16 14:35:22 UTC (rev 16796)
@@ -2,77 +2,72 @@
import org.hibernate.cache.CacheException;
import org.hibernate.cache.CollectionRegion;
-import org.hibernate.cache.Region;
import org.hibernate.cache.access.CollectionRegionAccessStrategy;
import org.hibernate.cache.access.SoftLock;
+/**
+ * Transactional collection region access for Infinispan.
+ *
+ * @author Chris Bredesen
+ */
public class TransactionalAccess implements CollectionRegionAccessStrategy {
- private final Region region;
+ private final InfinispanCollectionRegion region;
- public TransactionalAccess( Region region ) {
+ public TransactionalAccess( InfinispanCollectionRegion region ) {
this.region = region;
}
public void evict( Object key ) throws CacheException {
- // TODO Auto-generated method stub
-
+ region.getCache().evict( key );
}
public void evictAll() throws CacheException {
- // TODO Auto-generated method stub
-
+ // TODO ensure proper clustering semantics
+ region.getCache().clear();
}
public Object get( Object key, long txTimestamp ) throws CacheException {
- // TODO Auto-generated method stub
- return null;
+ return region.getCache().get( key );
}
- public CollectionRegion getRegion() {
- // TODO Auto-generated method stub
- return null;
- }
-
- public SoftLock lockItem( Object key, Object version ) throws CacheException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public SoftLock lockRegion() throws CacheException {
- // TODO Auto-generated method stub
- return null;
- }
-
public boolean putFromLoad( Object key, Object value, long txTimestamp, Object version )
throws CacheException {
- // TODO Auto-generated method stub
- return false;
+ region.getCache().putForExternalRead( key, value );
+ return true;
}
public boolean putFromLoad( Object key, Object value, long txTimestamp, Object version,
boolean minimalPutOverride ) throws CacheException {
- // TODO Auto-generated method stub
- return false;
+ region.getCache().putForExternalRead( key, value );
+ return true;
}
public void remove( Object key ) throws CacheException {
- // TODO Auto-generated method stub
-
+ region.getCache().remove( key );
}
public void removeAll() throws CacheException {
- // TODO Auto-generated method stub
+ region.getCache().clear();
+ }
+ public CollectionRegion getRegion() {
+ return region;
}
- public void unlockItem( Object key, SoftLock lock ) throws CacheException {
- // TODO Auto-generated method stub
+ // following methods copied from o.h.c.jbc2.collection.TransactionalAccess
- }
+ public SoftLock lockItem(Object key, Object version) throws CacheException {
+ return null;
+ }
- public void unlockRegion( SoftLock lock ) throws CacheException {
- // TODO Auto-generated method stub
+ public SoftLock lockRegion() throws CacheException {
+ return null;
+ }
- }
+ public void unlockItem(Object key, SoftLock lock) throws CacheException {
+ }
-}
+ public void unlockRegion(SoftLock lock) throws CacheException {
+ }
+
+}
\ No newline at end of file
Modified: core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/InfinispanEntityRegion.java
===================================================================
--- core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/InfinispanEntityRegion.java 2009-06-16 14:34:28 UTC (rev 16795)
+++ core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/InfinispanEntityRegion.java 2009-06-16 14:35:22 UTC (rev 16796)
@@ -5,7 +5,7 @@
import org.hibernate.cache.EntityRegion;
import org.hibernate.cache.access.AccessType;
import org.hibernate.cache.access.EntityRegionAccessStrategy;
-import org.hibernate.cache.infinispan.BaseTransactionalDataRegion;
+import org.hibernate.cache.infinispan.impl.BaseTransactionalDataRegion;
import org.infinispan.Cache;
public class InfinispanEntityRegion extends BaseTransactionalDataRegion implements EntityRegion {
Copied: core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseGeneralDataRegion.java (from rev 16771, core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/BaseGeneralDataRegion.java)
===================================================================
--- core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseGeneralDataRegion.java (rev 0)
+++ core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseGeneralDataRegion.java 2009-06-16 14:35:22 UTC (rev 16796)
@@ -0,0 +1,34 @@
+package org.hibernate.cache.infinispan.impl;
+
+import org.hibernate.cache.CacheException;
+import org.hibernate.cache.GeneralDataRegion;
+import org.infinispan.Cache;
+
+/**
+ * Support for Infinispan {@link GeneralDataRegion} implementors.
+ *
+ * @author Chris Bredesen
+ */
+public abstract class BaseGeneralDataRegion extends BaseRegion implements GeneralDataRegion {
+
+ public BaseGeneralDataRegion( Cache<Object, Object> cache, String name ) {
+ super( cache, name );
+ }
+
+ public void evict( Object key ) throws CacheException {
+ getCache().evict( key );
+ }
+
+ public void evictAll() throws CacheException {
+ getCache().clear();
+ }
+
+ public Object get( Object key ) throws CacheException {
+ return getCache().get( key );
+ }
+
+ public void put( Object key, Object value ) throws CacheException {
+ getCache().put( key, value );
+ }
+
+}
\ No newline at end of file
Property changes on: core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseGeneralDataRegion.java
___________________________________________________________________
Name: svn:mergeinfo
+
Copied: core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseRegion.java (from rev 16778, core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/BaseRegion.java)
===================================================================
--- core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseRegion.java (rev 0)
+++ core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseRegion.java 2009-06-16 14:35:22 UTC (rev 16796)
@@ -0,0 +1,76 @@
+package org.hibernate.cache.infinispan.impl;
+
+import java.util.Collections;
+import java.util.Map;
+
+import org.hibernate.cache.CacheException;
+import org.hibernate.cache.Region;
+import org.infinispan.Cache;
+
+/**
+ * Support for Infinispan {@link Region}s. Handles common "utility" methods for
+ * an underlying named Cache. In other words, this implementation doesn't
+ * actually read or write data. Subclasses are expected to provide core cache
+ * interaction appropriate to the semantics needed.
+ *
+ * @author Chris Bredesen
+ */
+abstract class BaseRegion implements Region {
+ private final Cache<Object, Object> cache;
+ private final String name;
+
+ public BaseRegion( Cache<Object, Object> cache, String name ) {
+ this.cache = cache;
+ this.name = name;
+ }
+
+ public Cache<Object, Object> getCache() {
+ return cache;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public long getElementCountInMemory() {
+ return cache.size();
+ }
+
+ /**
+ * Not supported.
+ *
+ * @return -1
+ */
+ public long getElementCountOnDisk() {
+ return -1;
+ }
+
+ /**
+ * Not supported.
+ *
+ * @return -1
+ */
+ public long getSizeInMemory() {
+ return -1;
+ }
+
+ public int getTimeout() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ public long nextTimestamp() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ @SuppressWarnings("unchecked")
+ public Map toMap() {
+ return Collections.EMPTY_MAP;
+ }
+
+ public void destroy() throws CacheException {
+ // TODO see if we need to do this even in spite of RF.shutdown()
+ }
+
+}
\ No newline at end of file
Property changes on: core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseRegion.java
___________________________________________________________________
Name: svn:mergeinfo
+
Copied: core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseTransactionalDataRegion.java (from rev 16771, core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/BaseTransactionalDataRegion.java)
===================================================================
--- core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseTransactionalDataRegion.java (rev 0)
+++ core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseTransactionalDataRegion.java 2009-06-16 14:35:22 UTC (rev 16796)
@@ -0,0 +1,28 @@
+package org.hibernate.cache.infinispan.impl;
+
+import org.hibernate.cache.CacheDataDescription;
+import org.hibernate.cache.TransactionalDataRegion;
+import org.infinispan.Cache;
+
+/**
+ * Support for Inifinispan {@link TransactionalDataRegion} implementors.
+ *
+ * @author Chris Bredesen
+ */
+public abstract class BaseTransactionalDataRegion extends BaseRegion implements TransactionalDataRegion {
+ private final CacheDataDescription metadata;
+
+ public BaseTransactionalDataRegion( Cache<Object, Object> cache, String name, CacheDataDescription metadata ) {
+ super( cache, name );
+ this.metadata = metadata;
+ }
+
+ public CacheDataDescription getCacheDataDescription() {
+ return metadata;
+ }
+
+ public boolean isTransactionAware() {
+ return true;
+ }
+
+}
\ No newline at end of file
Property changes on: core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseTransactionalDataRegion.java
___________________________________________________________________
Name: svn:mergeinfo
+
Modified: core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/query/InfinispanQueryResultsRegion.java
===================================================================
--- core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/query/InfinispanQueryResultsRegion.java 2009-06-16 14:34:28 UTC (rev 16795)
+++ core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/query/InfinispanQueryResultsRegion.java 2009-06-16 14:35:22 UTC (rev 16796)
@@ -1,7 +1,7 @@
package org.hibernate.cache.infinispan.query;
import org.hibernate.cache.QueryResultsRegion;
-import org.hibernate.cache.infinispan.BaseGeneralDataRegion;
+import org.hibernate.cache.infinispan.impl.BaseGeneralDataRegion;
import org.infinispan.Cache;
public class InfinispanQueryResultsRegion extends BaseGeneralDataRegion implements QueryResultsRegion {
Modified: core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/InfinispanTimestampsRegion.java
===================================================================
--- core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/InfinispanTimestampsRegion.java 2009-06-16 14:34:28 UTC (rev 16795)
+++ core/branches/INFINISPAN/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/InfinispanTimestampsRegion.java 2009-06-16 14:35:22 UTC (rev 16796)
@@ -1,7 +1,7 @@
package org.hibernate.cache.infinispan.timestamp;
import org.hibernate.cache.TimestampsRegion;
-import org.hibernate.cache.infinispan.BaseGeneralDataRegion;
+import org.hibernate.cache.infinispan.impl.BaseGeneralDataRegion;
import org.infinispan.Cache;
public class InfinispanTimestampsRegion extends BaseGeneralDataRegion implements TimestampsRegion {
Copied: core/branches/INFINISPAN/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/BasicCacheTest.java (from rev 16778, core/branches/INFINISPAN/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/BasicEntityTest.java)
===================================================================
--- core/branches/INFINISPAN/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/BasicCacheTest.java (rev 0)
+++ core/branches/INFINISPAN/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/BasicCacheTest.java 2009-06-16 14:35:22 UTC (rev 16796)
@@ -0,0 +1,93 @@
+package org.hibernate.test.cache.infinispan.functional;
+
+import org.hibernate.Session;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.stat.SecondLevelCacheStatistics;
+import org.hibernate.stat.Statistics;
+
+public class BasicCacheTest extends FunctionalTestCase {
+
+ public BasicCacheTest( String string ) {
+ super( string );
+ }
+
+ public String[] getMappings() {
+ return new String[] { "cache/infinispan/functional/Item.hbm.xml" };
+ }
+
+ @Override
+ public String getCacheConcurrencyStrategy() {
+ return "transactional";
+ }
+
+ public void testEntityCache() {
+ Item item = new Item("chris", "Chris's Item");
+
+ Session s = openSession();
+ Statistics stats = s.getSessionFactory().getStatistics();
+ s.getTransaction().begin();
+ s.persist( item );
+ s.getTransaction().commit();
+ s.close();
+
+ stats.clear();
+ s = openSession();
+ Item found = (Item) s.load( Item.class, item.getId() );
+ System.out.println( stats );
+ assertEquals( item.getDescription(), found.getDescription() );
+ assertEquals( 0, stats.getSecondLevelCacheMissCount() );
+ assertEquals( 1, stats.getSecondLevelCacheHitCount() );
+ s.delete( found );
+ s.close();
+ }
+
+ public void testQueryCache() {
+ Item item = new Item( "chris", "Chris's Item" );
+
+ Session s = openSession();
+ s.getTransaction().begin();
+ s.persist( item );
+ s.getTransaction().commit();
+ s.close();
+
+ s = openSession();
+ s.createQuery( "from Item" ).setCacheable( true ).list();
+ s.close();
+
+ s = openSession();
+ Statistics stats = s.getSessionFactory().getStatistics();
+ stats.clear();
+ s.createQuery( "from Item" ).setCacheable( true ).list();
+ assertEquals( 1, stats.getQueryCacheHitCount() );
+ s.createQuery( "delete from Item" ).executeUpdate();
+ s.close();
+ }
+
+ public void testCollectionCache() {
+ Item item = new Item( "chris", "Chris's Item" );
+ Item another = new Item( "another", "Owned Item" );
+ item.addItem( another );
+
+ Session s = openSession();
+ s.getTransaction().begin();
+ s.persist( another );
+ s.persist( item );
+ s.getTransaction().commit();
+ s.close();
+
+ s = openSession();
+ Item loaded = (Item) s.load( Item.class, item.getId() );
+ assertEquals( 1, loaded.getItems().size() );
+ s.close();
+
+ s = openSession();
+ Statistics stats = s.getSessionFactory().getStatistics();
+ stats.clear();
+ SecondLevelCacheStatistics cStats = stats.getSecondLevelCacheStatistics( Item.class.getName() + ".items" );
+ Item loadedWithCachedCollection = (Item) s.load( Item.class, item.getId() );
+ assertEquals( 1, loadedWithCachedCollection.getItems().size() );
+ assertEquals( 1, cStats.getHitCount() );
+ s.close();
+ }
+
+}
\ No newline at end of file
Property changes on: core/branches/INFINISPAN/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/BasicCacheTest.java
___________________________________________________________________
Name: svn:mergeinfo
+
Deleted: core/branches/INFINISPAN/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/BasicEntityTest.java
===================================================================
--- core/branches/INFINISPAN/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/BasicEntityTest.java 2009-06-16 14:34:28 UTC (rev 16795)
+++ core/branches/INFINISPAN/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/BasicEntityTest.java 2009-06-16 14:35:22 UTC (rev 16796)
@@ -1,45 +0,0 @@
-package org.hibernate.test.cache.infinispan.functional;
-
-import org.hibernate.Session;
-import org.hibernate.junit.functional.FunctionalTestCase;
-import org.hibernate.stat.Statistics;
-
-public class BasicEntityTest extends FunctionalTestCase {
-
- public BasicEntityTest( String string ) {
- super( string );
- }
-
- public String[] getMappings() {
- return new String[] { "cache/infinispan/functional/Item.hbm.xml" };
- }
-
- @Override
- public String getCacheConcurrencyStrategy() {
- return "transactional";
- }
-
- public void testEntityCache() {
- Item item = new Item();
- item.setName( "chris" );
- item.setDescription( "Chris's Item" );
-
- Session s = openSession();
- Statistics stats = s.getSessionFactory().getStatistics();
- s.getTransaction().begin();
- s.persist( item );
- s.getTransaction().commit();
- s.close();
-
- stats.clear();
- s = openSession();
- Item found = (Item) s.load( Item.class, item.getId() );
- System.out.println( stats );
- assertEquals( item.getDescription(), found.getDescription() );
- assertEquals( 0, stats.getSecondLevelCacheMissCount() );
- assertEquals( 1, stats.getSecondLevelCacheHitCount() );
- s.delete( found );
- s.close();
- }
-
-}
\ No newline at end of file
Modified: core/branches/INFINISPAN/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/Item.hbm.xml
===================================================================
--- core/branches/INFINISPAN/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/Item.hbm.xml 2009-06-16 14:34:28 UTC (rev 16795)
+++ core/branches/INFINISPAN/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/Item.hbm.xml 2009-06-16 14:35:22 UTC (rev 16796)
@@ -35,6 +35,11 @@
</id>
<property name="name" not-null="true"/>
<property name="description" not-null="true"/>
+ <many-to-one name="owner" column="owner_id" class="Item" />
+ <set name="items" inverse="true">
+ <key column="owner_id" />
+ <one-to-many class="Item"/>
+ </set>
</class>
<class name="VersionedItem" table="VersionedItems">
@@ -46,4 +51,4 @@
<property name="description" not-null="true"/>
</class>
-</hibernate-mapping>
+</hibernate-mapping>
\ No newline at end of file
Modified: core/branches/INFINISPAN/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/Item.java
===================================================================
--- core/branches/INFINISPAN/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/Item.java 2009-06-16 14:34:28 UTC (rev 16795)
+++ core/branches/INFINISPAN/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/Item.java 2009-06-16 14:35:22 UTC (rev 16796)
@@ -23,6 +23,9 @@
*/
package org.hibernate.test.cache.infinispan.functional;
+import java.util.HashSet;
+import java.util.Set;
+
/**
* @author Gavin King
*/
@@ -30,8 +33,17 @@
private Long id;
private String name;
private String description;
+ private Item owner;
+ private Set<Item> items = new HashSet<Item>();
- public String getDescription() {
+ public Item() {}
+
+ public Item( String name, String description ) {
+ this.name = name;
+ this.description = description;
+ }
+
+ public String getDescription() {
return description;
}
@@ -54,4 +66,25 @@
public void setName(String name) {
this.name = name;
}
+
+ public Item getOwner() {
+ return owner;
+ }
+
+ public void setOwner( Item owner ) {
+ this.owner = owner;
+ }
+
+ public Set<Item> getItems() {
+ return items;
+ }
+
+ public void setItems( Set<Item> items ) {
+ this.items = items;
+ }
+
+ public void addItem( Item item ) {
+ item.setOwner( this );
+ getItems().add( item );
+ }
}
Modified: core/branches/INFINISPAN/cache-infinispan/src/test/resources/hibernate.properties
===================================================================
--- core/branches/INFINISPAN/cache-infinispan/src/test/resources/hibernate.properties 2009-06-16 14:34:28 UTC (rev 16795)
+++ core/branches/INFINISPAN/cache-infinispan/src/test/resources/hibernate.properties 2009-06-16 14:35:22 UTC (rev 16796)
@@ -36,4 +36,5 @@
hibernate.generate_statistics true
hibernate.cache.use_second_level_cache true
+hibernate.cache.use_query_cache true
hibernate.cache.region.factory_class org.hibernate.cache.infinispan.InfinispanRegionFactory
\ No newline at end of file
15 years, 5 months
Hibernate SVN: r16795 - core/branches/INFINISPAN/testsuite.
by hibernate-commits@lists.jboss.org
Author: cbredesen
Date: 2009-06-16 10:34:28 -0400 (Tue, 16 Jun 2009)
New Revision: 16795
Modified:
core/branches/INFINISPAN/testsuite/pom.xml
Log:
Removing errant dependency addition
Modified: core/branches/INFINISPAN/testsuite/pom.xml
===================================================================
--- core/branches/INFINISPAN/testsuite/pom.xml 2009-06-16 14:18:22 UTC (rev 16794)
+++ core/branches/INFINISPAN/testsuite/pom.xml 2009-06-16 14:34:28 UTC (rev 16795)
@@ -110,11 +110,6 @@
<artifactId>hsqldb</artifactId>
<version>1.8.0.2</version>
</dependency>
- <dependency>
- <groupId>${groupId}</groupId>
- <artifactId>hibernate-infinispan</artifactId>
- <version>${version}</version>
- </dependency>
</dependencies>
<properties>
<db.dialect>org.hibernate.dialect.HSQLDialect</db.dialect>
15 years, 5 months