Hibernate SVN: r16402 - in validator/trunk: hibernate-validator and 26 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-04-22 10:13:26 -0400 (Wed, 22 Apr 2009)
New Revision: 16402
Modified:
validator/trunk/hibernate-validator-archetype/pom.xml
validator/trunk/hibernate-validator-archetype/src/main/resources/log4j.properties
validator/trunk/hibernate-validator-legacy/pom.xml
validator/trunk/hibernate-validator-legacy/src/main/assembly/dist.xml
validator/trunk/hibernate-validator-legacy/src/main/docbook/en-US/master.xml
validator/trunk/hibernate-validator-legacy/src/main/docbook/en-US/modules/checkconstraints.xml
validator/trunk/hibernate-validator-legacy/src/main/docbook/en-US/modules/defineconstraints.xml
validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages.properties
validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_cs.properties
validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_da.properties
validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_de.properties
validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_en.properties
validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_es.properties
validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_fr.properties
validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_it.properties
validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_ja.properties
validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_nl.properties
validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_pt_BR.properties
validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_sv.properties
validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_zh_CN.properties
validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_zh_TW.properties
validator/trunk/hibernate-validator-legacy/src/test/resources/ValidatorMessages.properties
validator/trunk/hibernate-validator-legacy/src/test/resources/ValidatorMessages_da.properties
validator/trunk/hibernate-validator-legacy/src/test/resources/ValidatorMessages_fr.properties
validator/trunk/hibernate-validator-legacy/src/test/resources/hibernate.properties
validator/trunk/hibernate-validator-legacy/src/test/resources/log4j.properties
validator/trunk/hibernate-validator-legacy/src/test/resources/messages_en.properties
validator/trunk/hibernate-validator-tck-runner/pom.xml
validator/trunk/hibernate-validator-tck-runner/src/jboss-as/build.properties
validator/trunk/hibernate-validator-tck-runner/src/jboss-as/build.xml
validator/trunk/hibernate-validator-tck-runner/src/main/resources/META-INF/jboss-test-harness.properties
validator/trunk/hibernate-validator-tck-runner/src/test/resources/jndi.properties
validator/trunk/hibernate-validator-tck-runner/src/test/resources/log4j.xml
validator/trunk/hibernate-validator-tck-runner/src/test/resources/org/jboss/testharness/impl/packaging/jsr299/default/beans.xml
validator/trunk/hibernate-validator/pom.xml
validator/trunk/hibernate-validator/src/main/assembly/dist.xml
validator/trunk/hibernate-validator/src/main/docbook/en-US/master.xml
validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/checkconstraints.xml
validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/customconstraints.xml
validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/defineconstraints.xml
validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/extendedri.xml
validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/gettingstarted.xml
validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/integration.xml
validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/introduction.xml
validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/usingvalidator.xml
validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/xmlconfiguration.xml
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java
validator/trunk/hibernate-validator/src/site/site.xml
validator/trunk/hibernate-validator/src/test/resources/META-INF/validation.xml
validator/trunk/hibernate-validator/src/test/resources/META-INF/validation/order-constraints.xml
validator/trunk/hibernate-validator/src/test/resources/META-INF/validation/user-constraints.xml
validator/trunk/hibernate-validator/src/test/resources/ValidationMessages_es.properties
validator/trunk/hibernate-validator/src/test/resources/log4j.properties
validator/trunk/hibernate-validator/src/test/suite/unit-tests.xml
validator/trunk/pom.xml
validator/trunk/src/site/site.xml
validator/trunk/tck-utils/api/pom.xml
validator/trunk/tck-utils/impl/pom.xml
validator/trunk/tck-utils/pom.xml
Log:
svn:keywords
Property changes on: validator/trunk/hibernate-validator/pom.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/main/assembly/dist.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/main/docbook/en-US/master.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/checkconstraints.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/customconstraints.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/defineconstraints.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/extendedri.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/gettingstarted.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/integration.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/introduction.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/usingvalidator.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/xmlconfiguration.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/site/site.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/test/resources/META-INF/validation/order-constraints.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/test/resources/META-INF/validation/user-constraints.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/test/resources/META-INF/validation.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/test/resources/ValidationMessages_es.properties
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/test/resources/log4j.properties
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/test/suite/unit-tests.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-archetype/pom.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-archetype/src/main/resources/log4j.properties
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-legacy/pom.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/main/assembly/dist.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/main/docbook/en-US/master.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/main/docbook/en-US/modules/checkconstraints.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/main/docbook/en-US/modules/defineconstraints.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages.properties
___________________________________________________________________
Name: svn:keywords
- Author Date Id Revision
+ Date Revision Author Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_cs.properties
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_da.properties
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_de.properties
___________________________________________________________________
Name: svn:keywords
- Author Date Id Revision
+ Date Revision Author Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_en.properties
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_es.properties
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_fr.properties
___________________________________________________________________
Name: svn:keywords
- Author Date Id Revision
+ Date Revision Author Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_it.properties
___________________________________________________________________
Name: svn:keywords
- Author Date Id Revision
+ Date Revision Author Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_ja.properties
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_nl.properties
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_pt_BR.properties
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_sv.properties
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_zh_CN.properties
___________________________________________________________________
Name: svn:keywords
- Author Date Id Revision
+ Date Revision Author Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/main/resources/org/hibernate/validator/resources/DefaultValidatorMessages_zh_TW.properties
___________________________________________________________________
Name: svn:keywords
- Author Date Id Revision
+ Date Revision Author Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/test/resources/ValidatorMessages.properties
___________________________________________________________________
Name: svn:keywords
- Author Date Id Revision
+ Date Revision Author Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/test/resources/ValidatorMessages_da.properties
___________________________________________________________________
Name: svn:keywords
- Author Date Id Revision
+ Date Revision Author Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/test/resources/ValidatorMessages_fr.properties
___________________________________________________________________
Name: svn:keywords
- Author Date Id Revision
+ Date Revision Author Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/test/resources/hibernate.properties
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/test/resources/log4j.properties
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-legacy/src/test/resources/messages_en.properties
___________________________________________________________________
Name: svn:keywords
- Author Date Id Revision
+ Date Revision Author Id
Property changes on: validator/trunk/hibernate-validator-tck-runner/pom.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-tck-runner/src/jboss-as/build.properties
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-tck-runner/src/jboss-as/build.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-tck-runner/src/main/resources/META-INF/jboss-test-harness.properties
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-tck-runner/src/test/resources/jndi.properties
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-tck-runner/src/test/resources/log4j.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-tck-runner/src/test/resources/org/jboss/testharness/impl/packaging/jsr299/default/beans.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/pom.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/src/site/site.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/tck-utils/api/pom.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/tck-utils/impl/pom.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/tck-utils/pom.xml
___________________________________________________________________
Name: svn:keywords
+ Id
15 years, 7 months
Hibernate SVN: r16401 - in validator/trunk/hibernate-validator/src: test/java/org/hibernate/validation/engine and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-04-22 10:09:42 -0400 (Wed, 22 Apr 2009)
New Revision: 16401
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/ValidatorImpl.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java
Log:
HV-144
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-04-22 11:12:04 UTC (rev 16400)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ExecutionContext.java 2009-04-22 14:09:42 UTC (rev 16401)
@@ -54,6 +54,11 @@
private final T rootBean;
/**
+ * The root bean class of the validation.
+ */
+ private Class<T> rootBeanClass;
+
+ /**
* Maps a group to an identity set to keep track of already validated objects. We have to make sure
* that each object gets only validated once per group and property path.
*/
@@ -106,12 +111,36 @@
*/
private final TraversableResolver traversableResolver;
- public ExecutionContext(T object, MessageInterpolator messageInterpolator, ConstraintValidatorFactory constraintValidatorFactory, TraversableResolver traversableResolver) {
- this( object, object, messageInterpolator, constraintValidatorFactory, traversableResolver );
+ public static <T> ExecutionContext<T> getContextForValidate(T object, MessageInterpolator messageInterpolator, ConstraintValidatorFactory constraintValidatorFactory, TraversableResolver traversableResolver) {
+ @SuppressWarnings("unchecked")
+ Class<T> rootBeanClass = ( Class<T> ) object.getClass();
+ return new ExecutionContext<T>(
+ rootBeanClass, object, object, messageInterpolator, constraintValidatorFactory, traversableResolver
+ );
}
- public ExecutionContext(T rootBean, Object object, MessageInterpolator messageInterpolator, ConstraintValidatorFactory constraintValidatorFactory, TraversableResolver traversableResolver) {
+ public static <T> ExecutionContext<T> getContextForValidateValue(Class<T> rootBeanClass, Object object, MessageInterpolator messageInterpolator, ConstraintValidatorFactory constraintValidatorFactory, TraversableResolver traversableResolver) {
+ return new ExecutionContext<T>(
+ rootBeanClass,
+ null,
+ object,
+ messageInterpolator,
+ constraintValidatorFactory,
+ traversableResolver
+ );
+ }
+
+ public static <T> ExecutionContext<T> getContextForValidateProperty(T rootBean, Object object, MessageInterpolator messageInterpolator, ConstraintValidatorFactory constraintValidatorFactory, TraversableResolver traversableResolver) {
+ @SuppressWarnings("unchecked")
+ Class<T> rootBeanClass = ( Class<T> ) rootBean.getClass();
+ return new ExecutionContext<T>(
+ rootBeanClass, rootBean, object, messageInterpolator, constraintValidatorFactory, traversableResolver
+ );
+ }
+
+ private ExecutionContext(Class<T> rootBeanClass, T rootBean, Object object, MessageInterpolator messageInterpolator, ConstraintValidatorFactory constraintValidatorFactory, TraversableResolver traversableResolver) {
this.rootBean = rootBean;
+ this.rootBeanClass = rootBeanClass;
this.messageInterpolator = messageInterpolator;
this.constraintValidatorFactory = constraintValidatorFactory;
this.traversableResolver = traversableResolver;
@@ -147,6 +176,12 @@
return rootBean;
}
+ @SuppressWarnings("unchecked")
+ // safe case since rootBean is of type T!
+ public Class<T> getRootBeanClass() {
+ return rootBeanClass;
+ }
+
public Class<?> getCurrentGroup() {
return currentGroup;
}
@@ -283,7 +318,7 @@
return new ConstraintViolationImpl<T>(
messageTemplate,
interpolatedMessage,
- null, //FIXME get the rootBeanClass
+ getRootBeanClass(),
getRootBean(),
peekCurrentBean(),
value,
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-04-22 11:12:04 UTC (rev 16400)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java 2009-04-22 14:09:42 UTC (rev 16401)
@@ -103,7 +103,7 @@
}
GroupChain groupChain = determineGroupExecutionOrder( groups );
- ExecutionContext<T> context = new ExecutionContext<T>(
+ ExecutionContext<T> context = ExecutionContext.getContextForValidate(
object, messageInterpolator, constraintValidatorFactory, traversableResolver
);
@@ -399,7 +399,7 @@
for ( Class<?> groupClass : groupList ) {
for ( MetaConstraint<T, ?> metaConstraint : metaConstraints ) {
- ExecutionContext<T> context = new ExecutionContext<T>(
+ ExecutionContext<T> context = ExecutionContext.getContextForValidateProperty(
object,
hostingBeanInstance,
messageInterpolator,
@@ -434,6 +434,7 @@
while ( groupIterator.hasNext() ) {
Group group = groupIterator.next();
validateValueForGroup(
+ beanType,
value,
propertyIter,
failingConstraintViolations,
@@ -449,6 +450,7 @@
int numberOfConstraintViolations = failingConstraintViolations.size();
for ( Group group : sequence ) {
validateValueForGroup(
+ beanType,
value,
propertyIter,
failingConstraintViolations,
@@ -463,7 +465,7 @@
}
}
- private <T> void validateValueForGroup(Object value, PropertyIterator propertyIter, List<ConstraintViolation<T>> failingConstraintViolations, Set<MetaConstraint<T, ?>> metaConstraints, Group group) {
+ private <T> void validateValueForGroup(Class<T> beanType, Object value, PropertyIterator propertyIter, List<ConstraintViolation<T>> failingConstraintViolations, Set<MetaConstraint<T, ?>> metaConstraints, Group group) {
int numberOfConstraintViolations = failingConstraintViolations.size();
BeanMetaData<T> beanMetaData = getBeanMetaData( metaConstraints.iterator().next().getBeanClass() );
@@ -478,8 +480,8 @@
for ( Class<?> groupClass : groupList ) {
for ( MetaConstraint<T, ?> metaConstraint : metaConstraints ) {
- ExecutionContext<T> context = new ExecutionContext<T>(
- ( T ) value, messageInterpolator, constraintValidatorFactory, traversableResolver
+ ExecutionContext<T> context = ExecutionContext.getContextForValidateValue(
+ beanType, value, messageInterpolator, constraintValidatorFactory, traversableResolver
);
context.pushProperty( propertyIter.getOriginalProperty() );
context.setCurrentGroup( groupClass );
@@ -554,7 +556,7 @@
private <T> BeanMetaData<T> getBeanMetaData(Class<T> beanClass) {
BeanMetaDataImpl<T> metadata = beanMetaDataCache.getBeanMetaData( beanClass );
if ( metadata == null ) {
- metadata = new BeanMetaDataImpl<T>( beanClass, constraintHelper);
+ metadata = new BeanMetaDataImpl<T>( beanClass, constraintHelper );
beanMetaDataCache.addBeanMetaData( beanClass, metadata );
}
return metadata;
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java 2009-04-22 11:12:04 UTC (rev 16400)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java 2009-04-22 14:09:42 UTC (rev 16401)
@@ -266,10 +266,11 @@
assertEquals( constraintViolations.size(), 1, "Wrong number of constraints" );
assertEquals( "may not be null", constraintViolation.getMessage(), "Wrong message" );
assertEquals( constraintViolation.getRootBean(), null, "Wrong root entity" );
+ assertEquals( constraintViolation.getRootBeanClass(), Customer.class, "Wrong root bean class" );
assertEquals( constraintViolation.getInvalidValue(), null, "Wrong value" );
assertEquals( "orderList[0].orderNumber", constraintViolation.getPropertyPath(), "Wrong propertyName" );
- constraintViolations = validator.validateValue( Customer.class, "orderList[0].orderNumber", "1234" );
+ constraintViolations = validator.validateValue( Customer.class, "orderList[0].orderNumber", 1234 );
assertEquals( constraintViolations.size(), 0, "Wrong number of constraints" );
}
15 years, 7 months
Hibernate SVN: r16400 - core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/schemaupdate.
by hibernate-commits@lists.jboss.org
Author: jcosta(a)redhat.com
Date: 2009-04-22 07:12:04 -0400 (Wed, 22 Apr 2009)
New Revision: 16400
Modified:
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/schemaupdate/1_Version.hbm.xml
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/schemaupdate/2_Version.hbm.xml
Log:
HHH-3621 - Making the 1_Version.hbm.xml and 2_Version.hbm.xml in schemaupdate consistent. The only difference should be the extra column in 2_Version, to test the update of the schema. For Branch_3_3
Modified: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/schemaupdate/1_Version.hbm.xml
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/schemaupdate/1_Version.hbm.xml 2009-04-22 11:11:06 UTC (rev 16399)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/schemaupdate/1_Version.hbm.xml 2009-04-22 11:12:04 UTC (rev 16400)
@@ -14,6 +14,6 @@
</id>
<property name="description"/>
</class>
-
+
</hibernate-mapping>
Modified: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/schemaupdate/2_Version.hbm.xml
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/schemaupdate/2_Version.hbm.xml 2009-04-22 11:11:06 UTC (rev 16399)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/schemaupdate/2_Version.hbm.xml 2009-04-22 11:12:04 UTC (rev 16400)
@@ -5,11 +5,10 @@
<hibernate-mapping package="org.hibernate.test.schemaupdate">
- <class name="Version" schema="PUBLIC">
+ <class name="Version">
<id name="id">
<generator class="org.hibernate.id.TableHiLoGenerator">
<param name="table">uid_table</param>
-<!-- <param name="schema">PUBLIC</param> -->
<param name="column">next_hi_value_column</param>
</generator>
</id>
15 years, 7 months
Hibernate SVN: r16399 - core/branches/Branch_3_2_4_SP1_CP/test/org/hibernate/test/schemaupdate.
by hibernate-commits@lists.jboss.org
Author: jcosta(a)redhat.com
Date: 2009-04-22 07:11:06 -0400 (Wed, 22 Apr 2009)
New Revision: 16399
Modified:
core/branches/Branch_3_2_4_SP1_CP/test/org/hibernate/test/schemaupdate/1_Version.hbm.xml
core/branches/Branch_3_2_4_SP1_CP/test/org/hibernate/test/schemaupdate/2_Version.hbm.xml
Log:
HHH-3621 - Making the 1_Version.hbm.xml and 2_Version.hbm.xml in schemaupdate consistent. The only difference should be the extra column in 2_Version, to test the update of the schema. For Branch_3_2_4_SP1_CP
Modified: core/branches/Branch_3_2_4_SP1_CP/test/org/hibernate/test/schemaupdate/1_Version.hbm.xml
===================================================================
--- core/branches/Branch_3_2_4_SP1_CP/test/org/hibernate/test/schemaupdate/1_Version.hbm.xml 2009-04-22 11:10:48 UTC (rev 16398)
+++ core/branches/Branch_3_2_4_SP1_CP/test/org/hibernate/test/schemaupdate/1_Version.hbm.xml 2009-04-22 11:11:06 UTC (rev 16399)
@@ -14,6 +14,6 @@
</id>
<property name="description"/>
</class>
-
+
</hibernate-mapping>
Modified: core/branches/Branch_3_2_4_SP1_CP/test/org/hibernate/test/schemaupdate/2_Version.hbm.xml
===================================================================
--- core/branches/Branch_3_2_4_SP1_CP/test/org/hibernate/test/schemaupdate/2_Version.hbm.xml 2009-04-22 11:10:48 UTC (rev 16398)
+++ core/branches/Branch_3_2_4_SP1_CP/test/org/hibernate/test/schemaupdate/2_Version.hbm.xml 2009-04-22 11:11:06 UTC (rev 16399)
@@ -5,11 +5,10 @@
<hibernate-mapping package="org.hibernate.test.schemaupdate">
- <class name="Version" schema="PUBLIC">
+ <class name="Version">
<id name="id">
<generator class="org.hibernate.id.TableHiLoGenerator">
<param name="table">uid_table</param>
-<!-- <param name="schema">PUBLIC</param> -->
<param name="column">next_hi_value_column</param>
</generator>
</id>
15 years, 7 months
Hibernate SVN: r16398 - core/branches/Branch_3_2/test/org/hibernate/test/schemaupdate.
by hibernate-commits@lists.jboss.org
Author: jcosta(a)redhat.com
Date: 2009-04-22 07:10:48 -0400 (Wed, 22 Apr 2009)
New Revision: 16398
Modified:
core/branches/Branch_3_2/test/org/hibernate/test/schemaupdate/1_Version.hbm.xml
core/branches/Branch_3_2/test/org/hibernate/test/schemaupdate/2_Version.hbm.xml
Log:
HHH-3621 - Making the 1_Version.hbm.xml and 2_Version.hbm.xml in schemaupdate consistent. The only difference should be the extra column in 2_Version, to test the update of the schema. For Branch_3_2
Modified: core/branches/Branch_3_2/test/org/hibernate/test/schemaupdate/1_Version.hbm.xml
===================================================================
--- core/branches/Branch_3_2/test/org/hibernate/test/schemaupdate/1_Version.hbm.xml 2009-04-22 11:09:22 UTC (rev 16397)
+++ core/branches/Branch_3_2/test/org/hibernate/test/schemaupdate/1_Version.hbm.xml 2009-04-22 11:10:48 UTC (rev 16398)
@@ -14,6 +14,6 @@
</id>
<property name="description"/>
</class>
-
+
</hibernate-mapping>
Modified: core/branches/Branch_3_2/test/org/hibernate/test/schemaupdate/2_Version.hbm.xml
===================================================================
--- core/branches/Branch_3_2/test/org/hibernate/test/schemaupdate/2_Version.hbm.xml 2009-04-22 11:09:22 UTC (rev 16397)
+++ core/branches/Branch_3_2/test/org/hibernate/test/schemaupdate/2_Version.hbm.xml 2009-04-22 11:10:48 UTC (rev 16398)
@@ -5,11 +5,10 @@
<hibernate-mapping package="org.hibernate.test.schemaupdate">
- <class name="Version" schema="PUBLIC">
+ <class name="Version">
<id name="id">
<generator class="org.hibernate.id.TableHiLoGenerator">
<param name="table">uid_table</param>
-<!-- <param name="schema">PUBLIC</param> -->
<param name="column">next_hi_value_column</param>
</generator>
</id>
15 years, 7 months
Hibernate SVN: r16397 - core/trunk/testsuite/src/test/resources.
by hibernate-commits@lists.jboss.org
Author: jcosta(a)redhat.com
Date: 2009-04-22 07:09:22 -0400 (Wed, 22 Apr 2009)
New Revision: 16397
Modified:
core/trunk/testsuite/src/test/resources/hibernate.properties
core/trunk/testsuite/src/test/resources/log4j.properties
Log:
HHH-3621 - Reverting the log4j.properties and hibernate.properties, which insisted in going with the other changes, in the previous commit.
Modified: core/trunk/testsuite/src/test/resources/hibernate.properties
===================================================================
--- core/trunk/testsuite/src/test/resources/hibernate.properties 2009-04-22 11:02:22 UTC (rev 16396)
+++ core/trunk/testsuite/src/test/resources/hibernate.properties 2009-04-22 11:09:22 UTC (rev 16397)
@@ -1,18 +1,31 @@
-##�Database specific
-hibernate.dialect org.hibernate.dialect.Oracle10gDialect
-hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver
-hibernate.connection.url jdbc:oracle:thin:@dev01.qa.atl.jboss.com:1521:qadb01
-hibernate.connection.username hibernate
-hibernate.connection.password hibernate
-hibernate.default_schema hibernate
+################################################################################
+# Copyright (c) 2007, Red Hat Middleware, LLC. All rights reserved. #
+# #
+# This copyrighted material is made available to anyone wishing to use, modify,#
+# copy, or redistribute it subject to the terms and conditions of the GNU #
+# Lesser General Public License, v. 2.1. This program is distributed in the #
+# hope that it will be useful, but WITHOUT A WARRANTY; without even the implied#
+# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU #
+# Lesser General Public License for more details. You should have received a #
+# copy of the GNU Lesser General Public License, v.2.1 along with this #
+# distribution; if not, write to the Free Software Foundation, Inc., #
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. #
+# #
+# Red Hat Author(s): Steve Ebersole #
+################################################################################
+hibernate.dialect ${db.dialect}
+hibernate.connection.driver_class ${jdbc.driver}
+hibernate.connection.url ${jdbc.url}
+hibernate.connection.username ${jdbc.user}
+hibernate.connection.password ${jdbc.pass}
+hibernate.connection.isolation ${jdbc.isolation}
-##�Extra options from original hibernate.properties
-hibernate.jdbc.batch_versioned_data false
-hibernate.jdbc.use_streams_for_binary true
+hibernate.connection.pool_size 5
-## options for cleandb
-driver=oracle.jdbc.driver.OracleDriver
-url=jdbc:oracle:thin:@dev01.qa.atl.jboss.com:1521:qadb01
-username=hibernate
-password=hibernate
-schema=HIBERNATE
+hibernate.show_sql true
+hibernate.format_sql true
+
+hibernate.max_fetch_depth 5
+
+hibernate.cache.region_prefix hibernate.test
+hibernate.cache.provider_class org.hibernate.cache.HashtableCacheProvider
Modified: core/trunk/testsuite/src/test/resources/log4j.properties
===================================================================
--- core/trunk/testsuite/src/test/resources/log4j.properties 2009-04-22 11:02:22 UTC (rev 16396)
+++ core/trunk/testsuite/src/test/resources/log4j.properties 2009-04-22 11:09:22 UTC (rev 16397)
@@ -1,54 +1,10 @@
-### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
-### direct messages to file hibernate.log ###
-log4j.appender.file=org.apache.log4j.FileAppender
-log4j.appender.file.File=hibernate.log
-log4j.appender.file.layout=org.apache.log4j.PatternLayout
-log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
-### direct messages to socket - chainsaw ###
-log4j.appender.socket=org.apache.log4j.net.SocketAppender
-log4j.appender.socket.remoteHost=localhost
-log4j.appender.socket.port=4560
-log4j.appender.socket.locationInfo=true
+log4j.rootLogger=info, stdout
-### set log levels - for more verbose logging change 'info' to 'debug' ###
-
-log4j.rootLogger=warn, stdout
-
-log4j.logger.org.hibernate=debug
-#log4j.logger.org.hibernate=debug
-
-log4j.logger.org.hibernate.ejb=debug
-log4j.logger.org.hibernate.ejb.packaging=debug
-log4j.logger.org.hibernate.reflection=debug
-
-#log4j.logger.org.hibernate.engine.Cascades=debug
-#log4j.logger.org.hibernate.hql=debug
-
-### log just the SQL
-log4j.logger.org.hibernate.SQL=debug
-
-### log JDBC bind parameters ###
-#log4j.logger.org.hibernate.type=info
-log4j.logger.org.hibernate.type=debug
-
-### log schema export/update ###
+log4j.logger.org.hibernate.test=info
log4j.logger.org.hibernate.tool.hbm2ddl=debug
-
-### log HQL parse trees
-#log4j.logger.org.hibernate.hql=debug
-
-### log cache activity ###
-#log4j.logger.org.hibernate.cache=debug
-
-### log JDBC resource acquisition
-#log4j.logger.org.hibernate.jdbc=debug
-
-### enable the following line if you want to track down connection ###
-### leakages when using DriverManagerConnectionProvider ###
-#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
15 years, 7 months
Hibernate SVN: r16396 - in core/trunk/testsuite/src/test: resources and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: jcosta(a)redhat.com
Date: 2009-04-22 07:02:22 -0400 (Wed, 22 Apr 2009)
New Revision: 16396
Modified:
core/trunk/testsuite/src/test/java/org/hibernate/test/schemaupdate/1_Version.hbm.xml
core/trunk/testsuite/src/test/java/org/hibernate/test/schemaupdate/2_Version.hbm.xml
core/trunk/testsuite/src/test/resources/hibernate.properties
core/trunk/testsuite/src/test/resources/log4j.properties
Log:
HHH-3621 - Making the 1_Version.hbm.xml and 2_Version.hbm.xml in schemaupdate consistent. The only difference should be the extra column in 2_Version, to test the update of the schema.
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/schemaupdate/1_Version.hbm.xml
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/schemaupdate/1_Version.hbm.xml 2009-04-22 10:59:38 UTC (rev 16395)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/schemaupdate/1_Version.hbm.xml 2009-04-22 11:02:22 UTC (rev 16396)
@@ -14,6 +14,6 @@
</id>
<property name="description"/>
</class>
-
+
</hibernate-mapping>
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/schemaupdate/2_Version.hbm.xml
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/schemaupdate/2_Version.hbm.xml 2009-04-22 10:59:38 UTC (rev 16395)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/schemaupdate/2_Version.hbm.xml 2009-04-22 11:02:22 UTC (rev 16396)
@@ -5,11 +5,10 @@
<hibernate-mapping package="org.hibernate.test.schemaupdate">
- <class name="Version" schema="PUBLIC">
+ <class name="Version">
<id name="id">
<generator class="org.hibernate.id.TableHiLoGenerator">
<param name="table">uid_table</param>
-<!-- <param name="schema">PUBLIC</param> -->
<param name="column">next_hi_value_column</param>
</generator>
</id>
Modified: core/trunk/testsuite/src/test/resources/hibernate.properties
===================================================================
--- core/trunk/testsuite/src/test/resources/hibernate.properties 2009-04-22 10:59:38 UTC (rev 16395)
+++ core/trunk/testsuite/src/test/resources/hibernate.properties 2009-04-22 11:02:22 UTC (rev 16396)
@@ -1,31 +1,18 @@
-################################################################################
-# Copyright (c) 2007, Red Hat Middleware, LLC. All rights reserved. #
-# #
-# This copyrighted material is made available to anyone wishing to use, modify,#
-# copy, or redistribute it subject to the terms and conditions of the GNU #
-# Lesser General Public License, v. 2.1. This program is distributed in the #
-# hope that it will be useful, but WITHOUT A WARRANTY; without even the implied#
-# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU #
-# Lesser General Public License for more details. You should have received a #
-# copy of the GNU Lesser General Public License, v.2.1 along with this #
-# distribution; if not, write to the Free Software Foundation, Inc., #
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. #
-# #
-# Red Hat Author(s): Steve Ebersole #
-################################################################################
-hibernate.dialect ${db.dialect}
-hibernate.connection.driver_class ${jdbc.driver}
-hibernate.connection.url ${jdbc.url}
-hibernate.connection.username ${jdbc.user}
-hibernate.connection.password ${jdbc.pass}
-hibernate.connection.isolation ${jdbc.isolation}
+##�Database specific
+hibernate.dialect org.hibernate.dialect.Oracle10gDialect
+hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver
+hibernate.connection.url jdbc:oracle:thin:@dev01.qa.atl.jboss.com:1521:qadb01
+hibernate.connection.username hibernate
+hibernate.connection.password hibernate
+hibernate.default_schema hibernate
-hibernate.connection.pool_size 5
+##�Extra options from original hibernate.properties
+hibernate.jdbc.batch_versioned_data false
+hibernate.jdbc.use_streams_for_binary true
-hibernate.show_sql true
-hibernate.format_sql true
-
-hibernate.max_fetch_depth 5
-
-hibernate.cache.region_prefix hibernate.test
-hibernate.cache.provider_class org.hibernate.cache.HashtableCacheProvider
+## options for cleandb
+driver=oracle.jdbc.driver.OracleDriver
+url=jdbc:oracle:thin:@dev01.qa.atl.jboss.com:1521:qadb01
+username=hibernate
+password=hibernate
+schema=HIBERNATE
Modified: core/trunk/testsuite/src/test/resources/log4j.properties
===================================================================
--- core/trunk/testsuite/src/test/resources/log4j.properties 2009-04-22 10:59:38 UTC (rev 16395)
+++ core/trunk/testsuite/src/test/resources/log4j.properties 2009-04-22 11:02:22 UTC (rev 16396)
@@ -1,3 +1,4 @@
+### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
@@ -3,7 +4,50 @@
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
+### direct messages to file hibernate.log ###
+log4j.appender.file=org.apache.log4j.FileAppender
+log4j.appender.file.File=hibernate.log
+log4j.appender.file.layout=org.apache.log4j.PatternLayout
+log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
-log4j.rootLogger=info, stdout
+### direct messages to socket - chainsaw ###
+log4j.appender.socket=org.apache.log4j.net.SocketAppender
+log4j.appender.socket.remoteHost=localhost
+log4j.appender.socket.port=4560
+log4j.appender.socket.locationInfo=true
-log4j.logger.org.hibernate.test=info
+### set log levels - for more verbose logging change 'info' to 'debug' ###
+
+log4j.rootLogger=warn, stdout
+
+log4j.logger.org.hibernate=debug
+#log4j.logger.org.hibernate=debug
+
+log4j.logger.org.hibernate.ejb=debug
+log4j.logger.org.hibernate.ejb.packaging=debug
+log4j.logger.org.hibernate.reflection=debug
+
+#log4j.logger.org.hibernate.engine.Cascades=debug
+#log4j.logger.org.hibernate.hql=debug
+
+### log just the SQL
+log4j.logger.org.hibernate.SQL=debug
+
+### log JDBC bind parameters ###
+#log4j.logger.org.hibernate.type=info
+log4j.logger.org.hibernate.type=debug
+
+### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=debug
+
+### log HQL parse trees
+#log4j.logger.org.hibernate.hql=debug
+
+### log cache activity ###
+#log4j.logger.org.hibernate.cache=debug
+
+### log JDBC resource acquisition
+#log4j.logger.org.hibernate.jdbc=debug
+
+### enable the following line if you want to track down connection ###
+### leakages when using DriverManagerConnectionProvider ###
+#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
15 years, 7 months
Hibernate SVN: r16395 - in validator/trunk: hibernate-validator/src/main/java/org/hibernate/validation/engine and 5 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-04-22 06:59:38 -0400 (Wed, 22 Apr 2009)
New Revision: 16395
Added:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.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/metadata/
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/AnnotationIgnores.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/ValidationBootstrapParameters.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/ValidationXmlParser.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/XmlMappingParser.java
Removed:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/AnnotationIgnores.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/MetaConstraint.java
Modified:
validator/trunk/hibernate-validator-archetype/src/main/java/org/hibernate/validator/quickstart/Car.java
validator/trunk/hibernate-validator-archetype/src/test/java/org/hibernate/validator/quickstart/CarTest.java
validator/trunk/hibernate-validator-tck-runner/src/main/java/org/hibernate/validation/test/StandaloneContainersImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/HibernateValidationProvider.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/ConfigurationImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/DefaultValidationProviderResolver.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/MessageInterpolatorContext.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/xml/Optional.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/xml/TestGroup.java
Log:
HV-142
Extracted the xml parsing code
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/HibernateValidationProvider.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/HibernateValidationProvider.java 2009-04-22 09:02:56 UTC (rev 16394)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/HibernateValidationProvider.java 2009-04-22 10:59:38 UTC (rev 16395)
@@ -24,8 +24,8 @@
import javax.validation.spi.ConfigurationState;
import javax.validation.spi.ValidationProvider;
+import org.hibernate.validation.engine.ConfigurationImpl;
import org.hibernate.validation.engine.HibernateValidatorConfiguration;
-import org.hibernate.validation.engine.ConfigurationImpl;
import org.hibernate.validation.engine.ValidatorFactoryImpl;
/**
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/AnnotationIgnores.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/AnnotationIgnores.java 2009-04-22 09:02:56 UTC (rev 16394)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/AnnotationIgnores.java 2009-04-22 10:59:38 UTC (rev 16395)
@@ -1,119 +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.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;
- }
-}
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataCache.java
___________________________________________________________________
Name: svn:keywords
+ Id
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-04-22 09:02:56 UTC (rev 16394)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataImpl.java 2009-04-22 10:59:38 UTC (rev 16395)
@@ -39,6 +39,7 @@
import org.slf4j.Logger;
+import org.hibernate.validation.engine.xml.AnnotationIgnores;
import org.hibernate.validation.util.LoggerFactory;
import org.hibernate.validation.util.ReflectionHelper;
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-04-22 09:02:56 UTC (rev 16394)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConfigurationImpl.java 2009-04-22 10:59:38 UTC (rev 16395)
@@ -18,13 +18,9 @@
package org.hibernate.validation.engine;
import java.io.InputStream;
-import java.net.URL;
-import java.util.HashMap;
-import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
-import javax.validation.Configuration;
import javax.validation.ConstraintValidatorFactory;
import javax.validation.MessageInterpolator;
import javax.validation.TraversableResolver;
@@ -34,23 +30,14 @@
import javax.validation.spi.BootstrapState;
import javax.validation.spi.ConfigurationState;
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.engine.resolver.DefaultTraversableResolver;
+import org.hibernate.validation.engine.xml.ValidationBootstrapParameters;
+import org.hibernate.validation.engine.xml.ValidationXmlParser;
import org.hibernate.validation.util.LoggerFactory;
-import org.hibernate.validation.util.ReflectionHelper;
import org.hibernate.validation.util.Version;
-import org.hibernate.validation.xml.PropertyType;
-import org.hibernate.validation.xml.ValidationConfigType;
/**
* Hibernate specific <code>Configuration</code> implementation.
@@ -65,15 +52,13 @@
}
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";
private final MessageInterpolator defaultMessageInterpolator = new ResourceBundleMessageInterpolator();
private final TraversableResolver defaultTraversableResolver = new DefaultTraversableResolver();
private final ConstraintValidatorFactory defaultValidatorFactory = new ConstraintValidatorFactoryImpl();
private final ValidationProviderResolver providerResolver;
- private ParameterHolder parameterHolder;
+ private ValidationBootstrapParameters validationBootstrapParameters;
private boolean ignoreXmlConfiguration = false;
public ConfigurationImpl(BootstrapState state) {
@@ -83,7 +68,7 @@
else {
this.providerResolver = state.getValidationProviderResolver();
}
- parameterHolder = new ParameterHolder();
+ validationBootstrapParameters = new ValidationBootstrapParameters();
}
public ConfigurationImpl(ValidationProvider provider) {
@@ -91,8 +76,8 @@
throw new ValidationException( "Assertion error: inconsistent ConfigurationImpl construction" );
}
this.providerResolver = null;
- parameterHolder = new ParameterHolder();
- parameterHolder.provider = provider;
+ validationBootstrapParameters = new ValidationBootstrapParameters();
+ validationBootstrapParameters.provider = provider;
}
public HibernateValidatorConfiguration ignoreXmlConfiguration() {
@@ -101,28 +86,28 @@
}
public ConfigurationImpl messageInterpolator(MessageInterpolator interpolator) {
- this.parameterHolder.messageInterpolator = interpolator;
+ this.validationBootstrapParameters.messageInterpolator = interpolator;
return this;
}
public ConfigurationImpl traversableResolver(TraversableResolver resolver) {
- this.parameterHolder.traversableResolver = resolver;
+ this.validationBootstrapParameters.traversableResolver = resolver;
return this;
}
public ConfigurationImpl constraintValidatorFactory(ConstraintValidatorFactory constraintValidatorFactory) {
- this.parameterHolder.constraintValidatorFactory = constraintValidatorFactory;
+ this.validationBootstrapParameters.constraintValidatorFactory = constraintValidatorFactory;
return this;
}
public HibernateValidatorConfiguration addMapping(InputStream stream) {
- parameterHolder.mappings.add( stream );
+ validationBootstrapParameters.mappings.add( stream );
return this;
}
public HibernateValidatorConfiguration addProperty(String name, String value) {
if ( value != null ) {
- parameterHolder.configProperties.put( name, value );
+ validationBootstrapParameters.configProperties.put( name, value );
}
return this;
}
@@ -131,18 +116,18 @@
parseValidationXml();
ValidatorFactory factory = null;
if ( isSpecificProvider() ) {
- factory = parameterHolder.provider.buildValidatorFactory( this );
+ factory = validationBootstrapParameters.provider.buildValidatorFactory( this );
}
else {
- if ( parameterHolder.providerClass != null ) {
+ if ( validationBootstrapParameters.providerClass != null ) {
for ( ValidationProvider provider : providerResolver.getValidationProviders() ) {
- if ( provider.isSuitable( parameterHolder.providerClass ) ) {
+ if ( provider.isSuitable( validationBootstrapParameters.providerClass ) ) {
factory = provider.buildValidatorFactory( this );
break;
}
}
if ( factory == null ) {
- throw new ValidationException( "Unable to find provider: " + parameterHolder.providerClass );
+ throw new ValidationException( "Unable to find provider: " + validationBootstrapParameters.providerClass );
}
}
else {
@@ -153,7 +138,7 @@
}
// reset the param holder
- parameterHolder = new ParameterHolder();
+ validationBootstrapParameters = new ValidationBootstrapParameters();
return factory;
}
@@ -162,23 +147,23 @@
}
public MessageInterpolator getMessageInterpolator() {
- return parameterHolder.messageInterpolator;
+ return validationBootstrapParameters.messageInterpolator;
}
public Set<InputStream> getMappingStreams() {
- return parameterHolder.mappings;
+ return validationBootstrapParameters.mappings;
}
public ConstraintValidatorFactory getConstraintValidatorFactory() {
- return parameterHolder.constraintValidatorFactory;
+ return validationBootstrapParameters.constraintValidatorFactory;
}
public TraversableResolver getTraversableResolver() {
- return parameterHolder.traversableResolver;
+ return validationBootstrapParameters.traversableResolver;
}
public Map<String, String> getProperties() {
- return parameterHolder.configProperties;
+ return validationBootstrapParameters.configProperties;
}
public MessageInterpolator getDefaultMessageInterpolator() {
@@ -186,7 +171,7 @@
}
private boolean isSpecificProvider() {
- return parameterHolder.provider != null;
+ return validationBootstrapParameters.provider != null;
}
/**
@@ -198,244 +183,46 @@
return;
}
- ValidationConfigType config = getValidationConfig();
- ParameterHolder xmlParameters = new ParameterHolder();
- 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 );
- }
+ ValidationBootstrapParameters xmlParameters = new ValidationXmlParser().parseValidationXml();
applyXmlSettings( xmlParameters );
}
- private void applyXmlSettings(ParameterHolder xmlParameters) {
- parameterHolder.providerClass = xmlParameters.providerClass;
+ private void applyXmlSettings(ValidationBootstrapParameters xmlParameters) {
+ validationBootstrapParameters.providerClass = xmlParameters.providerClass;
- if ( parameterHolder.messageInterpolator == null ) {
+ if ( validationBootstrapParameters.messageInterpolator == null ) {
if ( xmlParameters.messageInterpolator != null ) {
- parameterHolder.messageInterpolator = xmlParameters.messageInterpolator;
+ validationBootstrapParameters.messageInterpolator = xmlParameters.messageInterpolator;
}
else {
- parameterHolder.messageInterpolator = defaultMessageInterpolator;
+ validationBootstrapParameters.messageInterpolator = defaultMessageInterpolator;
}
}
- if ( parameterHolder.traversableResolver == null ) {
+ if ( validationBootstrapParameters.traversableResolver == null ) {
if ( xmlParameters.traversableResolver != null ) {
- parameterHolder.traversableResolver = xmlParameters.traversableResolver;
+ validationBootstrapParameters.traversableResolver = xmlParameters.traversableResolver;
}
else {
- parameterHolder.traversableResolver = defaultTraversableResolver;
+ validationBootstrapParameters.traversableResolver = defaultTraversableResolver;
}
}
- if ( parameterHolder.constraintValidatorFactory == null ) {
+ if ( validationBootstrapParameters.constraintValidatorFactory == null ) {
if ( xmlParameters.constraintValidatorFactory != null ) {
- parameterHolder.constraintValidatorFactory = xmlParameters.constraintValidatorFactory;
+ validationBootstrapParameters.constraintValidatorFactory = xmlParameters.constraintValidatorFactory;
}
else {
- parameterHolder.constraintValidatorFactory = defaultValidatorFactory;
+ validationBootstrapParameters.constraintValidatorFactory = defaultValidatorFactory;
}
}
- parameterHolder.mappings.addAll( xmlParameters.mappings );
+ validationBootstrapParameters.mappings.addAll( xmlParameters.mappings );
for ( Map.Entry<String, String> entry : xmlParameters.configProperties.entrySet() ) {
- if ( parameterHolder.configProperties.get( entry.getKey() ) == null ) {
- parameterHolder.configProperties.put( entry.getKey(), entry.getValue() );
+ if ( validationBootstrapParameters.configProperties.get( entry.getKey() ) == null ) {
+ validationBootstrapParameters.configProperties.put( entry.getKey(), entry.getValue() );
}
}
}
-
- private void setConstraintFactoryFromXml(ValidationConfigType config, ParameterHolder 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, ParameterHolder 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, ParameterHolder xmlParameters) {
- for ( String mappingFileName : config.getConstraintMapping() ) {
- if ( log.isDebugEnabled() ) {
- log.debug(
- "Trying to open input stream for {}.", mappingFileName
- );
- InputStream in = getInputStreamForPath( mappingFileName );
- if ( in == null ) {
- throw new ValidationException( "Unable to open input stream for mapping file " + mappingFileName + "." );
- }
- xmlParameters.mappings.add( in );
- }
- }
- }
-
- private void setMessageInterpolatorFromXml(ValidationConfigType config, ParameterHolder 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, ParameterHolder 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, ParameterHolder xmlParamters) {
- String providerClassName = config.getDefaultProvider();
- if ( providerClassName != null ) {
- try {
- xmlParamters.providerClass = ( Class<? extends Configuration<?>> ) 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 = null;
- 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() );
- }
- return validationConfig;
- }
-
- private InputStream getInputStreamForPath(String path) {
- InputStream inputStream = this.getClass().getResourceAsStream( path );
- // try absolute path
- if ( inputStream == null && !path.startsWith( "/" ) ) {
- 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;
- }
-
- private static class ParameterHolder {
- ConstraintValidatorFactory constraintValidatorFactory;
- MessageInterpolator messageInterpolator;
- TraversableResolver traversableResolver;
- ValidationProvider provider;
- Class<? extends Configuration<?>> providerClass = null;
- final Map<String, String> configProperties = new HashMap<String, String>();
- final Set<InputStream> mappings = new HashSet<InputStream>();
- }
}
Deleted: 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-04-22 09:02:56 UTC (rev 16394)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java 2009-04-22 10:59:38 UTC (rev 16395)
@@ -1,252 +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.Array;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import javax.validation.ConstraintDescriptor;
-import javax.validation.ConstraintValidator;
-import javax.validation.ConstraintValidatorFactory;
-import javax.validation.UnexpectedTypeException;
-import javax.validation.ValidationException;
-import javax.validation.ConstraintViolation;
-
-import com.googlecode.jtype.TypeUtils;
-import org.slf4j.Logger;
-
-import org.hibernate.validation.util.LoggerFactory;
-import org.hibernate.validation.util.ValidatorTypeHelper;
-
-/**
- * Due to constraint conposition a single constraint annotation can lead to a whole constraint tree beeing validated.
- * This class encapsulates such a tree.
- *
- * @author Hardy Ferentschik
- */
-public class ConstraintTree<A extends Annotation> {
-
- private static final Logger log = LoggerFactory.make();
-
- private final ConstraintTree<?> parent;
- private final List<ConstraintTree<?>> children;
- private final ConstraintDescriptor<A> descriptor;
-
- public ConstraintTree(ConstraintDescriptor<A> descriptor) {
- this( descriptor, null );
- }
-
- private ConstraintTree(ConstraintDescriptor<A> descriptor, ConstraintTree<?> parent) {
- this.parent = parent;
- this.descriptor = descriptor;
- final Set<ConstraintDescriptor<?>> composingConstraints = descriptor.getComposingConstraints();
- children = new ArrayList<ConstraintTree<?>>( composingConstraints.size() );
-
- for ( ConstraintDescriptor<?> composingDescriptor : composingConstraints ) {
- ConstraintTree<?> treeNode = createConstraintTree( composingDescriptor );
- children.add( treeNode );
- }
- }
-
- private <U extends Annotation> ConstraintTree<U> createConstraintTree(ConstraintDescriptor<U> composingDescriptor) {
- return new ConstraintTree<U>( composingDescriptor, this );
- }
-
- public boolean isRoot() {
- return parent == null;
- }
-
- public ConstraintTree getParent() {
- return parent;
- }
-
- public List<ConstraintTree<?>> getChildren() {
- return children;
- }
-
- public boolean hasChildren() {
- return children.size() > 0;
- }
-
- public ConstraintDescriptor<A> getDescriptor() {
- return descriptor;
- }
-
- /**
- * Validates the specified value.
- *
- * @param value The value to validate
- * @param type The type of the value determined from the type the annotation was placed on.
- * @param executionContext The current execution context.
- * @param constraintViolations List of constraint violation into which to accumulate all constraint violation as we traverse
- * this <code>ConstraintTree </code>.
- * @param <T> Type of the root bean for the current validation.
- * @param <V> Type of the value to be validated.
- */
- public <T, V> void validateConstraints(V value, Type type, ExecutionContext<T> executionContext, List<ConstraintViolation<T>> constraintViolations) {
- for ( ConstraintTree<?> tree : getChildren() ) {
- tree.validateConstraints( value, type, executionContext, constraintViolations );
- }
-
- if ( log.isTraceEnabled() ) {
- log.trace( "Validating value {} against constraint defined by {}", value, descriptor );
- }
- ConstraintValidator<A, V> validator = getInitalizedValidator(
- value, type, executionContext.getConstraintValidatorFactory()
- );
- ConstraintValidatorContextImpl constraintValidatorContext = new ConstraintValidatorContextImpl(
- executionContext.peekParentPath(), executionContext.peekProperty(), descriptor
- );
- if ( !validator.isValid( value, constraintValidatorContext ) ) {
- constraintViolations.addAll( executionContext.createConstraintViolations( value, constraintValidatorContext ) );
- }
- if ( reportAsSingleViolation() && constraintViolations.size() > 0 ) {
- constraintViolations.clear();
- final String message = ( String ) getParent().getDescriptor().getAttributes().get( "message" );
- final String property = executionContext.peekPropertyPath();
- ConstraintValidatorContextImpl.ErrorMessage error = constraintValidatorContext.new ErrorMessage( message, property );
- constraintViolations.add( executionContext.createConstraintViolation( value, error, descriptor ) );
- }
- }
-
- private boolean reportAsSingleViolation() {
- return getParent() != null
- && getParent().getDescriptor().isReportAsSingleViolation();
- }
-
- /**
- * @param value The value to be validated.
- * @param type The type of the value to be validated (the type of the member/class the constraint was placed on).
- * @param constraintFactory constraint factory used to instantiate the constraint validator.
- *
- * @return A initalized constraint validator matching the type of the value to be validated.
- */
- private <V> ConstraintValidator<A, V> getInitalizedValidator(V value, Type type, ConstraintValidatorFactory constraintFactory) {
- Class<? extends ConstraintValidator<?, ?>> validatorClass = findMatchingValidatorClass( value, type );
-
- @SuppressWarnings("unchecked")
- ConstraintValidator<A, V> constraintValidator = ( ConstraintValidator<A, V> ) constraintFactory.getInstance(
- validatorClass
- );
- initializeConstraint( descriptor, constraintValidator );
- return constraintValidator;
- }
-
- /**
- * Runs the validator resolution algorithm.
- *
- * @param value The value to be validated.
- * @param type The type of the value to be validated (the type of the member/class the constraint was placed on).
- *
- * @return The class of a matching validator.
- */
- private Class<? extends ConstraintValidator<?, ?>> findMatchingValidatorClass(Object value, Type type) {
- Map<Type, Class<? extends ConstraintValidator<?, ?>>> validatorsTypes =
- ValidatorTypeHelper.getValidatorsTypes( descriptor.getConstraintValidatorClasses() );
-
- List<Type> suitableTypes = new ArrayList<Type>();
- findSuitableValidatorTypes( type, validatorsTypes, suitableTypes );
- // TODO - do we really have to take the actual value into consideration here as well? Or is it enough to
- // work with the type the constraint was placed on?
- if ( value != null ) {
- findSuitableValidatorTypes( determineValueClass( value ), validatorsTypes, suitableTypes );
- }
-
- resolveAssignableTypes( suitableTypes );
- verifyResolveWasUnique( type, suitableTypes );
-
- return validatorsTypes.get( suitableTypes.get( 0 ) );
- }
-
- private Class determineValueClass(Object value) {
- Class valueClass = value.getClass();
- if ( valueClass.isArray() ) {
- valueClass = Array.class;
- }
- return valueClass;
- }
-
- private void verifyResolveWasUnique(Type valueClass, List<Type> assignableClasses) {
- if ( assignableClasses.size() == 0 ) {
- throw new UnexpectedTypeException( "No validator could be found for type: " + valueClass );
- }
- else if ( assignableClasses.size() > 1 ) {
- StringBuilder builder = new StringBuilder();
- builder.append( "There are multiple validators which could validate the type " );
- builder.append( valueClass );
- builder.append( ". The validator classes are: " );
- for ( Type clazz : assignableClasses ) {
- builder.append( clazz );
- builder.append( ", " );
- }
- builder.delete( builder.length() - 2, builder.length() );
- throw new UnexpectedTypeException( builder.toString() );
- }
- }
-
- private void findSuitableValidatorTypes(Type type, Map<Type, Class<? extends ConstraintValidator<?, ?>>> validatorsTypes, List<Type> suitableTypes) {
- for ( Type validatorType : validatorsTypes.keySet() ) {
- if ( TypeUtils.isAssignable( validatorType, type ) && !suitableTypes.contains( validatorType ) ) {
- suitableTypes.add( validatorType );
- }
- }
- }
-
- /**
- * Tries to reduce all assignable classes down to a single class.
- *
- * @param assignableTypes The set of all classes which are assignable to the class of the value to be validated and
- * which are handled by at least one of the validators for the specified constraint.
- */
- private void resolveAssignableTypes(List<Type> assignableTypes) {
- if ( assignableTypes.size() == 0 || assignableTypes.size() == 1 ) {
- return;
- }
-
- List<Type> typesToRemove = new ArrayList<Type>();
- do {
- typesToRemove.clear();
- Type type = assignableTypes.get( 0 );
- for ( int i = 1; i < assignableTypes.size(); i++ ) {
- if ( TypeUtils.isAssignable( type, assignableTypes.get( i ) ) ) {
- typesToRemove.add( type );
- }
- else if ( TypeUtils.isAssignable( assignableTypes.get( i ), type ) ) {
- typesToRemove.add( assignableTypes.get( i ) );
- }
- }
- assignableTypes.removeAll( typesToRemove );
- } while ( typesToRemove.size() > 0 );
- }
-
- private <V> void initializeConstraint
- (ConstraintDescriptor<A>
- descriptor, ConstraintValidator<A, V>
- constraintValidator) {
- try {
- constraintValidator.initialize( descriptor.getAnnotation() );
- }
- catch ( RuntimeException e ) {
- throw new ValidationException( "Unable to intialize " + constraintValidator.getClass().getName(), e );
- }
- }
-}
Added: 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 (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java 2009-04-22 10:59:38 UTC (rev 16395)
@@ -0,0 +1,252 @@
+// $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.Array;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.validation.ConstraintDescriptor;
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorFactory;
+import javax.validation.ConstraintViolation;
+import javax.validation.UnexpectedTypeException;
+import javax.validation.ValidationException;
+
+import com.googlecode.jtype.TypeUtils;
+import org.slf4j.Logger;
+
+import org.hibernate.validation.util.LoggerFactory;
+import org.hibernate.validation.util.ValidatorTypeHelper;
+
+/**
+ * Due to constraint conposition a single constraint annotation can lead to a whole constraint tree beeing validated.
+ * This class encapsulates such a tree.
+ *
+ * @author Hardy Ferentschik
+ */
+public class ConstraintTree<A extends Annotation> {
+
+ private static final Logger log = LoggerFactory.make();
+
+ private final ConstraintTree<?> parent;
+ private final List<ConstraintTree<?>> children;
+ private final ConstraintDescriptor<A> descriptor;
+
+ public ConstraintTree(ConstraintDescriptor<A> descriptor) {
+ this( descriptor, null );
+ }
+
+ private ConstraintTree(ConstraintDescriptor<A> descriptor, ConstraintTree<?> parent) {
+ this.parent = parent;
+ this.descriptor = descriptor;
+ final Set<ConstraintDescriptor<?>> composingConstraints = descriptor.getComposingConstraints();
+ children = new ArrayList<ConstraintTree<?>>( composingConstraints.size() );
+
+ for ( ConstraintDescriptor<?> composingDescriptor : composingConstraints ) {
+ ConstraintTree<?> treeNode = createConstraintTree( composingDescriptor );
+ children.add( treeNode );
+ }
+ }
+
+ private <U extends Annotation> ConstraintTree<U> createConstraintTree(ConstraintDescriptor<U> composingDescriptor) {
+ return new ConstraintTree<U>( composingDescriptor, this );
+ }
+
+ public boolean isRoot() {
+ return parent == null;
+ }
+
+ public ConstraintTree getParent() {
+ return parent;
+ }
+
+ public List<ConstraintTree<?>> getChildren() {
+ return children;
+ }
+
+ public boolean hasChildren() {
+ return children.size() > 0;
+ }
+
+ public ConstraintDescriptor<A> getDescriptor() {
+ return descriptor;
+ }
+
+ /**
+ * Validates the specified value.
+ *
+ * @param value The value to validate
+ * @param type The type of the value determined from the type the annotation was placed on.
+ * @param executionContext The current execution context.
+ * @param constraintViolations List of constraint violation into which to accumulate all constraint violation as we traverse
+ * this <code>ConstraintTree </code>.
+ * @param <T> Type of the root bean for the current validation.
+ * @param <V> Type of the value to be validated.
+ */
+ public <T, V> void validateConstraints(V value, Type type, ExecutionContext<T> executionContext, List<ConstraintViolation<T>> constraintViolations) {
+ for ( ConstraintTree<?> tree : getChildren() ) {
+ tree.validateConstraints( value, type, executionContext, constraintViolations );
+ }
+
+ if ( log.isTraceEnabled() ) {
+ log.trace( "Validating value {} against constraint defined by {}", value, descriptor );
+ }
+ ConstraintValidator<A, V> validator = getInitalizedValidator(
+ value, type, executionContext.getConstraintValidatorFactory()
+ );
+ ConstraintValidatorContextImpl constraintValidatorContext = new ConstraintValidatorContextImpl(
+ executionContext.peekParentPath(), executionContext.peekProperty(), descriptor
+ );
+ if ( !validator.isValid( value, constraintValidatorContext ) ) {
+ constraintViolations.addAll( executionContext.createConstraintViolations( value, constraintValidatorContext ) );
+ }
+ if ( reportAsSingleViolation() && constraintViolations.size() > 0 ) {
+ constraintViolations.clear();
+ final String message = ( String ) getParent().getDescriptor().getAttributes().get( "message" );
+ final String property = executionContext.peekPropertyPath();
+ ConstraintValidatorContextImpl.ErrorMessage error = constraintValidatorContext.new ErrorMessage( message, property );
+ constraintViolations.add( executionContext.createConstraintViolation( value, error, descriptor ) );
+ }
+ }
+
+ private boolean reportAsSingleViolation() {
+ return getParent() != null
+ && getParent().getDescriptor().isReportAsSingleViolation();
+ }
+
+ /**
+ * @param value The value to be validated.
+ * @param type The type of the value to be validated (the type of the member/class the constraint was placed on).
+ * @param constraintFactory constraint factory used to instantiate the constraint validator.
+ *
+ * @return A initalized constraint validator matching the type of the value to be validated.
+ */
+ private <V> ConstraintValidator<A, V> getInitalizedValidator(V value, Type type, ConstraintValidatorFactory constraintFactory) {
+ Class<? extends ConstraintValidator<?, ?>> validatorClass = findMatchingValidatorClass( value, type );
+
+ @SuppressWarnings("unchecked")
+ ConstraintValidator<A, V> constraintValidator = ( ConstraintValidator<A, V> ) constraintFactory.getInstance(
+ validatorClass
+ );
+ initializeConstraint( descriptor, constraintValidator );
+ return constraintValidator;
+ }
+
+ /**
+ * Runs the validator resolution algorithm.
+ *
+ * @param value The value to be validated.
+ * @param type The type of the value to be validated (the type of the member/class the constraint was placed on).
+ *
+ * @return The class of a matching validator.
+ */
+ private Class<? extends ConstraintValidator<?, ?>> findMatchingValidatorClass(Object value, Type type) {
+ Map<Type, Class<? extends ConstraintValidator<?, ?>>> validatorsTypes =
+ ValidatorTypeHelper.getValidatorsTypes( descriptor.getConstraintValidatorClasses() );
+
+ List<Type> suitableTypes = new ArrayList<Type>();
+ findSuitableValidatorTypes( type, validatorsTypes, suitableTypes );
+ // TODO - do we really have to take the actual value into consideration here as well? Or is it enough to
+ // work with the type the constraint was placed on?
+ if ( value != null ) {
+ findSuitableValidatorTypes( determineValueClass( value ), validatorsTypes, suitableTypes );
+ }
+
+ resolveAssignableTypes( suitableTypes );
+ verifyResolveWasUnique( type, suitableTypes );
+
+ return validatorsTypes.get( suitableTypes.get( 0 ) );
+ }
+
+ private Class determineValueClass(Object value) {
+ Class valueClass = value.getClass();
+ if ( valueClass.isArray() ) {
+ valueClass = Array.class;
+ }
+ return valueClass;
+ }
+
+ private void verifyResolveWasUnique(Type valueClass, List<Type> assignableClasses) {
+ if ( assignableClasses.size() == 0 ) {
+ throw new UnexpectedTypeException( "No validator could be found for type: " + valueClass );
+ }
+ else if ( assignableClasses.size() > 1 ) {
+ StringBuilder builder = new StringBuilder();
+ builder.append( "There are multiple validators which could validate the type " );
+ builder.append( valueClass );
+ builder.append( ". The validator classes are: " );
+ for ( Type clazz : assignableClasses ) {
+ builder.append( clazz );
+ builder.append( ", " );
+ }
+ builder.delete( builder.length() - 2, builder.length() );
+ throw new UnexpectedTypeException( builder.toString() );
+ }
+ }
+
+ private void findSuitableValidatorTypes(Type type, Map<Type, Class<? extends ConstraintValidator<?, ?>>> validatorsTypes, List<Type> suitableTypes) {
+ for ( Type validatorType : validatorsTypes.keySet() ) {
+ if ( TypeUtils.isAssignable( validatorType, type ) && !suitableTypes.contains( validatorType ) ) {
+ suitableTypes.add( validatorType );
+ }
+ }
+ }
+
+ /**
+ * Tries to reduce all assignable classes down to a single class.
+ *
+ * @param assignableTypes The set of all classes which are assignable to the class of the value to be validated and
+ * which are handled by at least one of the validators for the specified constraint.
+ */
+ private void resolveAssignableTypes(List<Type> assignableTypes) {
+ if ( assignableTypes.size() == 0 || assignableTypes.size() == 1 ) {
+ return;
+ }
+
+ List<Type> typesToRemove = new ArrayList<Type>();
+ do {
+ typesToRemove.clear();
+ Type type = assignableTypes.get( 0 );
+ for ( int i = 1; i < assignableTypes.size(); i++ ) {
+ if ( TypeUtils.isAssignable( type, assignableTypes.get( i ) ) ) {
+ typesToRemove.add( type );
+ }
+ else if ( TypeUtils.isAssignable( assignableTypes.get( i ), type ) ) {
+ typesToRemove.add( assignableTypes.get( i ) );
+ }
+ }
+ assignableTypes.removeAll( typesToRemove );
+ } while ( typesToRemove.size() > 0 );
+ }
+
+ private <V> void initializeConstraint
+ (ConstraintDescriptor<A>
+ descriptor, ConstraintValidator<A, V>
+ constraintValidator) {
+ try {
+ constraintValidator.initialize( descriptor.getAnnotation() );
+ }
+ catch ( RuntimeException e ) {
+ throw new ValidationException( "Unable to intialize " + constraintValidator.getClass().getName(), e );
+ }
+ }
+}
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/DefaultValidationProviderResolver.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/DefaultValidationProviderResolver.java 2009-04-22 09:02:56 UTC (rev 16394)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/DefaultValidationProviderResolver.java 2009-04-22 10:59:38 UTC (rev 16395)
@@ -1,17 +1,17 @@
package org.hibernate.validation.engine;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.net.URL;
-import java.io.InputStream;
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.io.IOException;
+import javax.validation.ValidationException;
import javax.validation.ValidationProviderResolver;
-import javax.validation.ValidationException;
import javax.validation.spi.ValidationProvider;
/**
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-04-22 09:02:56 UTC (rev 16394)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ExecutionContext.java 2009-04-22 10:59:38 UTC (rev 16395)
@@ -27,9 +27,9 @@
import java.util.Stack;
import javax.validation.ConstraintDescriptor;
import javax.validation.ConstraintValidatorFactory;
+import javax.validation.ConstraintViolation;
import javax.validation.MessageInterpolator;
import javax.validation.TraversableResolver;
-import javax.validation.ConstraintViolation;
import org.hibernate.validation.util.IdentitySet;
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MessageInterpolatorContext.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MessageInterpolatorContext.java 2009-04-22 09:02:56 UTC (rev 16394)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MessageInterpolatorContext.java 2009-04-22 10:59:38 UTC (rev 16395)
@@ -1,7 +1,7 @@
package org.hibernate.validation.engine;
+import javax.validation.ConstraintDescriptor;
import javax.validation.MessageInterpolator;
-import javax.validation.ConstraintDescriptor;
/**
* Takes mandatory elements in the constructor
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-04-22 09:02:56 UTC (rev 16394)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java 2009-04-22 10:59:38 UTC (rev 16395)
@@ -1,177 +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.Array;
-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.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).isArray()) {
- t = Array.class;
- }
- }
- }
- 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 );
- }
- }
- }
-}
Added: 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 (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java 2009-04-22 10:59:38 UTC (rev 16395)
@@ -0,0 +1,177 @@
+// $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.Array;
+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.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).isArray()) {
+ t = Array.class;
+ }
+ }
+ }
+ 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 );
+ }
+ }
+ }
+}
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-04-22 09:02:56 UTC (rev 16394)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorFactoryImpl.java 2009-04-22 10:59:38 UTC (rev 16395)
@@ -17,59 +17,21 @@
*/
package org.hibernate.validation.engine;
-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.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.ConstraintValidatorFactory;
import javax.validation.MessageInterpolator;
import javax.validation.TraversableResolver;
-import javax.validation.ValidationException;
import javax.validation.Validator;
import javax.validation.ValidatorContext;
import javax.validation.ValidatorFactory;
import javax.validation.spi.ConfigurationState;
-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.engine.xml.AnnotationIgnores;
+import org.hibernate.validation.engine.xml.XmlMappingParser;
-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;
-
/**
* Factory returning initialized <code>Validator</code> instances.
*
@@ -78,24 +40,12 @@
*/
public class ValidatorFactoryImpl implements ValidatorFactory {
- 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 MessageInterpolator messageInterpolator;
private final TraversableResolver traversableResolver;
private final ConstraintValidatorFactory constraintValidatorFactory;
private final ConstraintHelper constraintHelper;
private final BeanMetaDataCache beanMetaDataCache;
- private final Set<Class<?>> processedClasses = new HashSet<Class<?>>();
- 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 ValidatorFactoryImpl(ConfigurationState configurationState) {
this.messageInterpolator = configurationState.getMessageInterpolator();
this.constraintValidatorFactory = configurationState.getConstraintValidatorFactory();
@@ -103,13 +53,7 @@
this.constraintHelper = new ConstraintHelper();
this.beanMetaDataCache = new BeanMetaDataCache();
- 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<?>>>();
-
- parseMappingFiles( configurationState.getMappingStreams() );
- initBeanMetaData();
+ initBeanMetaData( configurationState.getMappingStreams() );
}
/**
@@ -139,504 +83,27 @@
);
}
- 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;
- }
+ private <T> void initBeanMetaData(Set<InputStream> mappingStreams) {
- private void parseMappingFiles(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() );
- }
- }
- }
- }
+ XmlMappingParser mappingParser = new XmlMappingParser( constraintHelper );
+ mappingParser.parse( mappingStreams );
- @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 ( String validatorClassName : validatedByType.getValue() ) {
- Class<? extends ConstraintValidator<?, ?>> validatorClass;
- try {
- validatorClass = ( Class<? extends ConstraintValidator<?, ?>> ) ReflectionHelper.classForName(
- validatorClassName,
- 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 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 List<Class<?>> createGroupSequence(GroupSequenceType groupSequenceType, String defaultPackage) {
- List<Class<?>> groupSequence = new ArrayList<Class<?>>();
- for ( String groupName : groupSequenceType.getValue() ) {
- Class<?> group = getClass( groupName, defaultPackage );
- groupSequence.add( group );
- }
- return groupSequence;
- }
-
- 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 <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, new Class[] { }, 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 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 <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 Class<?>[] getGroups(GroupsType groupsType, String defaultPackage) {
- if ( groupsType == null ) {
- return new Class[] { };
- }
-
- List<Class<?>> groupList = new ArrayList<Class<?>>();
- for ( String groupClass : groupsType.getValue() ) {
- groupList.add( getClass( groupClass, 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 <T> void initBeanMetaData() {
- for ( Class<?> beanClass : processedClasses ) {
+ AnnotationIgnores annotationIgnores = mappingParser.getAnnotationIgnores();
+ for ( Class<?> beanClass : mappingParser.getProcessedClasses() ) {
BeanMetaDataImpl<?> metaData = new BeanMetaDataImpl<T>(
( Class<T> ) beanClass, constraintHelper, annotationIgnores
);
- for ( MetaConstraint<?, ? extends Annotation> constraint : constraintMap.get( beanClass ) ) {
+ for ( MetaConstraint<?, ? extends Annotation> constraint : mappingParser.getConstraintMap()
+ .get( beanClass ) ) {
metaData.addMetaConstraint( constraint );
}
- for ( Member m : cascadedMembers.get( beanClass ) ) {
+ for ( Member m : mappingParser.getCascadedMembers().get( beanClass ) ) {
metaData.addCascadedMember( m );
}
- if ( defaultSequences.containsKey( beanClass ) ) {
- metaData.setDefaultGroupSequence( defaultSequences.get( beanClass ) );
+ if ( mappingParser.getDefaultSequences().containsKey( beanClass ) ) {
+ metaData.setDefaultGroupSequence( mappingParser.getDefaultSequences().get( beanClass ) );
}
beanMetaDataCache.addBeanMetaData( ( Class<T> ) beanClass, ( BeanMetaDataImpl<T> ) metaData );
}
}
-
- 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;
- }
}
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-04-22 09:02:56 UTC (rev 16394)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java 2009-04-22 10:59:38 UTC (rev 16395)
@@ -17,9 +17,9 @@
*/
package org.hibernate.validation.engine;
+import java.lang.annotation.Annotation;
import java.lang.reflect.Member;
import java.lang.reflect.Type;
-import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/AnnotationIgnores.java (from rev 16370, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/AnnotationIgnores.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/AnnotationIgnores.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/AnnotationIgnores.java 2009-04-22 10:59:38 UTC (rev 16395)
@@ -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.engine.xml;
+
+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;
+ }
+}
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/AnnotationIgnores.java
___________________________________________________________________
Name: svn:keywords
+ Id
Added: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/ValidationBootstrapParameters.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/ValidationBootstrapParameters.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/ValidationBootstrapParameters.java 2009-04-22 10:59:38 UTC (rev 16395)
@@ -0,0 +1,42 @@
+// $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.xml;
+
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import javax.validation.Configuration;
+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 Configuration<?>> providerClass = null;
+ public final Map<String, String> configProperties = new HashMap<String, String>();
+ public final Set<InputStream> mappings = new HashSet<InputStream>();
+}
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/ValidationBootstrapParameters.java
___________________________________________________________________
Name: svn:keywords
+ Id
Added: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/ValidationXmlParser.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/ValidationXmlParser.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/ValidationXmlParser.java 2009-04-22 10:59:38 UTC (rev 16395)
@@ -0,0 +1,252 @@
+// $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.xml;
+
+import java.io.InputStream;
+import java.net.URL;
+import javax.validation.Configuration;
+import javax.validation.ConstraintValidatorFactory;
+import javax.validation.MessageInterpolator;
+import javax.validation.TraversableResolver;
+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.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 ( String mappingFileName : config.getConstraintMapping() ) {
+ if ( log.isDebugEnabled() ) {
+ log.debug(
+ "Trying to open input stream for {}.", mappingFileName
+ );
+ InputStream in = getInputStreamForPath( mappingFileName );
+ if ( in == null ) {
+ throw new ValidationException( "Unable to open input stream for mapping file " + mappingFileName + "." );
+ }
+ 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 Configuration<?>> ) 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 = null;
+ 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() );
+ }
+ return validationConfig;
+ }
+
+ private InputStream getInputStreamForPath(String path) {
+ InputStream inputStream = this.getClass().getResourceAsStream( path );
+ // try absolute path
+ if ( inputStream == null && !path.startsWith( "/" ) ) {
+ 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;
+ }
+}
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/ValidationXmlParser.java
___________________________________________________________________
Name: svn:keywords
+ Id
Added: 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 (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/XmlMappingParser.java 2009-04-22 10:59:38 UTC (rev 16395)
@@ -0,0 +1,597 @@
+// $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.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.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.engine.ConstraintDescriptorImpl;
+import org.hibernate.validation.engine.ConstraintHelper;
+import org.hibernate.validation.engine.MetaConstraint;
+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 Map<Class<?>, List<MetaConstraint<?, ? extends Annotation>>> getConstraintMap() {
+ return constraintMap;
+ }
+
+ public Map<Class<?>, List<Member>> getCascadedMembers() {
+ return cascadedMembers;
+ }
+
+ public Map<Class<?>, List<Class<?>>> getDefaultSequences() {
+ return defaultSequences;
+ }
+
+ @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 ( String validatorClassName : validatedByType.getValue() ) {
+ Class<? extends ConstraintValidator<?, ?>> validatorClass;
+ try {
+ validatorClass = ( Class<? extends ConstraintValidator<?, ?>> ) ReflectionHelper.classForName(
+ validatorClassName,
+ 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 ( String groupName : groupSequenceType.getValue() ) {
+ Class<?> group = getClass( groupName, 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, new Class[] { }, 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 ( String groupClass : groupsType.getValue() ) {
+ groupList.add( getClass( groupClass, 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;
+ }
+}
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/xml/XmlMappingParser.java
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/xml/Optional.java
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/xml/TestGroup.java
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-archetype/src/main/java/org/hibernate/validator/quickstart/Car.java
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-archetype/src/test/java/org/hibernate/validator/quickstart/CarTest.java
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator-tck-runner/src/main/java/org/hibernate/validation/test/StandaloneContainersImpl.java
___________________________________________________________________
Name: svn:keywords
+ Id
15 years, 7 months
Hibernate SVN: r16394 - in core/branches/envers-hibernate-3.3: src/main/java/org/hibernate/envers and 8 other directories.
by hibernate-commits@lists.jboss.org
Author: adamw
Date: 2009-04-22 05:02:56 -0400 (Wed, 22 Apr 2009)
New Revision: 16394
Added:
core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference/
core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference/BidirectionalReference.java
core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference/GreetingPO.java
core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference/GreetingSetPO.java
Removed:
core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference/BidirectionalReference.java
core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference/GreetingPO.java
core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference/GreetingSetPO.java
Modified:
core/branches/envers-hibernate-3.3/
core/branches/envers-hibernate-3.3/pom.xml
core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/AuditReaderFactory.java
core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/ComponentPropertyMapper.java
core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/ExtendedPropertyMapper.java
core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/MultiPropertyMapper.java
core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/PropertyMapper.java
core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/SinglePropertyMapper.java
core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/SubclassPropertyMapper.java
core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/relation/AbstractCollectionMapper.java
core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/relation/OneToOneNotOwningMapper.java
core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/relation/ToOneIdMapper.java
core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/event/AuditEventListener.java
core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/AbstractAuditWorkUnit.java
core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/AddWorkUnit.java
core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/CollectionChangeWorkUnit.java
core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/DelWorkUnit.java
core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/ModWorkUnit.java
core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/PersistentCollectionChangeWorkUnit.java
core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/tools/Tools.java
core/branches/envers-hibernate-3.3/src/test/resources/testng.xml
Log:
svn merge -r 16062:16393 https://svn.jboss.org/repos/hibernate/core/trunk/envers .
Property changes on: core/branches/envers-hibernate-3.3
___________________________________________________________________
Name: svn:ignore
- target
local
*.ipr
*.iws
*.iml
.classpath
.project
.nbattrs
*.log
*.properties
.clover
+ target
local
*.ipr
*.iws
*.iml
.classpath
.project
.settings
.nbattrs
*.log
*.properties
.clover
Modified: core/branches/envers-hibernate-3.3/pom.xml
===================================================================
--- core/branches/envers-hibernate-3.3/pom.xml 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/pom.xml 2009-04-22 09:02:56 UTC (rev 16394)
@@ -108,6 +108,12 @@
<scope>test</scope>
</dependency>
<dependency>
+ <groupId>cglib</groupId>
+ <artifactId>cglib</artifactId>
+ <version>2.2</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.4.GA</version>
Modified: core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/AuditReaderFactory.java
===================================================================
--- core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/AuditReaderFactory.java 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/AuditReaderFactory.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -43,15 +43,18 @@
/**
* Create an audit reader associated with an open session.
- * <b>WARNING:</b> Using Envers with Hibernate (not with Hibernate Entity Manager/JPA) is experimental,
- * if possible, use {@link AuditReaderFactory#get(javax.persistence.EntityManager)}.
* @param session An open session.
* @return An audit reader associated with the given sesison. It shouldn't be used
* after the session is closed.
* @throws AuditException When the given required listeners aren't installed.
*/
public static AuditReader get(Session session) throws AuditException {
- SessionImplementor sessionImpl = (SessionImplementor) session;
+ SessionImplementor sessionImpl;
+ if (!(session instanceof SessionImplementor)) {
+ sessionImpl = (SessionImplementor) session.getSessionFactory().getCurrentSession();
+ } else {
+ sessionImpl = (SessionImplementor) session;
+ }
EventListeners listeners = sessionImpl.getListeners();
@@ -83,6 +86,7 @@
}
if (entityManager.getDelegate() instanceof EntityManager) {
+ entityManager = (EntityManager) entityManager.getDelegate();
if (entityManager.getDelegate() instanceof Session) {
return get((Session) entityManager.getDelegate());
}
Modified: core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/ComponentPropertyMapper.java
===================================================================
--- core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/ComponentPropertyMapper.java 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/ComponentPropertyMapper.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -36,6 +36,7 @@
import org.hibernate.collection.PersistentCollection;
import org.hibernate.property.Setter;
import org.hibernate.util.ReflectHelper;
+import org.hibernate.engine.SessionImplementor;
/**
* @author Adam Warski (adam at warski dot org)
@@ -63,8 +64,8 @@
delegate.addComposite(propertyData, propertyMapper);
}
- public boolean mapToMapFromEntity(Map<String, Object> data, Object newObj, Object oldObj) {
- return delegate.mapToMapFromEntity(data, newObj, oldObj);
+ public boolean mapToMapFromEntity(SessionImplementor session, Map<String, Object> data, Object newObj, Object oldObj) {
+ return delegate.mapToMapFromEntity(session, data, newObj, oldObj);
}
public void mapToEntityFromMap(AuditConfiguration verCfg, Object obj, Map data, Object primaryKey, AuditReaderImplementor versionsReader, Number revision) {
Modified: core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/ExtendedPropertyMapper.java
===================================================================
--- core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/ExtendedPropertyMapper.java 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/ExtendedPropertyMapper.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -23,11 +23,13 @@
*/
package org.hibernate.envers.entities.mapper;
+import org.hibernate.engine.SessionImplementor;
+
import java.util.Map;
/**
* @author Adam Warski (adam at warski dot org)
*/
public interface ExtendedPropertyMapper extends PropertyMapper, CompositeMapperBuilder {
- public boolean map(Map<String, Object> data, String[] propertyNames, Object[] newState, Object[] oldState);
+ public boolean map(SessionImplementor session, Map<String, Object> data, String[] propertyNames, Object[] newState, Object[] oldState);
}
Modified: core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/MultiPropertyMapper.java
===================================================================
--- core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/MultiPropertyMapper.java 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/MultiPropertyMapper.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -36,6 +36,7 @@
import org.hibernate.collection.PersistentCollection;
import org.hibernate.property.Getter;
+import org.hibernate.engine.SessionImplementor;
/**
* @author Adam Warski (adam at warski dot org)
@@ -75,13 +76,13 @@
private Object getAtIndexOrNull(Object[] array, int index) { return array == null ? null : array[index]; }
- public boolean map(Map<String, Object> data, String[] propertyNames, Object[] newState, Object[] oldState) {
+ public boolean map(SessionImplementor session, Map<String, Object> data, String[] propertyNames, Object[] newState, Object[] oldState) {
boolean ret = false;
for (int i=0; i<propertyNames.length; i++) {
String propertyName = propertyNames[i];
if (propertyDatas.containsKey(propertyName)) {
- ret |= properties.get(propertyDatas.get(propertyName)).mapToMapFromEntity(data,
+ ret |= properties.get(propertyDatas.get(propertyName)).mapToMapFromEntity(session, data,
getAtIndexOrNull(newState, i),
getAtIndexOrNull(oldState, i));
}
@@ -90,7 +91,7 @@
return ret;
}
- public boolean mapToMapFromEntity(Map<String, Object> data, Object newObj, Object oldObj) {
+ public boolean mapToMapFromEntity(SessionImplementor session, Map<String, Object> data, Object newObj, Object oldObj) {
boolean ret = false;
for (PropertyData propertyData : properties.keySet()) {
Getter getter;
@@ -102,7 +103,7 @@
return false;
}
- ret |= properties.get(propertyData).mapToMapFromEntity(data,
+ ret |= properties.get(propertyData).mapToMapFromEntity(session, data,
newObj == null ? null : getter.get(newObj),
oldObj == null ? null : getter.get(oldObj));
}
Modified: core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/PropertyMapper.java
===================================================================
--- core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/PropertyMapper.java 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/PropertyMapper.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -31,6 +31,7 @@
import org.hibernate.envers.reader.AuditReaderImplementor;
import org.hibernate.collection.PersistentCollection;
+import org.hibernate.engine.SessionImplementor;
/**
* @author Adam Warski (adam at warski dot org)
@@ -38,12 +39,13 @@
public interface PropertyMapper {
/**
* Maps properties to the given map, basing on differences between properties of new and old objects.
- * @param data Data to map to.
- * @param newObj New state of the entity.
- * @param oldObj Old state of the entity.
- * @return True if there are any differences between the states represented by newObj and oldObj.
+ * @param session The current session.
+ * @param data Data to map to.
+ * @param newObj New state of the entity.
+ * @param oldObj Old state of the entity.
+ * @return True if there are any differences between the states represented by newObj and oldObj.
*/
- boolean mapToMapFromEntity(Map<String, Object> data, Object newObj, Object oldObj);
+ boolean mapToMapFromEntity(SessionImplementor session, Map<String, Object> data, Object newObj, Object oldObj);
/**
* Maps properties from the given map to the given object.
Modified: core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/SinglePropertyMapper.java
===================================================================
--- core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/SinglePropertyMapper.java 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/SinglePropertyMapper.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -36,6 +36,7 @@
import org.hibernate.collection.PersistentCollection;
import org.hibernate.property.Setter;
+import org.hibernate.engine.SessionImplementor;
/**
* TODO: diff
@@ -54,7 +55,7 @@
this.propertyData = propertyData;
}
- public boolean mapToMapFromEntity(Map<String, Object> data, Object newObj, Object oldObj) {
+ public boolean mapToMapFromEntity(SessionImplementor session, Map<String, Object> data, Object newObj, Object oldObj) {
data.put(propertyData.getName(), newObj);
return !Tools.objectsEqual(newObj, oldObj);
Modified: core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/SubclassPropertyMapper.java
===================================================================
--- core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/SubclassPropertyMapper.java 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/SubclassPropertyMapper.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -32,6 +32,7 @@
import org.hibernate.envers.reader.AuditReaderImplementor;
import org.hibernate.collection.PersistentCollection;
+import org.hibernate.engine.SessionImplementor;
/**
* A mapper which maps from a parent mapper and a "main" one, but adds only to the "main". The "main" mapper
@@ -47,16 +48,16 @@
this.parentMapper = parentMapper;
}
- public boolean map(Map<String, Object> data, String[] propertyNames, Object[] newState, Object[] oldState) {
- boolean parentDiffs = parentMapper.map(data, propertyNames, newState, oldState);
- boolean mainDiffs = main.map(data, propertyNames, newState, oldState);
+ public boolean map(SessionImplementor session, Map<String, Object> data, String[] propertyNames, Object[] newState, Object[] oldState) {
+ boolean parentDiffs = parentMapper.map(session, data, propertyNames, newState, oldState);
+ boolean mainDiffs = main.map(session, data, propertyNames, newState, oldState);
return parentDiffs || mainDiffs;
}
- public boolean mapToMapFromEntity(Map<String, Object> data, Object newObj, Object oldObj) {
- boolean parentDiffs = parentMapper.mapToMapFromEntity(data, newObj, oldObj);
- boolean mainDiffs = main.mapToMapFromEntity(data, newObj, oldObj);
+ public boolean mapToMapFromEntity(SessionImplementor session, Map<String, Object> data, Object newObj, Object oldObj) {
+ boolean parentDiffs = parentMapper.mapToMapFromEntity(session, data, newObj, oldObj);
+ boolean mainDiffs = main.mapToMapFromEntity(session, data, newObj, oldObj);
return parentDiffs || mainDiffs;
}
Modified: core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/relation/AbstractCollectionMapper.java
===================================================================
--- core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/relation/AbstractCollectionMapper.java 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/relation/AbstractCollectionMapper.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -45,6 +45,7 @@
import org.hibernate.collection.PersistentCollection;
import org.hibernate.property.Setter;
+import org.hibernate.engine.SessionImplementor;
/**
* @author Adam Warski (adam at warski dot org)
@@ -130,7 +131,7 @@
return collectionChanges;
}
- public boolean mapToMapFromEntity(Map<String, Object> data, Object newObj, Object oldObj) {
+ public boolean mapToMapFromEntity(SessionImplementor session, Map<String, Object> data, Object newObj, Object oldObj) {
// Changes are mapped in the "mapCollectionChanges" method.
return false;
}
Modified: core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/relation/OneToOneNotOwningMapper.java
===================================================================
--- core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/relation/OneToOneNotOwningMapper.java 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/relation/OneToOneNotOwningMapper.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -38,6 +38,7 @@
import org.hibernate.envers.tools.reflection.ReflectionTools;
import org.hibernate.NonUniqueResultException;
+import org.hibernate.engine.SessionImplementor;
import org.hibernate.collection.PersistentCollection;
import org.hibernate.property.Setter;
@@ -56,7 +57,7 @@
this.propertyData = propertyData;
}
- public boolean mapToMapFromEntity(Map<String, Object> data, Object newObj, Object oldObj) {
+ public boolean mapToMapFromEntity(SessionImplementor session, Map<String, Object> data, Object newObj, Object oldObj) {
return false;
}
Modified: core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/relation/ToOneIdMapper.java
===================================================================
--- core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/relation/ToOneIdMapper.java 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/entities/mapper/relation/ToOneIdMapper.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -40,6 +40,7 @@
import org.hibernate.collection.PersistentCollection;
import org.hibernate.property.Setter;
+import org.hibernate.engine.SessionImplementor;
/**
* @author Adam Warski (adam at warski dot org)
@@ -55,13 +56,13 @@
this.referencedEntityName = referencedEntityName;
}
- public boolean mapToMapFromEntity(Map<String, Object> data, Object newObj, Object oldObj) {
+ public boolean mapToMapFromEntity(SessionImplementor session, Map<String, Object> data, Object newObj, Object oldObj) {
HashMap<String, Object> newData = new HashMap<String, Object>();
data.put(propertyData.getName(), newData);
delegate.mapToMapFromEntity(newData, newObj);
- return !Tools.objectsEqual(newObj, oldObj);
+ return !Tools.entitiesEqual(session, newObj, oldObj);
}
public void mapToEntityFromMap(AuditConfiguration verCfg, Object obj, Map data, Object primaryKey,
Modified: core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/event/AuditEventListener.java
===================================================================
--- core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/event/AuditEventListener.java 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/event/AuditEventListener.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -91,41 +91,49 @@
Object oldValue = oldState == null ? null : oldState[i];
Object newValue = newState == null ? null : newState[i];
- if (!Tools.objectsEqual(oldValue, newValue)) {
+ if (!Tools.entitiesEqual(session, oldValue, newValue)) {
// We have to generate changes both in the old collection (size decreses) and new collection
// (size increases).
if (newValue != null) {
// relDesc.getToEntityName() doesn't always return the entity name of the value - in case
// of subclasses, this will be root class, no the actual class. So it can't be used here.
String toEntityName;
- if(newValue instanceof HibernateProxy) {
+ Serializable id;
+
+ if (newValue instanceof HibernateProxy) {
HibernateProxy hibernateProxy = (HibernateProxy) newValue;
toEntityName = session.bestGuessEntityName(newValue);
- newValue = hibernateProxy.getHibernateLazyInitializer().getImplementation();
+ id = hibernateProxy.getHibernateLazyInitializer().getIdentifier();
+ // We've got to initialize the object from the proxy to later read its state.
+ newValue = Tools.getTargetFromProxy(hibernateProxy);
} else {
toEntityName = session.guessEntityName(newValue);
+
+ IdMapper idMapper = verCfg.getEntCfg().get(toEntityName).getIdMapper();
+ id = (Serializable) idMapper.mapToIdFromEntity(newValue);
}
- IdMapper idMapper = verCfg.getEntCfg().get(toEntityName).getIdMapper();
-
- Serializable id = (Serializable) idMapper.mapToIdFromEntity(newValue);
- verSync.addWorkUnit(new CollectionChangeWorkUnit(toEntityName, verCfg, id, newValue));
+ verSync.addWorkUnit(new CollectionChangeWorkUnit(session, toEntityName, verCfg, id, newValue));
}
if (oldValue != null) {
String toEntityName;
+ Serializable id;
+
if(oldValue instanceof HibernateProxy) {
HibernateProxy hibernateProxy = (HibernateProxy) oldValue;
toEntityName = session.bestGuessEntityName(oldValue);
- oldValue = hibernateProxy.getHibernateLazyInitializer().getImplementation();
+ id = hibernateProxy.getHibernateLazyInitializer().getIdentifier();
+ // We've got to initialize the object as we'll read it's state anyway.
+ oldValue = Tools.getTargetFromProxy(hibernateProxy);
} else {
toEntityName = session.guessEntityName(oldValue);
+
+ IdMapper idMapper = verCfg.getEntCfg().get(toEntityName).getIdMapper();
+ id = (Serializable) idMapper.mapToIdFromEntity(oldValue);
}
-
- IdMapper idMapper = verCfg.getEntCfg().get(toEntityName).getIdMapper();
-
- Serializable id = (Serializable) idMapper.mapToIdFromEntity(oldValue);
- verSync.addWorkUnit(new CollectionChangeWorkUnit(toEntityName, verCfg, id, oldValue));
+
+ verSync.addWorkUnit(new CollectionChangeWorkUnit(session, toEntityName, verCfg, id, oldValue));
}
}
}
@@ -138,8 +146,8 @@
if (verCfg.getEntCfg().isVersioned(entityName)) {
AuditSync verSync = verCfg.getSyncManager().get(event.getSession());
- verSync.addWorkUnit(new AddWorkUnit(event.getPersister().getEntityName(), verCfg, event.getId(),
- event.getPersister(), event.getState()));
+ verSync.addWorkUnit(new AddWorkUnit(event.getSession(), event.getPersister().getEntityName(), verCfg,
+ event.getId(), event.getPersister(), event.getState()));
generateBidirectionalCollectionChangeWorkUnits(verSync, event.getPersister(), entityName, event.getState(),
null, event.getSession());
@@ -152,8 +160,8 @@
if (verCfg.getEntCfg().isVersioned(entityName)) {
AuditSync verSync = verCfg.getSyncManager().get(event.getSession());
- verSync.addWorkUnit(new ModWorkUnit(event.getPersister().getEntityName(), verCfg, event.getId(),
- event.getPersister(), event.getState(), event.getOldState()));
+ verSync.addWorkUnit(new ModWorkUnit(event.getSession(), event.getPersister().getEntityName(), verCfg,
+ event.getId(), event.getPersister(), event.getState(), event.getOldState()));
generateBidirectionalCollectionChangeWorkUnits(verSync, event.getPersister(), entityName, event.getState(),
event.getOldState(), event.getSession());
@@ -166,7 +174,8 @@
if (verCfg.getEntCfg().isVersioned(entityName)) {
AuditSync verSync = verCfg.getSyncManager().get(event.getSession());
- verSync.addWorkUnit(new DelWorkUnit(event.getPersister().getEntityName(), verCfg, event.getId()));
+ verSync.addWorkUnit(new DelWorkUnit(event.getSession(), event.getPersister().getEntityName(), verCfg,
+ event.getId()));
generateBidirectionalCollectionChangeWorkUnits(verSync, event.getPersister(), entityName, null,
event.getDeletedState(), event.getSession());
@@ -194,7 +203,8 @@
Object relatedObj = changeData.getChangedElement();
Serializable relatedId = (Serializable) relatedIdMapper.mapToIdFromEntity(relatedObj);
- verSync.addWorkUnit(new CollectionChangeWorkUnit(relatedEntityName, verCfg, relatedId, relatedObj));
+ verSync.addWorkUnit(new CollectionChangeWorkUnit(event.getSession(), relatedEntityName, verCfg,
+ relatedId, relatedObj));
}
}
}
@@ -206,14 +216,14 @@
if (verCfg.getEntCfg().isVersioned(entityName)) {
AuditSync verSync = verCfg.getSyncManager().get(event.getSession());
- PersistentCollectionChangeWorkUnit workUnit = new PersistentCollectionChangeWorkUnit(entityName, verCfg,
- newColl, collectionEntry, oldColl, event.getAffectedOwnerIdOrNull());
+ PersistentCollectionChangeWorkUnit workUnit = new PersistentCollectionChangeWorkUnit(event.getSession(),
+ entityName, verCfg, newColl, collectionEntry, oldColl, event.getAffectedOwnerIdOrNull());
verSync.addWorkUnit(workUnit);
if (workUnit.containsWork()) {
// There are some changes: a revision needs also be generated for the collection owner
- verSync.addWorkUnit(new CollectionChangeWorkUnit(event.getAffectedOwnerEntityName(), verCfg,
- event.getAffectedOwnerIdOrNull(), event.getAffectedOwnerOrNull()));
+ verSync.addWorkUnit(new CollectionChangeWorkUnit(event.getSession(), event.getAffectedOwnerEntityName(),
+ verCfg, event.getAffectedOwnerIdOrNull(), event.getAffectedOwnerOrNull()));
generateBidirectionalCollectionChangeWorkUnits(verSync, event, workUnit);
}
Modified: core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/AbstractAuditWorkUnit.java
===================================================================
--- core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/AbstractAuditWorkUnit.java 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/AbstractAuditWorkUnit.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -32,11 +32,13 @@
import org.hibernate.envers.configuration.AuditEntitiesConfiguration;
import org.hibernate.Session;
+import org.hibernate.engine.SessionImplementor;
/**
* @author Adam Warski (adam at warski dot org)
*/
public abstract class AbstractAuditWorkUnit implements AuditWorkUnit {
+ protected final SessionImplementor sessionImplementor;
protected final AuditConfiguration verCfg;
protected final Serializable id;
@@ -44,7 +46,9 @@
private Object performedData;
- protected AbstractAuditWorkUnit(String entityName, AuditConfiguration verCfg, Serializable id) {
+ protected AbstractAuditWorkUnit(SessionImplementor sessionImplementor, String entityName, AuditConfiguration verCfg,
+ Serializable id) {
+ this.sessionImplementor = sessionImplementor;
this.verCfg = verCfg;
this.id = id;
this.entityName = entityName;
Modified: core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/AddWorkUnit.java
===================================================================
--- core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/AddWorkUnit.java 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/AddWorkUnit.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -31,6 +31,7 @@
import org.hibernate.envers.configuration.AuditConfiguration;
import org.hibernate.Session;
+import org.hibernate.engine.SessionImplementor;
import org.hibernate.persister.entity.EntityPersister;
/**
@@ -40,9 +41,9 @@
private final Object[] state;
private final String[] propertyNames;
- public AddWorkUnit(String entityName, AuditConfiguration verCfg, Serializable id,
- EntityPersister entityPersister, Object[] state) {
- super(entityName, verCfg, id);
+ public AddWorkUnit(SessionImplementor sessionImplementor, String entityName, AuditConfiguration verCfg,
+ Serializable id, EntityPersister entityPersister, Object[] state) {
+ super(sessionImplementor, entityName, verCfg, id);
this.state = state;
this.propertyNames = entityPersister.getPropertyNames();
@@ -56,7 +57,8 @@
Map<String, Object> data = new HashMap<String, Object>();
fillDataWithId(data, revisionData, RevisionType.ADD);
- verCfg.getEntCfg().get(getEntityName()).getPropertyMapper().map(data, propertyNames, state, null);
+ verCfg.getEntCfg().get(getEntityName()).getPropertyMapper().map(sessionImplementor, data,
+ propertyNames, state, null);
session.save(verCfg.getAuditEntCfg().getAuditEntityName(getEntityName()), data);
Modified: core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/CollectionChangeWorkUnit.java
===================================================================
--- core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/CollectionChangeWorkUnit.java 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/CollectionChangeWorkUnit.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -31,6 +31,7 @@
import org.hibernate.envers.configuration.AuditConfiguration;
import org.hibernate.Session;
+import org.hibernate.engine.SessionImplementor;
/**
* @author Adam Warski (adam at warski dot org)
@@ -38,8 +39,9 @@
public class CollectionChangeWorkUnit extends AbstractAuditWorkUnit implements AuditWorkUnit {
private final Object entity;
- public CollectionChangeWorkUnit(String entityName, AuditConfiguration verCfg, Serializable id, Object entity) {
- super(entityName, verCfg, id);
+ public CollectionChangeWorkUnit(SessionImplementor session, String entityName, AuditConfiguration verCfg,
+ Serializable id, Object entity) {
+ super(session, entityName, verCfg, id);
this.entity = entity;
}
@@ -52,7 +54,8 @@
Map<String, Object> data = new HashMap<String, Object>();
fillDataWithId(data, revisionData, RevisionType.MOD);
- verCfg.getEntCfg().get(getEntityName()).getPropertyMapper().mapToMapFromEntity(data, entity, null);
+ verCfg.getEntCfg().get(getEntityName()).getPropertyMapper().mapToMapFromEntity(sessionImplementor,
+ data, entity, null);
session.save(verCfg.getAuditEntCfg().getAuditEntityName(getEntityName()), data);
Modified: core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/DelWorkUnit.java
===================================================================
--- core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/DelWorkUnit.java 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/DelWorkUnit.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -31,13 +31,14 @@
import org.hibernate.envers.configuration.AuditConfiguration;
import org.hibernate.Session;
+import org.hibernate.engine.SessionImplementor;
/**
* @author Adam Warski (adam at warski dot org)
*/
public class DelWorkUnit extends AbstractAuditWorkUnit implements AuditWorkUnit {
- public DelWorkUnit(String entityName, AuditConfiguration verCfg, Serializable id) {
- super(entityName, verCfg, id);
+ public DelWorkUnit(SessionImplementor sessionImplementor, String entityName, AuditConfiguration verCfg, Serializable id) {
+ super(sessionImplementor, entityName, verCfg, id);
}
public boolean containsWork() {
Modified: core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/ModWorkUnit.java
===================================================================
--- core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/ModWorkUnit.java 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/ModWorkUnit.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -31,6 +31,7 @@
import org.hibernate.envers.configuration.AuditConfiguration;
import org.hibernate.Session;
+import org.hibernate.engine.SessionImplementor;
import org.hibernate.persister.entity.EntityPersister;
/**
@@ -40,13 +41,13 @@
private final Map<String, Object> data;
private final boolean changes;
- public ModWorkUnit(String entityName, AuditConfiguration verCfg, Serializable id,
- EntityPersister entityPersister, Object[] newState, Object[] oldState) {
- super(entityName, verCfg, id);
+ public ModWorkUnit(SessionImplementor sessionImplementor, String entityName, AuditConfiguration verCfg,
+ Serializable id, EntityPersister entityPersister, Object[] newState, Object[] oldState) {
+ super(sessionImplementor, entityName, verCfg, id);
data = new HashMap<String, Object>();
- changes = verCfg.getEntCfg().get(getEntityName()).getPropertyMapper().map(data, entityPersister.getPropertyNames(),
- newState, oldState);
+ changes = verCfg.getEntCfg().get(getEntityName()).getPropertyMapper().map(sessionImplementor, data,
+ entityPersister.getPropertyNames(), newState, oldState);
}
public boolean containsWork() {
Modified: core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/PersistentCollectionChangeWorkUnit.java
===================================================================
--- core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/PersistentCollectionChangeWorkUnit.java 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/synchronization/work/PersistentCollectionChangeWorkUnit.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -34,6 +34,7 @@
import org.hibernate.Session;
import org.hibernate.persister.collection.AbstractCollectionPersister;
import org.hibernate.engine.CollectionEntry;
+import org.hibernate.engine.SessionImplementor;
import org.hibernate.collection.PersistentCollection;
/**
@@ -43,10 +44,10 @@
private final List<PersistentCollectionChangeData> collectionChanges;
private final String referencingPropertyName;
- public PersistentCollectionChangeWorkUnit(String entityName, AuditConfiguration verCfg,
- PersistentCollection collection, CollectionEntry collectionEntry,
- Serializable snapshot, Serializable id) {
- super(entityName, verCfg, null);
+ public PersistentCollectionChangeWorkUnit(SessionImplementor sessionImplementor, String entityName,
+ AuditConfiguration verCfg, PersistentCollection collection,
+ CollectionEntry collectionEntry, Serializable snapshot, Serializable id) {
+ super(sessionImplementor, entityName, verCfg, null);
String ownerEntityName = ((AbstractCollectionPersister) collectionEntry.getLoadedPersister()).getOwnerEntityName();
referencingPropertyName = collectionEntry.getRole().substring(ownerEntityName.length() + 1);
Modified: core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/tools/Tools.java
===================================================================
--- core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/tools/Tools.java 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/src/main/java/org/hibernate/envers/tools/Tools.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -23,6 +23,10 @@
*/
package org.hibernate.envers.tools;
+import org.hibernate.proxy.HibernateProxy;
+import org.hibernate.engine.SessionImplementor;
+import org.hibernate.Session;
+
import java.util.*;
/**
@@ -41,6 +45,42 @@
return new LinkedHashMap<K,V>();
}
+ public static boolean entitiesEqual(SessionImplementor session, Object obj1, Object obj2) {
+ Object id1 = getIdentifier(session, obj1);
+ Object id2 = getIdentifier(session, obj2);
+
+ return objectsEqual(id1, id2);
+ }
+
+ public static Object getIdentifier(SessionImplementor session, Object obj) {
+ if (obj == null) {
+ return null;
+ }
+
+ if (obj instanceof HibernateProxy) {
+ HibernateProxy hibernateProxy = (HibernateProxy) obj;
+ return hibernateProxy.getHibernateLazyInitializer().getIdentifier();
+ }
+
+
+ return session.getEntityPersister(null, obj).getIdentifier(obj, session.getEntityMode());
+ }
+
+ public static Object getTargetFromProxy(HibernateProxy proxy) {
+ if (!proxy.getHibernateLazyInitializer().isUninitialized()) {
+ return proxy.getHibernateLazyInitializer().getImplementation();
+ }
+
+ Session tempSession = proxy.getHibernateLazyInitializer().getSession().getFactory().openTemporarySession();
+ try {
+ proxy.getHibernateLazyInitializer().setSession((SessionImplementor) tempSession);
+ proxy.getHibernateLazyInitializer().initialize();
+ return proxy.getHibernateLazyInitializer().getImplementation();
+ } finally {
+ tempSession.close();
+ }
+ }
+
public static boolean objectsEqual(Object obj1, Object obj2) {
if (obj1 == null) {
return obj2 == null;
Copied: core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference (from rev 16393, core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/reference)
Deleted: core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference/BidirectionalReference.java
===================================================================
--- core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/reference/BidirectionalReference.java 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference/BidirectionalReference.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -1,150 +0,0 @@
-/*
- * Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
- * indicated by the @author tags or express copyright attribution
- * statements applied by the authors. All third-party contributions are
- * distributed under license by Red Hat Middleware LLC.
- *
- * This copyrighted material is made available to anyone wishing to use, modify,
- * copy, or redistribute it subject to the terms and conditions of the GNU
- * Lesser General Public License, as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
- * for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this distribution; if not, write to:
- * Free Software Foundation, Inc.
- * 51 Franklin Street, Fifth Floor
- * Boston, MA 02110-1301 USA
- */
-package org.hibernate.envers.test.integration.reference;
-
-import org.hibernate.ejb.Ejb3Configuration;
-import org.hibernate.envers.test.AbstractEntityTest;
-import org.hibernate.envers.test.tools.TestTools;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
-
-import javax.persistence.EntityManager;
-import java.util.Arrays;
-
-/**
- * @author Adam Warski (adam at warski dot org)
- */
-public class BidirectionalReference extends AbstractEntityTest {
- private Long set1_id;
- private Long set2_id;
-
- private Long g1_id;
-
- public void configure(Ejb3Configuration cfg) {
- cfg.addAnnotatedClass(GreetingPO.class);
- cfg.addAnnotatedClass(GreetingSetPO.class);
- }
-
- @BeforeClass(dependsOnMethods = "init")
- public void initData() {
- EntityManager em = getEntityManager();
-
- GreetingSetPO set1 = new GreetingSetPO();
- set1.setName("a1");
-
- GreetingSetPO set2 = new GreetingSetPO();
- set2.setName("a2");
-
- // Revision 1
- em.getTransaction().begin();
-
- em.persist(set1);
- em.persist(set2);
-
- set1_id = set1.getId();
- set2_id = set2.getId();
-
- em.getTransaction().commit();
- em.clear();
-
- // Revision 2
- em.getTransaction().begin();
-
- GreetingPO g1 = new GreetingPO();
- g1.setGreeting("g1");
- g1.setGreetingSet(em.getReference(GreetingSetPO.class, set1_id));
-
- em.persist(g1);
- g1_id = g1.getId();
-
- em.getTransaction().commit();
- em.clear();
-
- // Revision 3
- em.getTransaction().begin();
-
- g1 = em.find(GreetingPO.class, g1_id);
-
- g1.setGreetingSet(em.getReference(GreetingSetPO.class, set2_id));
-
- em.getTransaction().commit();
- }
-
- @Test
- public void testRevisionsCounts() {
- assert Arrays.asList(2, 3).equals(getAuditReader().getRevisions(GreetingPO.class, g1_id));
-
- assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(GreetingSetPO.class, set1_id));
- assert Arrays.asList(1, 3).equals(getAuditReader().getRevisions(GreetingSetPO.class, set2_id));
- }
-
- @Test
- public void testHistoryOfG1() {
- GreetingPO rev1 = getAuditReader().find(GreetingPO.class, g1_id, 1);
- GreetingPO rev2 = getAuditReader().find(GreetingPO.class, g1_id, 2);
- GreetingPO rev3 = getAuditReader().find(GreetingPO.class, g1_id, 3);
-
- assert rev1 == null;
- assert rev2.getGreetingSet().getName().equals("a1");
- assert rev3.getGreetingSet().getName().equals("a2");
- }
-
- @Test
- public void testHistoryOfSet1() {
- GreetingSetPO rev1 = getAuditReader().find(GreetingSetPO.class, set1_id, 1);
- GreetingSetPO rev2 = getAuditReader().find(GreetingSetPO.class, set1_id, 2);
- GreetingSetPO rev3 = getAuditReader().find(GreetingSetPO.class, set1_id, 3);
-
- assert rev1.getName().equals("a1");
- assert rev2.getName().equals("a1");
- assert rev3.getName().equals("a1");
-
- GreetingPO g1 = new GreetingPO();
- g1.setId(g1_id);
- g1.setGreeting("g1");
-
- assert rev1.getGreetings().size() == 0;
- assert rev2.getGreetings().equals(TestTools.makeSet(g1));
- assert rev3.getGreetings().size() == 0;
- }
-
- @Test
- public void testHistoryOfSet2() {
- GreetingSetPO rev1 = getAuditReader().find(GreetingSetPO.class, set2_id, 1);
- GreetingSetPO rev2 = getAuditReader().find(GreetingSetPO.class, set2_id, 2);
- GreetingSetPO rev3 = getAuditReader().find(GreetingSetPO.class, set2_id, 3);
-
- assert rev1.getName().equals("a2");
- assert rev2.getName().equals("a2");
- assert rev3.getName().equals("a2");
-
- GreetingPO g1 = new GreetingPO();
- g1.setId(g1_id);
- g1.setGreeting("g1");
-
- assert rev1.getGreetings().size() == 0;
- assert rev2.getGreetings().size() == 0;
- assert rev3.getGreetings().equals(TestTools.makeSet(g1));
- }
-}
\ No newline at end of file
Copied: core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference/BidirectionalReference.java (from rev 16393, core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/reference/BidirectionalReference.java)
===================================================================
--- core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference/BidirectionalReference.java (rev 0)
+++ core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference/BidirectionalReference.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -0,0 +1,150 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.envers.test.integration.reference;
+
+import org.hibernate.ejb.Ejb3Configuration;
+import org.hibernate.envers.test.AbstractEntityTest;
+import org.hibernate.envers.test.tools.TestTools;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+import javax.persistence.EntityManager;
+import java.util.Arrays;
+
+/**
+ * @author Adam Warski (adam at warski dot org)
+ */
+public class BidirectionalReference extends AbstractEntityTest {
+ private Long set1_id;
+ private Long set2_id;
+
+ private Long g1_id;
+
+ public void configure(Ejb3Configuration cfg) {
+ cfg.addAnnotatedClass(GreetingPO.class);
+ cfg.addAnnotatedClass(GreetingSetPO.class);
+ }
+
+ @BeforeClass(dependsOnMethods = "init")
+ public void initData() {
+ EntityManager em = getEntityManager();
+
+ GreetingSetPO set1 = new GreetingSetPO();
+ set1.setName("a1");
+
+ GreetingSetPO set2 = new GreetingSetPO();
+ set2.setName("a2");
+
+ // Revision 1
+ em.getTransaction().begin();
+
+ em.persist(set1);
+ em.persist(set2);
+
+ set1_id = set1.getId();
+ set2_id = set2.getId();
+
+ em.getTransaction().commit();
+ em.clear();
+
+ // Revision 2
+ em.getTransaction().begin();
+
+ GreetingPO g1 = new GreetingPO();
+ g1.setGreeting("g1");
+ g1.setGreetingSet(em.getReference(GreetingSetPO.class, set1_id));
+
+ em.persist(g1);
+ g1_id = g1.getId();
+
+ em.getTransaction().commit();
+ em.clear();
+
+ // Revision 3
+ em.getTransaction().begin();
+
+ g1 = em.find(GreetingPO.class, g1_id);
+
+ g1.setGreetingSet(em.getReference(GreetingSetPO.class, set2_id));
+
+ em.getTransaction().commit();
+ }
+
+ @Test
+ public void testRevisionsCounts() {
+ assert Arrays.asList(2, 3).equals(getAuditReader().getRevisions(GreetingPO.class, g1_id));
+
+ assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(GreetingSetPO.class, set1_id));
+ assert Arrays.asList(1, 3).equals(getAuditReader().getRevisions(GreetingSetPO.class, set2_id));
+ }
+
+ @Test
+ public void testHistoryOfG1() {
+ GreetingPO rev1 = getAuditReader().find(GreetingPO.class, g1_id, 1);
+ GreetingPO rev2 = getAuditReader().find(GreetingPO.class, g1_id, 2);
+ GreetingPO rev3 = getAuditReader().find(GreetingPO.class, g1_id, 3);
+
+ assert rev1 == null;
+ assert rev2.getGreetingSet().getName().equals("a1");
+ assert rev3.getGreetingSet().getName().equals("a2");
+ }
+
+ @Test
+ public void testHistoryOfSet1() {
+ GreetingSetPO rev1 = getAuditReader().find(GreetingSetPO.class, set1_id, 1);
+ GreetingSetPO rev2 = getAuditReader().find(GreetingSetPO.class, set1_id, 2);
+ GreetingSetPO rev3 = getAuditReader().find(GreetingSetPO.class, set1_id, 3);
+
+ assert rev1.getName().equals("a1");
+ assert rev2.getName().equals("a1");
+ assert rev3.getName().equals("a1");
+
+ GreetingPO g1 = new GreetingPO();
+ g1.setId(g1_id);
+ g1.setGreeting("g1");
+
+ assert rev1.getGreetings().size() == 0;
+ assert rev2.getGreetings().equals(TestTools.makeSet(g1));
+ assert rev3.getGreetings().size() == 0;
+ }
+
+ @Test
+ public void testHistoryOfSet2() {
+ GreetingSetPO rev1 = getAuditReader().find(GreetingSetPO.class, set2_id, 1);
+ GreetingSetPO rev2 = getAuditReader().find(GreetingSetPO.class, set2_id, 2);
+ GreetingSetPO rev3 = getAuditReader().find(GreetingSetPO.class, set2_id, 3);
+
+ assert rev1.getName().equals("a2");
+ assert rev2.getName().equals("a2");
+ assert rev3.getName().equals("a2");
+
+ GreetingPO g1 = new GreetingPO();
+ g1.setId(g1_id);
+ g1.setGreeting("g1");
+
+ assert rev1.getGreetings().size() == 0;
+ assert rev2.getGreetings().size() == 0;
+ assert rev3.getGreetings().equals(TestTools.makeSet(g1));
+ }
+}
\ No newline at end of file
Deleted: core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference/GreetingPO.java
===================================================================
--- core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/reference/GreetingPO.java 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference/GreetingPO.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -1,65 +0,0 @@
-package org.hibernate.envers.test.integration.reference;
-
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.ManyToOne;
-
-import org.hibernate.envers.Audited;
-
-@Entity
-@Audited
-public class GreetingPO {
- @Id
- @GeneratedValue
- private Long id;
-
- private String theGreeting;
-
- @ManyToOne
- private GreetingSetPO greetingSet;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getGreeting() {
- return theGreeting;
- }
-
- public void setGreeting(String greeting) {
- this.theGreeting = greeting;
- }
-
- public GreetingSetPO getGreetingSet() {
- return greetingSet;
- }
-
- public void setGreetingSet(GreetingSetPO greetingSet) {
- this.greetingSet = greetingSet;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof GreetingPO)) return false;
-
- GreetingPO that = (GreetingPO) o;
-
- if (id != null ? !id.equals(that.id) : that.id != null) return false;
- if (theGreeting != null ? !theGreeting.equals(that.theGreeting) : that.theGreeting != null) return false;
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = id != null ? id.hashCode() : 0;
- result = 31 * result + (theGreeting != null ? theGreeting.hashCode() : 0);
- return result;
- }
-}
\ No newline at end of file
Copied: core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference/GreetingPO.java (from rev 16393, core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/reference/GreetingPO.java)
===================================================================
--- core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference/GreetingPO.java (rev 0)
+++ core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference/GreetingPO.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -0,0 +1,65 @@
+package org.hibernate.envers.test.integration.reference;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+
+import org.hibernate.envers.Audited;
+
+@Entity
+@Audited
+public class GreetingPO {
+ @Id
+ @GeneratedValue
+ private Long id;
+
+ private String theGreeting;
+
+ @ManyToOne
+ private GreetingSetPO greetingSet;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getGreeting() {
+ return theGreeting;
+ }
+
+ public void setGreeting(String greeting) {
+ this.theGreeting = greeting;
+ }
+
+ public GreetingSetPO getGreetingSet() {
+ return greetingSet;
+ }
+
+ public void setGreetingSet(GreetingSetPO greetingSet) {
+ this.greetingSet = greetingSet;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof GreetingPO)) return false;
+
+ GreetingPO that = (GreetingPO) o;
+
+ if (id != null ? !id.equals(that.id) : that.id != null) return false;
+ if (theGreeting != null ? !theGreeting.equals(that.theGreeting) : that.theGreeting != null) return false;
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = id != null ? id.hashCode() : 0;
+ result = 31 * result + (theGreeting != null ? theGreeting.hashCode() : 0);
+ return result;
+ }
+}
\ No newline at end of file
Deleted: core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference/GreetingSetPO.java
===================================================================
--- core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/reference/GreetingSetPO.java 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference/GreetingSetPO.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -1,67 +0,0 @@
-package org.hibernate.envers.test.integration.reference;
-
-import java.util.Set;
-
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.OneToMany;
-
-import org.hibernate.envers.Audited;
-
-@Entity
-@Audited
-public class GreetingSetPO {
- @Id
- @GeneratedValue
- private Long id;
-
- private String name;
-
- @OneToMany(mappedBy = "greetingSet")
- private Set<GreetingPO> greetings;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public Set<GreetingPO> getGreetings() {
- return greetings;
- }
-
- public void setGreetings(Set<GreetingPO> greetings) {
- this.greetings = greetings;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof GreetingSetPO)) return false;
-
- GreetingSetPO that = (GreetingSetPO) o;
-
- if (id != null ? !id.equals(that.id) : that.id != null) return false;
- if (name != null ? !name.equals(that.name) : that.name != null) return false;
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = id != null ? id.hashCode() : 0;
- result = 31 * result + (name != null ? name.hashCode() : 0);
- return result;
- }
-}
\ No newline at end of file
Copied: core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference/GreetingSetPO.java (from rev 16393, core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/reference/GreetingSetPO.java)
===================================================================
--- core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference/GreetingSetPO.java (rev 0)
+++ core/branches/envers-hibernate-3.3/src/test/java/org/hibernate/envers/test/integration/reference/GreetingSetPO.java 2009-04-22 09:02:56 UTC (rev 16394)
@@ -0,0 +1,67 @@
+package org.hibernate.envers.test.integration.reference;
+
+import java.util.Set;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+
+import org.hibernate.envers.Audited;
+
+@Entity
+@Audited
+public class GreetingSetPO {
+ @Id
+ @GeneratedValue
+ private Long id;
+
+ private String name;
+
+ @OneToMany(mappedBy = "greetingSet")
+ private Set<GreetingPO> greetings;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Set<GreetingPO> getGreetings() {
+ return greetings;
+ }
+
+ public void setGreetings(Set<GreetingPO> greetings) {
+ this.greetings = greetings;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof GreetingSetPO)) return false;
+
+ GreetingSetPO that = (GreetingSetPO) o;
+
+ if (id != null ? !id.equals(that.id) : that.id != null) return false;
+ if (name != null ? !name.equals(that.name) : that.name != null) return false;
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = id != null ? id.hashCode() : 0;
+ result = 31 * result + (name != null ? name.hashCode() : 0);
+ return result;
+ }
+}
\ No newline at end of file
Modified: core/branches/envers-hibernate-3.3/src/test/resources/testng.xml
===================================================================
--- core/branches/envers-hibernate-3.3/src/test/resources/testng.xml 2009-04-22 08:38:05 UTC (rev 16393)
+++ core/branches/envers-hibernate-3.3/src/test/resources/testng.xml 2009-04-22 09:02:56 UTC (rev 16394)
@@ -45,6 +45,7 @@
<package name="org.hibernate.envers.test.integration.properties" />
<package name="org.hibernate.envers.test.integration.query" />
<package name="org.hibernate.envers.test.integration.query.ids" />
+ <package name="org.hibernate.envers.test.integration.reference" />
<package name="org.hibernate.envers.test.integration.reventity" />
<package name="org.hibernate.envers.test.integration.revfordate" />
<package name="org.hibernate.envers.test.integration.sameids" />
15 years, 7 months
Hibernate SVN: r16393 - in core/trunk/envers/src: main/java/org/hibernate/envers/entities/mapper/relation and 6 other directories.
by hibernate-commits@lists.jboss.org
Author: adamw
Date: 2009-04-22 04:38:05 -0400 (Wed, 22 Apr 2009)
New Revision: 16393
Added:
core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/reference/
core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/reference/BidirectionalReference.java
core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/reference/GreetingPO.java
core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/reference/GreetingSetPO.java
Modified:
core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/ComponentPropertyMapper.java
core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/ExtendedPropertyMapper.java
core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/MultiPropertyMapper.java
core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/PropertyMapper.java
core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/SinglePropertyMapper.java
core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/SubclassPropertyMapper.java
core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/AbstractCollectionMapper.java
core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/OneToOneNotOwningMapper.java
core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/ToOneIdMapper.java
core/trunk/envers/src/main/java/org/hibernate/envers/event/AuditEventListener.java
core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/AbstractAuditWorkUnit.java
core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/AddWorkUnit.java
core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/CollectionChangeWorkUnit.java
core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/DelWorkUnit.java
core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/ModWorkUnit.java
core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/PersistentCollectionChangeWorkUnit.java
core/trunk/envers/src/main/java/org/hibernate/envers/tools/Tools.java
core/trunk/envers/src/test/resources/testng.xml
Log:
HHH-3871:
- not loading proxied objects when not necessary
- test
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/ComponentPropertyMapper.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/ComponentPropertyMapper.java 2009-04-22 06:52:05 UTC (rev 16392)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/ComponentPropertyMapper.java 2009-04-22 08:38:05 UTC (rev 16393)
@@ -36,6 +36,7 @@
import org.hibernate.collection.PersistentCollection;
import org.hibernate.property.Setter;
import org.hibernate.util.ReflectHelper;
+import org.hibernate.engine.SessionImplementor;
/**
* @author Adam Warski (adam at warski dot org)
@@ -63,8 +64,8 @@
delegate.addComposite(propertyData, propertyMapper);
}
- public boolean mapToMapFromEntity(Map<String, Object> data, Object newObj, Object oldObj) {
- return delegate.mapToMapFromEntity(data, newObj, oldObj);
+ public boolean mapToMapFromEntity(SessionImplementor session, Map<String, Object> data, Object newObj, Object oldObj) {
+ return delegate.mapToMapFromEntity(session, data, newObj, oldObj);
}
public void mapToEntityFromMap(AuditConfiguration verCfg, Object obj, Map data, Object primaryKey, AuditReaderImplementor versionsReader, Number revision) {
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/ExtendedPropertyMapper.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/ExtendedPropertyMapper.java 2009-04-22 06:52:05 UTC (rev 16392)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/ExtendedPropertyMapper.java 2009-04-22 08:38:05 UTC (rev 16393)
@@ -23,11 +23,13 @@
*/
package org.hibernate.envers.entities.mapper;
+import org.hibernate.engine.SessionImplementor;
+
import java.util.Map;
/**
* @author Adam Warski (adam at warski dot org)
*/
public interface ExtendedPropertyMapper extends PropertyMapper, CompositeMapperBuilder {
- public boolean map(Map<String, Object> data, String[] propertyNames, Object[] newState, Object[] oldState);
+ public boolean map(SessionImplementor session, Map<String, Object> data, String[] propertyNames, Object[] newState, Object[] oldState);
}
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/MultiPropertyMapper.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/MultiPropertyMapper.java 2009-04-22 06:52:05 UTC (rev 16392)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/MultiPropertyMapper.java 2009-04-22 08:38:05 UTC (rev 16393)
@@ -36,6 +36,7 @@
import org.hibernate.collection.PersistentCollection;
import org.hibernate.property.Getter;
+import org.hibernate.engine.SessionImplementor;
/**
* @author Adam Warski (adam at warski dot org)
@@ -75,13 +76,13 @@
private Object getAtIndexOrNull(Object[] array, int index) { return array == null ? null : array[index]; }
- public boolean map(Map<String, Object> data, String[] propertyNames, Object[] newState, Object[] oldState) {
+ public boolean map(SessionImplementor session, Map<String, Object> data, String[] propertyNames, Object[] newState, Object[] oldState) {
boolean ret = false;
for (int i=0; i<propertyNames.length; i++) {
String propertyName = propertyNames[i];
if (propertyDatas.containsKey(propertyName)) {
- ret |= properties.get(propertyDatas.get(propertyName)).mapToMapFromEntity(data,
+ ret |= properties.get(propertyDatas.get(propertyName)).mapToMapFromEntity(session, data,
getAtIndexOrNull(newState, i),
getAtIndexOrNull(oldState, i));
}
@@ -90,7 +91,7 @@
return ret;
}
- public boolean mapToMapFromEntity(Map<String, Object> data, Object newObj, Object oldObj) {
+ public boolean mapToMapFromEntity(SessionImplementor session, Map<String, Object> data, Object newObj, Object oldObj) {
boolean ret = false;
for (PropertyData propertyData : properties.keySet()) {
Getter getter;
@@ -102,7 +103,7 @@
return false;
}
- ret |= properties.get(propertyData).mapToMapFromEntity(data,
+ ret |= properties.get(propertyData).mapToMapFromEntity(session, data,
newObj == null ? null : getter.get(newObj),
oldObj == null ? null : getter.get(oldObj));
}
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/PropertyMapper.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/PropertyMapper.java 2009-04-22 06:52:05 UTC (rev 16392)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/PropertyMapper.java 2009-04-22 08:38:05 UTC (rev 16393)
@@ -31,6 +31,7 @@
import org.hibernate.envers.reader.AuditReaderImplementor;
import org.hibernate.collection.PersistentCollection;
+import org.hibernate.engine.SessionImplementor;
/**
* @author Adam Warski (adam at warski dot org)
@@ -38,12 +39,13 @@
public interface PropertyMapper {
/**
* Maps properties to the given map, basing on differences between properties of new and old objects.
- * @param data Data to map to.
- * @param newObj New state of the entity.
- * @param oldObj Old state of the entity.
- * @return True if there are any differences between the states represented by newObj and oldObj.
+ * @param session The current session.
+ * @param data Data to map to.
+ * @param newObj New state of the entity.
+ * @param oldObj Old state of the entity.
+ * @return True if there are any differences between the states represented by newObj and oldObj.
*/
- boolean mapToMapFromEntity(Map<String, Object> data, Object newObj, Object oldObj);
+ boolean mapToMapFromEntity(SessionImplementor session, Map<String, Object> data, Object newObj, Object oldObj);
/**
* Maps properties from the given map to the given object.
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/SinglePropertyMapper.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/SinglePropertyMapper.java 2009-04-22 06:52:05 UTC (rev 16392)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/SinglePropertyMapper.java 2009-04-22 08:38:05 UTC (rev 16393)
@@ -36,6 +36,7 @@
import org.hibernate.collection.PersistentCollection;
import org.hibernate.property.Setter;
+import org.hibernate.engine.SessionImplementor;
/**
* TODO: diff
@@ -54,7 +55,7 @@
this.propertyData = propertyData;
}
- public boolean mapToMapFromEntity(Map<String, Object> data, Object newObj, Object oldObj) {
+ public boolean mapToMapFromEntity(SessionImplementor session, Map<String, Object> data, Object newObj, Object oldObj) {
data.put(propertyData.getName(), newObj);
return !Tools.objectsEqual(newObj, oldObj);
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/SubclassPropertyMapper.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/SubclassPropertyMapper.java 2009-04-22 06:52:05 UTC (rev 16392)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/SubclassPropertyMapper.java 2009-04-22 08:38:05 UTC (rev 16393)
@@ -32,6 +32,7 @@
import org.hibernate.envers.reader.AuditReaderImplementor;
import org.hibernate.collection.PersistentCollection;
+import org.hibernate.engine.SessionImplementor;
/**
* A mapper which maps from a parent mapper and a "main" one, but adds only to the "main". The "main" mapper
@@ -47,16 +48,16 @@
this.parentMapper = parentMapper;
}
- public boolean map(Map<String, Object> data, String[] propertyNames, Object[] newState, Object[] oldState) {
- boolean parentDiffs = parentMapper.map(data, propertyNames, newState, oldState);
- boolean mainDiffs = main.map(data, propertyNames, newState, oldState);
+ public boolean map(SessionImplementor session, Map<String, Object> data, String[] propertyNames, Object[] newState, Object[] oldState) {
+ boolean parentDiffs = parentMapper.map(session, data, propertyNames, newState, oldState);
+ boolean mainDiffs = main.map(session, data, propertyNames, newState, oldState);
return parentDiffs || mainDiffs;
}
- public boolean mapToMapFromEntity(Map<String, Object> data, Object newObj, Object oldObj) {
- boolean parentDiffs = parentMapper.mapToMapFromEntity(data, newObj, oldObj);
- boolean mainDiffs = main.mapToMapFromEntity(data, newObj, oldObj);
+ public boolean mapToMapFromEntity(SessionImplementor session, Map<String, Object> data, Object newObj, Object oldObj) {
+ boolean parentDiffs = parentMapper.mapToMapFromEntity(session, data, newObj, oldObj);
+ boolean mainDiffs = main.mapToMapFromEntity(session, data, newObj, oldObj);
return parentDiffs || mainDiffs;
}
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/AbstractCollectionMapper.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/AbstractCollectionMapper.java 2009-04-22 06:52:05 UTC (rev 16392)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/AbstractCollectionMapper.java 2009-04-22 08:38:05 UTC (rev 16393)
@@ -45,6 +45,7 @@
import org.hibernate.collection.PersistentCollection;
import org.hibernate.property.Setter;
+import org.hibernate.engine.SessionImplementor;
/**
* @author Adam Warski (adam at warski dot org)
@@ -130,7 +131,7 @@
return collectionChanges;
}
- public boolean mapToMapFromEntity(Map<String, Object> data, Object newObj, Object oldObj) {
+ public boolean mapToMapFromEntity(SessionImplementor session, Map<String, Object> data, Object newObj, Object oldObj) {
// Changes are mapped in the "mapCollectionChanges" method.
return false;
}
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/OneToOneNotOwningMapper.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/OneToOneNotOwningMapper.java 2009-04-22 06:52:05 UTC (rev 16392)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/OneToOneNotOwningMapper.java 2009-04-22 08:38:05 UTC (rev 16393)
@@ -38,6 +38,7 @@
import org.hibernate.envers.tools.reflection.ReflectionTools;
import org.hibernate.NonUniqueResultException;
+import org.hibernate.engine.SessionImplementor;
import org.hibernate.collection.PersistentCollection;
import org.hibernate.property.Setter;
@@ -56,7 +57,7 @@
this.propertyData = propertyData;
}
- public boolean mapToMapFromEntity(Map<String, Object> data, Object newObj, Object oldObj) {
+ public boolean mapToMapFromEntity(SessionImplementor session, Map<String, Object> data, Object newObj, Object oldObj) {
return false;
}
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/ToOneIdMapper.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/ToOneIdMapper.java 2009-04-22 06:52:05 UTC (rev 16392)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/ToOneIdMapper.java 2009-04-22 08:38:05 UTC (rev 16393)
@@ -40,6 +40,7 @@
import org.hibernate.collection.PersistentCollection;
import org.hibernate.property.Setter;
+import org.hibernate.engine.SessionImplementor;
/**
* @author Adam Warski (adam at warski dot org)
@@ -55,13 +56,13 @@
this.referencedEntityName = referencedEntityName;
}
- public boolean mapToMapFromEntity(Map<String, Object> data, Object newObj, Object oldObj) {
+ public boolean mapToMapFromEntity(SessionImplementor session, Map<String, Object> data, Object newObj, Object oldObj) {
HashMap<String, Object> newData = new HashMap<String, Object>();
data.put(propertyData.getName(), newData);
delegate.mapToMapFromEntity(newData, newObj);
- return !Tools.objectsEqual(newObj, oldObj);
+ return !Tools.entitiesEqual(session, newObj, oldObj);
}
public void mapToEntityFromMap(AuditConfiguration verCfg, Object obj, Map data, Object primaryKey,
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/event/AuditEventListener.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/event/AuditEventListener.java 2009-04-22 06:52:05 UTC (rev 16392)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/event/AuditEventListener.java 2009-04-22 08:38:05 UTC (rev 16393)
@@ -90,41 +90,49 @@
Object oldValue = oldState == null ? null : oldState[i];
Object newValue = newState == null ? null : newState[i];
- if (!Tools.objectsEqual(oldValue, newValue)) {
+ if (!Tools.entitiesEqual(session, oldValue, newValue)) {
// We have to generate changes both in the old collection (size decreses) and new collection
// (size increases).
if (newValue != null) {
// relDesc.getToEntityName() doesn't always return the entity name of the value - in case
// of subclasses, this will be root class, no the actual class. So it can't be used here.
String toEntityName;
- if(newValue instanceof HibernateProxy) {
+ Serializable id;
+
+ if (newValue instanceof HibernateProxy) {
HibernateProxy hibernateProxy = (HibernateProxy) newValue;
toEntityName = session.bestGuessEntityName(newValue);
- newValue = hibernateProxy.getHibernateLazyInitializer().getImplementation();
+ id = hibernateProxy.getHibernateLazyInitializer().getIdentifier();
+ // We've got to initialize the object from the proxy to later read its state.
+ newValue = Tools.getTargetFromProxy(hibernateProxy);
} else {
toEntityName = session.guessEntityName(newValue);
+
+ IdMapper idMapper = verCfg.getEntCfg().get(toEntityName).getIdMapper();
+ id = (Serializable) idMapper.mapToIdFromEntity(newValue);
}
- IdMapper idMapper = verCfg.getEntCfg().get(toEntityName).getIdMapper();
-
- Serializable id = (Serializable) idMapper.mapToIdFromEntity(newValue);
- verSync.addWorkUnit(new CollectionChangeWorkUnit(toEntityName, verCfg, id, newValue));
+ verSync.addWorkUnit(new CollectionChangeWorkUnit(session, toEntityName, verCfg, id, newValue));
}
if (oldValue != null) {
String toEntityName;
+ Serializable id;
+
if(oldValue instanceof HibernateProxy) {
HibernateProxy hibernateProxy = (HibernateProxy) oldValue;
toEntityName = session.bestGuessEntityName(oldValue);
- oldValue = hibernateProxy.getHibernateLazyInitializer().getImplementation();
+ id = hibernateProxy.getHibernateLazyInitializer().getIdentifier();
+ // We've got to initialize the object as we'll read it's state anyway.
+ oldValue = Tools.getTargetFromProxy(hibernateProxy);
} else {
toEntityName = session.guessEntityName(oldValue);
+
+ IdMapper idMapper = verCfg.getEntCfg().get(toEntityName).getIdMapper();
+ id = (Serializable) idMapper.mapToIdFromEntity(oldValue);
}
-
- IdMapper idMapper = verCfg.getEntCfg().get(toEntityName).getIdMapper();
-
- Serializable id = (Serializable) idMapper.mapToIdFromEntity(oldValue);
- verSync.addWorkUnit(new CollectionChangeWorkUnit(toEntityName, verCfg, id, oldValue));
+
+ verSync.addWorkUnit(new CollectionChangeWorkUnit(session, toEntityName, verCfg, id, oldValue));
}
}
}
@@ -137,8 +145,8 @@
if (verCfg.getEntCfg().isVersioned(entityName)) {
AuditSync verSync = verCfg.getSyncManager().get(event.getSession());
- verSync.addWorkUnit(new AddWorkUnit(event.getPersister().getEntityName(), verCfg, event.getId(),
- event.getPersister(), event.getState()));
+ verSync.addWorkUnit(new AddWorkUnit(event.getSession(), event.getPersister().getEntityName(), verCfg,
+ event.getId(), event.getPersister(), event.getState()));
generateBidirectionalCollectionChangeWorkUnits(verSync, event.getPersister(), entityName, event.getState(),
null, event.getSession());
@@ -151,8 +159,8 @@
if (verCfg.getEntCfg().isVersioned(entityName)) {
AuditSync verSync = verCfg.getSyncManager().get(event.getSession());
- verSync.addWorkUnit(new ModWorkUnit(event.getPersister().getEntityName(), verCfg, event.getId(),
- event.getPersister(), event.getState(), event.getOldState()));
+ verSync.addWorkUnit(new ModWorkUnit(event.getSession(), event.getPersister().getEntityName(), verCfg,
+ event.getId(), event.getPersister(), event.getState(), event.getOldState()));
generateBidirectionalCollectionChangeWorkUnits(verSync, event.getPersister(), entityName, event.getState(),
event.getOldState(), event.getSession());
@@ -165,7 +173,8 @@
if (verCfg.getEntCfg().isVersioned(entityName)) {
AuditSync verSync = verCfg.getSyncManager().get(event.getSession());
- verSync.addWorkUnit(new DelWorkUnit(event.getPersister().getEntityName(), verCfg, event.getId()));
+ verSync.addWorkUnit(new DelWorkUnit(event.getSession(), event.getPersister().getEntityName(), verCfg,
+ event.getId()));
generateBidirectionalCollectionChangeWorkUnits(verSync, event.getPersister(), entityName, null,
event.getDeletedState(), event.getSession());
@@ -193,7 +202,8 @@
Object relatedObj = changeData.getChangedElement();
Serializable relatedId = (Serializable) relatedIdMapper.mapToIdFromEntity(relatedObj);
- verSync.addWorkUnit(new CollectionChangeWorkUnit(relatedEntityName, verCfg, relatedId, relatedObj));
+ verSync.addWorkUnit(new CollectionChangeWorkUnit(event.getSession(), relatedEntityName, verCfg,
+ relatedId, relatedObj));
}
}
}
@@ -205,14 +215,14 @@
if (verCfg.getEntCfg().isVersioned(entityName)) {
AuditSync verSync = verCfg.getSyncManager().get(event.getSession());
- PersistentCollectionChangeWorkUnit workUnit = new PersistentCollectionChangeWorkUnit(entityName, verCfg,
- newColl, collectionEntry, oldColl, event.getAffectedOwnerIdOrNull());
+ PersistentCollectionChangeWorkUnit workUnit = new PersistentCollectionChangeWorkUnit(event.getSession(),
+ entityName, verCfg, newColl, collectionEntry, oldColl, event.getAffectedOwnerIdOrNull());
verSync.addWorkUnit(workUnit);
if (workUnit.containsWork()) {
// There are some changes: a revision needs also be generated for the collection owner
- verSync.addWorkUnit(new CollectionChangeWorkUnit(event.getAffectedOwnerEntityName(), verCfg,
- event.getAffectedOwnerIdOrNull(), event.getAffectedOwnerOrNull()));
+ verSync.addWorkUnit(new CollectionChangeWorkUnit(event.getSession(), event.getAffectedOwnerEntityName(),
+ verCfg, event.getAffectedOwnerIdOrNull(), event.getAffectedOwnerOrNull()));
generateBidirectionalCollectionChangeWorkUnits(verSync, event, workUnit);
}
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/AbstractAuditWorkUnit.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/AbstractAuditWorkUnit.java 2009-04-22 06:52:05 UTC (rev 16392)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/AbstractAuditWorkUnit.java 2009-04-22 08:38:05 UTC (rev 16393)
@@ -32,11 +32,13 @@
import org.hibernate.envers.configuration.AuditEntitiesConfiguration;
import org.hibernate.Session;
+import org.hibernate.engine.SessionImplementor;
/**
* @author Adam Warski (adam at warski dot org)
*/
public abstract class AbstractAuditWorkUnit implements AuditWorkUnit {
+ protected final SessionImplementor sessionImplementor;
protected final AuditConfiguration verCfg;
protected final Serializable id;
@@ -44,7 +46,9 @@
private Object performedData;
- protected AbstractAuditWorkUnit(String entityName, AuditConfiguration verCfg, Serializable id) {
+ protected AbstractAuditWorkUnit(SessionImplementor sessionImplementor, String entityName, AuditConfiguration verCfg,
+ Serializable id) {
+ this.sessionImplementor = sessionImplementor;
this.verCfg = verCfg;
this.id = id;
this.entityName = entityName;
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/AddWorkUnit.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/AddWorkUnit.java 2009-04-22 06:52:05 UTC (rev 16392)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/AddWorkUnit.java 2009-04-22 08:38:05 UTC (rev 16393)
@@ -31,6 +31,7 @@
import org.hibernate.envers.configuration.AuditConfiguration;
import org.hibernate.Session;
+import org.hibernate.engine.SessionImplementor;
import org.hibernate.persister.entity.EntityPersister;
/**
@@ -40,9 +41,9 @@
private final Object[] state;
private final String[] propertyNames;
- public AddWorkUnit(String entityName, AuditConfiguration verCfg, Serializable id,
- EntityPersister entityPersister, Object[] state) {
- super(entityName, verCfg, id);
+ public AddWorkUnit(SessionImplementor sessionImplementor, String entityName, AuditConfiguration verCfg,
+ Serializable id, EntityPersister entityPersister, Object[] state) {
+ super(sessionImplementor, entityName, verCfg, id);
this.state = state;
this.propertyNames = entityPersister.getPropertyNames();
@@ -56,7 +57,8 @@
Map<String, Object> data = new HashMap<String, Object>();
fillDataWithId(data, revisionData, RevisionType.ADD);
- verCfg.getEntCfg().get(getEntityName()).getPropertyMapper().map(data, propertyNames, state, null);
+ verCfg.getEntCfg().get(getEntityName()).getPropertyMapper().map(sessionImplementor, data,
+ propertyNames, state, null);
session.save(verCfg.getAuditEntCfg().getAuditEntityName(getEntityName()), data);
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/CollectionChangeWorkUnit.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/CollectionChangeWorkUnit.java 2009-04-22 06:52:05 UTC (rev 16392)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/CollectionChangeWorkUnit.java 2009-04-22 08:38:05 UTC (rev 16393)
@@ -31,6 +31,7 @@
import org.hibernate.envers.configuration.AuditConfiguration;
import org.hibernate.Session;
+import org.hibernate.engine.SessionImplementor;
/**
* @author Adam Warski (adam at warski dot org)
@@ -38,8 +39,9 @@
public class CollectionChangeWorkUnit extends AbstractAuditWorkUnit implements AuditWorkUnit {
private final Object entity;
- public CollectionChangeWorkUnit(String entityName, AuditConfiguration verCfg, Serializable id, Object entity) {
- super(entityName, verCfg, id);
+ public CollectionChangeWorkUnit(SessionImplementor session, String entityName, AuditConfiguration verCfg,
+ Serializable id, Object entity) {
+ super(session, entityName, verCfg, id);
this.entity = entity;
}
@@ -52,7 +54,8 @@
Map<String, Object> data = new HashMap<String, Object>();
fillDataWithId(data, revisionData, RevisionType.MOD);
- verCfg.getEntCfg().get(getEntityName()).getPropertyMapper().mapToMapFromEntity(data, entity, null);
+ verCfg.getEntCfg().get(getEntityName()).getPropertyMapper().mapToMapFromEntity(sessionImplementor,
+ data, entity, null);
session.save(verCfg.getAuditEntCfg().getAuditEntityName(getEntityName()), data);
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/DelWorkUnit.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/DelWorkUnit.java 2009-04-22 06:52:05 UTC (rev 16392)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/DelWorkUnit.java 2009-04-22 08:38:05 UTC (rev 16393)
@@ -31,13 +31,14 @@
import org.hibernate.envers.configuration.AuditConfiguration;
import org.hibernate.Session;
+import org.hibernate.engine.SessionImplementor;
/**
* @author Adam Warski (adam at warski dot org)
*/
public class DelWorkUnit extends AbstractAuditWorkUnit implements AuditWorkUnit {
- public DelWorkUnit(String entityName, AuditConfiguration verCfg, Serializable id) {
- super(entityName, verCfg, id);
+ public DelWorkUnit(SessionImplementor sessionImplementor, String entityName, AuditConfiguration verCfg, Serializable id) {
+ super(sessionImplementor, entityName, verCfg, id);
}
public boolean containsWork() {
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/ModWorkUnit.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/ModWorkUnit.java 2009-04-22 06:52:05 UTC (rev 16392)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/ModWorkUnit.java 2009-04-22 08:38:05 UTC (rev 16393)
@@ -31,6 +31,7 @@
import org.hibernate.envers.configuration.AuditConfiguration;
import org.hibernate.Session;
+import org.hibernate.engine.SessionImplementor;
import org.hibernate.persister.entity.EntityPersister;
/**
@@ -40,13 +41,13 @@
private final Map<String, Object> data;
private final boolean changes;
- public ModWorkUnit(String entityName, AuditConfiguration verCfg, Serializable id,
- EntityPersister entityPersister, Object[] newState, Object[] oldState) {
- super(entityName, verCfg, id);
+ public ModWorkUnit(SessionImplementor sessionImplementor, String entityName, AuditConfiguration verCfg,
+ Serializable id, EntityPersister entityPersister, Object[] newState, Object[] oldState) {
+ super(sessionImplementor, entityName, verCfg, id);
data = new HashMap<String, Object>();
- changes = verCfg.getEntCfg().get(getEntityName()).getPropertyMapper().map(data, entityPersister.getPropertyNames(),
- newState, oldState);
+ changes = verCfg.getEntCfg().get(getEntityName()).getPropertyMapper().map(sessionImplementor, data,
+ entityPersister.getPropertyNames(), newState, oldState);
}
public boolean containsWork() {
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/PersistentCollectionChangeWorkUnit.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/PersistentCollectionChangeWorkUnit.java 2009-04-22 06:52:05 UTC (rev 16392)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/PersistentCollectionChangeWorkUnit.java 2009-04-22 08:38:05 UTC (rev 16393)
@@ -34,6 +34,7 @@
import org.hibernate.Session;
import org.hibernate.persister.collection.AbstractCollectionPersister;
import org.hibernate.engine.CollectionEntry;
+import org.hibernate.engine.SessionImplementor;
import org.hibernate.collection.PersistentCollection;
/**
@@ -43,10 +44,10 @@
private final List<PersistentCollectionChangeData> collectionChanges;
private final String referencingPropertyName;
- public PersistentCollectionChangeWorkUnit(String entityName, AuditConfiguration verCfg,
- PersistentCollection collection, CollectionEntry collectionEntry,
- Serializable snapshot, Serializable id) {
- super(entityName, verCfg, null);
+ public PersistentCollectionChangeWorkUnit(SessionImplementor sessionImplementor, String entityName,
+ AuditConfiguration verCfg, PersistentCollection collection,
+ CollectionEntry collectionEntry, Serializable snapshot, Serializable id) {
+ super(sessionImplementor, entityName, verCfg, null);
String ownerEntityName = ((AbstractCollectionPersister) collectionEntry.getLoadedPersister()).getOwnerEntityName();
referencingPropertyName = collectionEntry.getRole().substring(ownerEntityName.length() + 1);
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/tools/Tools.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/tools/Tools.java 2009-04-22 06:52:05 UTC (rev 16392)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/tools/Tools.java 2009-04-22 08:38:05 UTC (rev 16393)
@@ -23,6 +23,10 @@
*/
package org.hibernate.envers.tools;
+import org.hibernate.proxy.HibernateProxy;
+import org.hibernate.engine.SessionImplementor;
+import org.hibernate.Session;
+
import java.util.*;
/**
@@ -41,6 +45,42 @@
return new LinkedHashMap<K,V>();
}
+ public static boolean entitiesEqual(SessionImplementor session, Object obj1, Object obj2) {
+ Object id1 = getIdentifier(session, obj1);
+ Object id2 = getIdentifier(session, obj2);
+
+ return objectsEqual(id1, id2);
+ }
+
+ public static Object getIdentifier(SessionImplementor session, Object obj) {
+ if (obj == null) {
+ return null;
+ }
+
+ if (obj instanceof HibernateProxy) {
+ HibernateProxy hibernateProxy = (HibernateProxy) obj;
+ return hibernateProxy.getHibernateLazyInitializer().getIdentifier();
+ }
+
+
+ return session.getEntityPersister(null, obj).getIdentifier(obj, session.getEntityMode());
+ }
+
+ public static Object getTargetFromProxy(HibernateProxy proxy) {
+ if (!proxy.getHibernateLazyInitializer().isUninitialized()) {
+ return proxy.getHibernateLazyInitializer().getImplementation();
+ }
+
+ Session tempSession = proxy.getHibernateLazyInitializer().getSession().getFactory().openTemporarySession();
+ try {
+ proxy.getHibernateLazyInitializer().setSession((SessionImplementor) tempSession);
+ proxy.getHibernateLazyInitializer().initialize();
+ return proxy.getHibernateLazyInitializer().getImplementation();
+ } finally {
+ tempSession.close();
+ }
+ }
+
public static boolean objectsEqual(Object obj1, Object obj2) {
if (obj1 == null) {
return obj2 == null;
Copied: core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/reference/BidirectionalReference.java (from rev 16165, core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicList.java)
===================================================================
--- core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/reference/BidirectionalReference.java (rev 0)
+++ core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/reference/BidirectionalReference.java 2009-04-22 08:38:05 UTC (rev 16393)
@@ -0,0 +1,150 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.envers.test.integration.reference;
+
+import org.hibernate.ejb.Ejb3Configuration;
+import org.hibernate.envers.test.AbstractEntityTest;
+import org.hibernate.envers.test.tools.TestTools;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+import javax.persistence.EntityManager;
+import java.util.Arrays;
+
+/**
+ * @author Adam Warski (adam at warski dot org)
+ */
+public class BidirectionalReference extends AbstractEntityTest {
+ private Long set1_id;
+ private Long set2_id;
+
+ private Long g1_id;
+
+ public void configure(Ejb3Configuration cfg) {
+ cfg.addAnnotatedClass(GreetingPO.class);
+ cfg.addAnnotatedClass(GreetingSetPO.class);
+ }
+
+ @BeforeClass(dependsOnMethods = "init")
+ public void initData() {
+ EntityManager em = getEntityManager();
+
+ GreetingSetPO set1 = new GreetingSetPO();
+ set1.setName("a1");
+
+ GreetingSetPO set2 = new GreetingSetPO();
+ set2.setName("a2");
+
+ // Revision 1
+ em.getTransaction().begin();
+
+ em.persist(set1);
+ em.persist(set2);
+
+ set1_id = set1.getId();
+ set2_id = set2.getId();
+
+ em.getTransaction().commit();
+ em.clear();
+
+ // Revision 2
+ em.getTransaction().begin();
+
+ GreetingPO g1 = new GreetingPO();
+ g1.setGreeting("g1");
+ g1.setGreetingSet(em.getReference(GreetingSetPO.class, set1_id));
+
+ em.persist(g1);
+ g1_id = g1.getId();
+
+ em.getTransaction().commit();
+ em.clear();
+
+ // Revision 3
+ em.getTransaction().begin();
+
+ g1 = em.find(GreetingPO.class, g1_id);
+
+ g1.setGreetingSet(em.getReference(GreetingSetPO.class, set2_id));
+
+ em.getTransaction().commit();
+ }
+
+ @Test
+ public void testRevisionsCounts() {
+ assert Arrays.asList(2, 3).equals(getAuditReader().getRevisions(GreetingPO.class, g1_id));
+
+ assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(GreetingSetPO.class, set1_id));
+ assert Arrays.asList(1, 3).equals(getAuditReader().getRevisions(GreetingSetPO.class, set2_id));
+ }
+
+ @Test
+ public void testHistoryOfG1() {
+ GreetingPO rev1 = getAuditReader().find(GreetingPO.class, g1_id, 1);
+ GreetingPO rev2 = getAuditReader().find(GreetingPO.class, g1_id, 2);
+ GreetingPO rev3 = getAuditReader().find(GreetingPO.class, g1_id, 3);
+
+ assert rev1 == null;
+ assert rev2.getGreetingSet().getName().equals("a1");
+ assert rev3.getGreetingSet().getName().equals("a2");
+ }
+
+ @Test
+ public void testHistoryOfSet1() {
+ GreetingSetPO rev1 = getAuditReader().find(GreetingSetPO.class, set1_id, 1);
+ GreetingSetPO rev2 = getAuditReader().find(GreetingSetPO.class, set1_id, 2);
+ GreetingSetPO rev3 = getAuditReader().find(GreetingSetPO.class, set1_id, 3);
+
+ assert rev1.getName().equals("a1");
+ assert rev2.getName().equals("a1");
+ assert rev3.getName().equals("a1");
+
+ GreetingPO g1 = new GreetingPO();
+ g1.setId(g1_id);
+ g1.setGreeting("g1");
+
+ assert rev1.getGreetings().size() == 0;
+ assert rev2.getGreetings().equals(TestTools.makeSet(g1));
+ assert rev3.getGreetings().size() == 0;
+ }
+
+ @Test
+ public void testHistoryOfSet2() {
+ GreetingSetPO rev1 = getAuditReader().find(GreetingSetPO.class, set2_id, 1);
+ GreetingSetPO rev2 = getAuditReader().find(GreetingSetPO.class, set2_id, 2);
+ GreetingSetPO rev3 = getAuditReader().find(GreetingSetPO.class, set2_id, 3);
+
+ assert rev1.getName().equals("a2");
+ assert rev2.getName().equals("a2");
+ assert rev3.getName().equals("a2");
+
+ GreetingPO g1 = new GreetingPO();
+ g1.setId(g1_id);
+ g1.setGreeting("g1");
+
+ assert rev1.getGreetings().size() == 0;
+ assert rev2.getGreetings().size() == 0;
+ assert rev3.getGreetings().equals(TestTools.makeSet(g1));
+ }
+}
\ No newline at end of file
Added: core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/reference/GreetingPO.java
===================================================================
--- core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/reference/GreetingPO.java (rev 0)
+++ core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/reference/GreetingPO.java 2009-04-22 08:38:05 UTC (rev 16393)
@@ -0,0 +1,65 @@
+package org.hibernate.envers.test.integration.reference;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+
+import org.hibernate.envers.Audited;
+
+@Entity
+@Audited
+public class GreetingPO {
+ @Id
+ @GeneratedValue
+ private Long id;
+
+ private String theGreeting;
+
+ @ManyToOne
+ private GreetingSetPO greetingSet;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getGreeting() {
+ return theGreeting;
+ }
+
+ public void setGreeting(String greeting) {
+ this.theGreeting = greeting;
+ }
+
+ public GreetingSetPO getGreetingSet() {
+ return greetingSet;
+ }
+
+ public void setGreetingSet(GreetingSetPO greetingSet) {
+ this.greetingSet = greetingSet;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof GreetingPO)) return false;
+
+ GreetingPO that = (GreetingPO) o;
+
+ if (id != null ? !id.equals(that.id) : that.id != null) return false;
+ if (theGreeting != null ? !theGreeting.equals(that.theGreeting) : that.theGreeting != null) return false;
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = id != null ? id.hashCode() : 0;
+ result = 31 * result + (theGreeting != null ? theGreeting.hashCode() : 0);
+ return result;
+ }
+}
\ No newline at end of file
Added: core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/reference/GreetingSetPO.java
===================================================================
--- core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/reference/GreetingSetPO.java (rev 0)
+++ core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/reference/GreetingSetPO.java 2009-04-22 08:38:05 UTC (rev 16393)
@@ -0,0 +1,67 @@
+package org.hibernate.envers.test.integration.reference;
+
+import java.util.Set;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+
+import org.hibernate.envers.Audited;
+
+@Entity
+@Audited
+public class GreetingSetPO {
+ @Id
+ @GeneratedValue
+ private Long id;
+
+ private String name;
+
+ @OneToMany(mappedBy = "greetingSet")
+ private Set<GreetingPO> greetings;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Set<GreetingPO> getGreetings() {
+ return greetings;
+ }
+
+ public void setGreetings(Set<GreetingPO> greetings) {
+ this.greetings = greetings;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof GreetingSetPO)) return false;
+
+ GreetingSetPO that = (GreetingSetPO) o;
+
+ if (id != null ? !id.equals(that.id) : that.id != null) return false;
+ if (name != null ? !name.equals(that.name) : that.name != null) return false;
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = id != null ? id.hashCode() : 0;
+ result = 31 * result + (name != null ? name.hashCode() : 0);
+ return result;
+ }
+}
\ No newline at end of file
Modified: core/trunk/envers/src/test/resources/testng.xml
===================================================================
--- core/trunk/envers/src/test/resources/testng.xml 2009-04-22 06:52:05 UTC (rev 16392)
+++ core/trunk/envers/src/test/resources/testng.xml 2009-04-22 08:38:05 UTC (rev 16393)
@@ -45,6 +45,7 @@
<package name="org.hibernate.envers.test.integration.properties" />
<package name="org.hibernate.envers.test.integration.query" />
<package name="org.hibernate.envers.test.integration.query.ids" />
+ <package name="org.hibernate.envers.test.integration.reference" />
<package name="org.hibernate.envers.test.integration.reventity" />
<package name="org.hibernate.envers.test.integration.revfordate" />
<package name="org.hibernate.envers.test.integration.sameids" />
15 years, 7 months