Hibernate SVN: r16061 - validator/tags.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-03-03 09:29:04 -0500 (Tue, 03 Mar 2009)
New Revision: 16061
Added:
validator/tags/v4_0_0_Alpha2/
Log:
Created tag v4_0_0_Alpha2.
Copied: validator/tags/v4_0_0_Alpha2 (from rev 16060, validator/trunk)
15 years, 10 months
Hibernate SVN: r16060 - in validator/trunk/hibernate-validator: src/main/assembly and 4 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-03-03 09:26:08 -0500 (Tue, 03 Mar 2009)
New Revision: 16060
Modified:
validator/trunk/hibernate-validator/pom.xml
validator/trunk/hibernate-validator/readme.txt
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/gettingstarted.xml
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ExecutionContext.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/ConstraintValidatorContextTest.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/DummyBean.java
Log:
HV-114 Changed the implementation so that property in addError(String message, String property) in ConstraintValidatorContext is relative to the current validation. Added test
Made sure the referenced versions of correct. Updated the NYI sections.
Modified: validator/trunk/hibernate-validator/pom.xml
===================================================================
--- validator/trunk/hibernate-validator/pom.xml 2009-03-03 11:29:09 UTC (rev 16059)
+++ validator/trunk/hibernate-validator/pom.xml 2009-03-03 14:26:08 UTC (rev 16060)
@@ -22,7 +22,7 @@
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
- <version>1.0.Beta4-SNAPSHOT</version>
+ <version>1.0.Beta4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
Modified: validator/trunk/hibernate-validator/readme.txt
===================================================================
--- validator/trunk/hibernate-validator/readme.txt 2009-03-03 11:29:09 UTC (rev 16059)
+++ validator/trunk/hibernate-validator/readme.txt 2009-03-03 14:26:08 UTC (rev 16060)
@@ -22,14 +22,13 @@
This is an alpha release and not feature complete in relation to the latest version
of JSR 303. The following features are not yet fully implemented:
- - Group inheritance using interfaces and implicit grouping
+ - Implicit grouping
- Implementation of the TraversableResolver interface to allow integration with JPA
- - Polymorphism in graph validation
- XML configuration
You can find more information about the current state of the implementation on the
Bean Validation RI Roadmap - http://www.hibernate.org/459.html and there is copy of
- JSR as of the time of this release available here - http://in.relation.to/service/File/10678
+ JSR as of the time of this release available here - http://in.relation.to/service/File/10774
Documentation
-------------
@@ -61,7 +60,7 @@
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
- <version>x.y.z</version>
+ <version>${project.version}</version>
</dependency>
Hibernate Validator can be found in this repository: http://repository.jboss.com/maven2/
Modified: validator/trunk/hibernate-validator/src/main/assembly/dist.xml
===================================================================
--- validator/trunk/hibernate-validator/src/main/assembly/dist.xml 2009-03-03 11:29:09 UTC (rev 16059)
+++ validator/trunk/hibernate-validator/src/main/assembly/dist.xml 2009-03-03 14:26:08 UTC (rev 16060)
@@ -34,6 +34,18 @@
</dependencySet>
</dependencySets>
+ <files>
+ <file>
+ <source>readme.txt</source>
+ <outputDirectory>/</outputDirectory>
+ <filtered>true</filtered>
+ </file>
+ <file>
+ <source>license.txt</source>
+ <outputDirectory>/</outputDirectory>
+ </file>
+ </files>
+
<fileSets>
<fileSet>
<directory>target</directory>
@@ -55,6 +67,7 @@
<outputDirectory></outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
<excludes>
+ <exclude>*.txt</exclude>
<exclude>**/target/**</exclude>
<exclude>*.iml</exclude>
</excludes>
Modified: validator/trunk/hibernate-validator/src/main/docbook/en-US/master.xml
===================================================================
--- validator/trunk/hibernate-validator/src/main/docbook/en-US/master.xml 2009-03-03 11:29:09 UTC (rev 16059)
+++ validator/trunk/hibernate-validator/src/main/docbook/en-US/master.xml 2009-03-03 14:26:08 UTC (rev 16060)
@@ -69,12 +69,12 @@
implementation nor this documenation is complete. However, implementation
should be in a state allowing first experiments with this new API. The
following list shows the missing features in relation to the <ulink
- url="http://in.relation.to/service/File/10678">1.0.Beta3 version of JSR
+ url="http://in.relation.to/service/File/10774">1.0.Beta4 version of JSR
303</ulink> :</para>
<itemizedlist>
<listitem>
- <para>Group inheritance using interfaces and implicit grouping</para>
+ <para>Implicit grouping</para>
</listitem>
<listitem>
@@ -83,10 +83,6 @@
</listitem>
<listitem>
- <para>Polymorphism in graph validation</para>
- </listitem>
-
- <listitem>
<para>XML configuration</para>
</listitem>
</itemizedlist>
Modified: validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/gettingstarted.xml
===================================================================
--- validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/gettingstarted.xml 2009-03-03 11:29:09 UTC (rev 16059)
+++ validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/gettingstarted.xml 2009-03-03 14:26:08 UTC (rev 16060)
@@ -357,7 +357,7 @@
<para>That concludes our 5 minute tour through the world of the Bean
Validation RI. We will complete this documentation in our coming releases.
For now we recommend to refer to the JSR 303 specification directly for
- more examples. The 1.0.Beta3 version of this specification is available
- <ulink url="http://in.relation.to/service/File/10678">here</ulink>.</para>
+ more examples. The 1.0.Beta4 version of this specification is available
+ <ulink url="http://in.relation.to/service/File/10774">here</ulink>.</para>
</section>
</chapter>
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-03-03 11:29:09 UTC (rev 16059)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ExecutionContext.java 2009-03-03 14:26:08 UTC (rev 16060)
@@ -43,6 +43,8 @@
private static final String PROPERTY_ROOT = "";
+ private static final String PROPERTY_PATH_SEPERATOR = ".";
+
/**
* The root bean of the validation.
*/
@@ -76,7 +78,7 @@
private ValidatedProperty currentValidatedProperty;
/**
- * Stack for keeping track of the currently validated bean.
+ * Stack for keeping track of the currently validated bean.
*/
private Stack<Object> beanStack = new Stack<Object>();
@@ -207,8 +209,8 @@
* @param property the new property to add to the current path.
*/
public void pushProperty(String property) {
+ currentValidatedProperty = new ValidatedProperty( peekPropertyPath(), property );
propertyPath.add( property );
- currentValidatedProperty = new ValidatedProperty( peekPropertyPath() );
}
/**
@@ -238,10 +240,12 @@
public String peekPropertyPath() {
StringBuilder builder = new StringBuilder();
- for ( String s : propertyPath ) {
- builder.append( s ).append( "." );
+ for ( int i = 0; i <= propertyPath.size() - 1; i++ ) {
+ builder.append( propertyPath.get( i ) );
+ if ( i < propertyPath.size() - 1 ) {
+ builder.append( PROPERTY_PATH_SEPERATOR );
+ }
}
- builder.delete( builder.lastIndexOf( "." ), builder.length() );
return builder.toString();
}
@@ -297,13 +301,15 @@
class ValidatedProperty {
private final List<ErrorMessage> errorMessages = new ArrayList<ErrorMessage>( 3 );
+ private final String property;
+ private final String propertyParent;
private ConstraintDescriptor constraintDescriptor;
private boolean defaultDisabled;
- private String property;
- private ValidatedProperty(String property) {
+ private ValidatedProperty(String propertyParent, String property) {
this.property = property;
+ this.propertyParent = propertyParent;
}
public void setConstraintDescriptor(ConstraintDescriptor constraintDescriptor) {
@@ -327,20 +333,31 @@
}
public void addError(String message) {
- errorMessages.add( new ErrorMessage( message, property ) );
+ errorMessages.add( new ErrorMessage( message, buildPropertyPath( propertyParent, property ) ) );
}
public void addError(String message, String property) {
- errorMessages.add( new ErrorMessage( message, property ) );
+ errorMessages.add( new ErrorMessage( message, buildPropertyPath( propertyParent, property ) ) );
}
public List<ErrorMessage> getErrorMessages() {
List<ErrorMessage> returnedErrorMessages = new ArrayList<ErrorMessage>( errorMessages );
if ( !defaultDisabled ) {
- returnedErrorMessages.add( new ErrorMessage( getDefaultErrorMessage(), property ) );
+ returnedErrorMessages.add(
+ new ErrorMessage( getDefaultErrorMessage(), buildPropertyPath( propertyParent, property ) )
+ );
}
return returnedErrorMessages;
}
+
+ private String buildPropertyPath(String parent, String leaf) {
+ if ( PROPERTY_ROOT.equals( parent ) ) {
+ return leaf;
+ }
+ else {
+ return new StringBuilder().append( parent ).append( PROPERTY_PATH_SEPERATOR ).append( leaf ).toString();
+ }
+ }
}
public class ErrorMessage {
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/ConstraintValidatorContextTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/ConstraintValidatorContextTest.java 2009-03-03 11:29:09 UTC (rev 16059)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/ConstraintValidatorContextTest.java 2009-03-03 14:26:08 UTC (rev 16060)
@@ -1,4 +1,4 @@
-// $Id:$
+// $Id$
/*
* JBoss, Home of Professional Open Source
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
@@ -23,6 +23,8 @@
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
+import static junit.framework.Assert.assertTrue;
+import static junit.framework.Assert.fail;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
@@ -37,6 +39,9 @@
public void testNoCustomization() {
Validator validator = TestUtil.getValidator();
+ DummyValidator.disableDefaultError( false );
+ DummyValidator.setErrorMessages( null );
+
DummyBean bean = new DummyBean( "foobar" );
Set<ConstraintViolation<DummyBean>> constraintViolations = validator.validate( bean );
@@ -52,9 +57,12 @@
public void testDisableDefaultErrorWithoutCustomError() {
Validator validator = TestUtil.getValidator();
- DummyBean bean = new DummyBean( "foobar" );
DummyValidator.disableDefaultError( true );
+ Map<String, String> errors = new HashMap<String, String>();
+ DummyValidator.setErrorMessages( errors );
+ DummyBean bean = new DummyBean( "foobar" );
+
Set<ConstraintViolation<DummyBean>> constraintViolations = validator.validate( bean );
assertEquals( "Wrong number of constraints", 0, constraintViolations.size() );
}
@@ -63,16 +71,46 @@
public void testDisableDefaultErrorWithCustomErrors() {
Validator validator = TestUtil.getValidator();
- DummyBean bean = new DummyBean( "foobar" );
DummyValidator.disableDefaultError( true );
Map<String, String> errors = new HashMap<String, String>();
errors.put( "message1", "property1" );
DummyValidator.setErrorMessages( errors );
+ DummyBean bean = new DummyBean( "foobar" );
+
Set<ConstraintViolation<DummyBean>> constraintViolations = validator.validate( bean );
assertEquals( "Wrong number of constraints", 1, constraintViolations.size() );
ConstraintViolation constraintViolation = constraintViolations.iterator().next();
assertEquals( "Wrong message", "message1", constraintViolation.getMessage() );
assertEquals( "Wrong property", "property1", constraintViolation.getPropertyPath() );
}
+
+ @Test
+ public void testNestedValidation() {
+ Validator validator = TestUtil.getValidator();
+
+ DummyValidator.disableDefaultError( false );
+ DummyValidator.setErrorMessages( null );
+
+ DummyBean bean = new DummyBean( "foo" );
+ bean.setNestedDummy( new DummyBean( "bar" ) );
+
+ Set<ConstraintViolation<DummyBean>> constraintViolations = validator.validate( bean );
+ assertEquals( "Wrong number of constraints", 2, constraintViolations.size() );
+ boolean validatedNestedBean = false;
+ for ( ConstraintViolation<DummyBean> violation : constraintViolations ) {
+
+ if ( violation.getPropertyPath().equals( "value" ) ) {
+ assertEquals( "Wrong message", "dummy message", violation.getMessage() );
+ }
+ else if ( violation.getPropertyPath().equals( "nestedDummy.value" ) ) {
+ assertEquals( "Wrong message", "dummy message", violation.getMessage() );
+ validatedNestedBean = true;
+ }
+ else {
+ fail( "Wrong property " + violation.getMessage() );
+ }
+ }
+ assertTrue( validatedNestedBean );
+ }
}
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/DummyBean.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/DummyBean.java 2009-03-03 11:29:09 UTC (rev 16059)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/DummyBean.java 2009-03-03 14:26:08 UTC (rev 16060)
@@ -1,4 +1,4 @@
-// $Id:$
+// $Id$
/*
* JBoss, Home of Professional Open Source
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
@@ -17,6 +17,8 @@
*/
package org.hibernate.validation.constraints.validatorcontext;
+import javax.validation.Valid;
+
/**
* @author Hardy Ferentschik
*/
@@ -25,7 +27,14 @@
@Dummy
String value;
+ @Valid
+ DummyBean nestedDummy;
+
public DummyBean(String value) {
this.value = value;
}
+
+ public void setNestedDummy(DummyBean nestedDummy) {
+ this.nestedDummy = nestedDummy;
+ }
}
15 years, 10 months
Hibernate SVN: r16059 - beanvalidation/tags.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-03-03 06:29:09 -0500 (Tue, 03 Mar 2009)
New Revision: 16059
Added:
beanvalidation/tags/v1_0_Beta4/
Log:
Created tag v1_0_Beta4.
Copied: beanvalidation/tags/v1_0_Beta4 (from rev 16058, beanvalidation/trunk)
15 years, 10 months
Hibernate SVN: r16058 - in validator/trunk/hibernate-validator/src: test/java/org/hibernate/validation/constraints and 3 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-03-03 06:06:02 -0500 (Tue, 03 Mar 2009)
New Revision: 16058
Added:
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/NoGroupsValidator.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/NoMessageValidator.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/ConstraintValidatorContextTest.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/Dummy.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/DummyBean.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/DummyValidator.java
Removed:
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/incomplete/
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/NoGroupsConstraintValidator.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/NoMessageConstraintValidator.java
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ExecutionContext.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/NoGroups.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/NoMessage.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/ValidProperty.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ConstraintHelperTest.java
Log:
HV-114 Added test and some cleanup.
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java 2009-03-02 17:10:46 UTC (rev 16057)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java 2009-03-03 11:06:02 UTC (rev 16058)
@@ -100,7 +100,7 @@
ConstraintValidator<A, V> validator = getInitalizedValidator(
value, executionContext.getConstraintValidatorFactory()
);
- executionContext.setConstraintDescriptor( descriptor );
+ executionContext.setCurrentConstraintDescriptor( descriptor );
if ( !validator.isValid( value, executionContext ) ) {
constraintViolations.addAll( executionContext.createConstraintViolations( value ) );
}
@@ -109,7 +109,7 @@
final String message = ( String ) getParent().getDescriptor().getParameters().get( "message" );
final String property = executionContext.peekPropertyPath();
ExecutionContext<T>.ErrorMessage error = executionContext.new ErrorMessage( message, property );
- constraintViolations.add(executionContext.createConstraintViolation( value, error ));
+ constraintViolations.add( executionContext.createConstraintViolation( value, error ) );
}
}
@@ -133,7 +133,6 @@
else {
validatorClass = findMatchingValidatorClass( value );
}
- //
@SuppressWarnings("unchecked")
ConstraintValidator<?, ?> constraintValidator =
constraintFactory.getInstance( validatorClass );
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-03-02 17:10:46 UTC (rev 16057)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ExecutionContext.java 2009-03-03 11:06:02 UTC (rev 16058)
@@ -18,7 +18,6 @@
package org.hibernate.validation.engine;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -61,12 +60,12 @@
private final List<ConstraintViolationImpl<T>> failingConstraintViolations;
/**
- * Keep track of the property path/
+ * The current property based based from the root bean.
*/
private List<String> propertyPath;
/**
- * The current group which is getting processed.
+ * The current group we are validating.
*/
private Class<?> currentGroup;
@@ -77,9 +76,9 @@
private ValidatedProperty currentValidatedProperty;
/**
- * Stack for keeping track of the currently validated object.
+ * Stack for keeping track of the currently validated bean.
*/
- private Stack<Object> validatedBeanStack = new Stack<Object>();
+ private Stack<Object> beanStack = new Stack<Object>();
/**
* The message resolver which should be used in this context.
@@ -106,16 +105,12 @@
this.constraintValidatorFactory = constraintValidatorFactory;
this.traversableResolver = traversableResolver;
- validatedBeanStack.push( object );
+ beanStack.push( object );
processedObjects = new HashMap<Class<?>, IdentitySet>();
propertyPath = new ArrayList<String>();
failingConstraintViolations = new ArrayList<ConstraintViolationImpl<T>>();
}
- public MessageInterpolator getMessageResolver() {
- return messageResolver;
- }
-
public ConstraintValidatorFactory getConstraintValidatorFactory() {
return constraintValidatorFactory;
}
@@ -140,30 +135,25 @@
currentValidatedProperty.addError( message, property );
}
- public List<ErrorMessage> getErrorMessages() {
+ public void setCurrentConstraintDescriptor(ConstraintDescriptor constraintDescriptor) {
assert currentValidatedProperty != null;
- return currentValidatedProperty.getErrorMessages();
- }
-
- public void setConstraintDescriptor(ConstraintDescriptor constraintDescriptor) {
- assert currentValidatedProperty != null;
currentValidatedProperty.setConstraintDescriptor( constraintDescriptor );
}
- public Object peekValidatedBean() {
- return validatedBeanStack.peek();
+ public Object peekCurrentBean() {
+ return beanStack.peek();
}
- public Class<?> peekValidatedBeanType() {
- return validatedBeanStack.peek().getClass();
+ public Class<?> peekCurrentBeanType() {
+ return beanStack.peek().getClass();
}
- public void pushValidatedBean(Object validatedBean) {
- validatedBeanStack.push( validatedBean );
+ public void pushCurrentBean(Object validatedBean) {
+ beanStack.push( validatedBean );
}
- public void popValidatedBean() {
- validatedBeanStack.pop();
+ public void popCurrentBean() {
+ beanStack.pop();
}
public T getRootBean() {
@@ -180,11 +170,11 @@
public void markProcessedForCurrentGroup() {
if ( processedObjects.containsKey( currentGroup ) ) {
- processedObjects.get( currentGroup ).add( validatedBeanStack.peek() );
+ processedObjects.get( currentGroup ).add( beanStack.peek() );
}
else {
IdentitySet set = new IdentitySet();
- set.add( validatedBeanStack.peek() );
+ set.add( beanStack.peek() );
processedObjects.put( currentGroup, set );
}
}
@@ -194,7 +184,7 @@
return objectsProcessedInCurrentGroups != null && objectsProcessedInCurrentGroups.contains( value );
}
- public void addConstraintFailure(ConstraintViolationImpl<T> failingConstraintViolation) {
+ private void addConstraintFailure(ConstraintViolationImpl<T> failingConstraintViolation) {
int i = failingConstraintViolations.indexOf( failingConstraintViolation );
if ( i == -1 ) {
failingConstraintViolations.add( failingConstraintViolation );
@@ -211,10 +201,6 @@
return failingConstraintViolations;
}
- public void clearFailingConstraints() {
- failingConstraintViolations.clear();
- }
-
/**
* Adds a new level to the current property path of this context.
*
@@ -222,7 +208,7 @@
*/
public void pushProperty(String property) {
propertyPath.add( property );
- currentValidatedProperty = new ValidatedProperty( peekPropertyPath(), getCurrentGroup() );
+ currentValidatedProperty = new ValidatedProperty( peekPropertyPath() );
}
/**
@@ -273,7 +259,7 @@
Class<?> rootBeanClass = rootBean == null ? null : rootBean.getClass();
return traversableResolver.isTraversable(
- peekValidatedBean(),
+ peekCurrentBean(),
peekProperty(),
rootBeanClass,
peekPropertyPath(),
@@ -292,16 +278,16 @@
public ConstraintViolationImpl<T> createConstraintViolation(Object value, ErrorMessage error) {
ConstraintDescriptor descriptor = currentValidatedProperty.getConstraintDescriptor();
String messageTemplate = error.getMessage();
- String interpolatedMessage = getMessageResolver().interpolate(
+ String interpolatedMessage = messageResolver.interpolate(
messageTemplate,
descriptor,
- peekValidatedBean()
+ peekCurrentBean()
);
return new ConstraintViolationImpl<T>(
messageTemplate,
interpolatedMessage,
getRootBean(),
- peekValidatedBean(),
+ peekCurrentBean(),
value,
error.getProperty(),
descriptor
@@ -314,11 +300,10 @@
private ConstraintDescriptor constraintDescriptor;
private boolean defaultDisabled;
private String property;
- private Class<?> group;
- private ValidatedProperty(String property, Class<?> group) {
+
+ private ValidatedProperty(String property) {
this.property = property;
- this.group = group;
}
public void setConstraintDescriptor(ConstraintDescriptor constraintDescriptor) {
@@ -350,8 +335,7 @@
}
public List<ErrorMessage> getErrorMessages() {
- List<ErrorMessage> returnedErrorMessages = new ArrayList<ErrorMessage>( errorMessages.size() + 1 );
- Collections.copy( returnedErrorMessages, errorMessages );
+ List<ErrorMessage> returnedErrorMessages = new ArrayList<ErrorMessage>( errorMessages );
if ( !defaultDisabled ) {
returnedErrorMessages.add( new ErrorMessage( getDefaultErrorMessage(), property ) );
}
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java 2009-03-02 17:10:46 UTC (rev 16057)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java 2009-03-03 11:06:02 UTC (rev 16058)
@@ -192,7 +192,7 @@
}
public <T> boolean validateConstraint(ExecutionContext<T> executionContext) {
- final Object leafBeanInstance = executionContext.peekValidatedBean();
+ final Object leafBeanInstance = executionContext.peekCurrentBean();
Object value = getValue( leafBeanInstance );
List<ConstraintViolationImpl<T>> constraintViolations = new ArrayList<ConstraintViolationImpl<T>>();
constraintTree.validateConstraints( value, executionContext, constraintViolations );
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-03-02 17:10:46 UTC (rev 16057)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java 2009-03-03 11:06:02 UTC (rev 16058)
@@ -183,7 +183,7 @@
* @return List of invalid constraints.
*/
private <T> List<ConstraintViolationImpl<T>> validateInContext(ExecutionContext<T> context, GroupChain groupChain) {
- if ( context.peekValidatedBean() == null ) {
+ if ( context.peekCurrentBean() == null ) {
return Collections.emptyList();
}
@@ -228,7 +228,7 @@
private <T> void validateConstraints(ExecutionContext<T> executionContext) {
//casting rely on the fact that root object is at the top of the stack
@SuppressWarnings(" unchecked")
- BeanMetaData<T> beanMetaData = getBeanMetaData( ( Class<T> ) executionContext.peekValidatedBeanType() );
+ BeanMetaData<T> beanMetaData = getBeanMetaData( ( Class<T> ) executionContext.peekCurrentBeanType() );
if ( executionContext.getCurrentGroup().getName().equals( Default.class.getName() ) ) {
List<Class<?>> defaultGroupSequence = beanMetaData.getDefaultGroupSequence();
if ( log.isTraceEnabled() && defaultGroupSequence.size() > 0 && defaultGroupSequence.get( 0 ) != Default.class ) {
@@ -275,12 +275,12 @@
}
private <T> void validateCascadedConstraints(ExecutionContext<T> context) {
- List<Member> cascadedMembers = getBeanMetaData( context.peekValidatedBeanType() )
+ List<Member> cascadedMembers = getBeanMetaData( context.peekCurrentBeanType() )
.getCascadedMembers();
for ( Member member : cascadedMembers ) {
Type type = ReflectionHelper.typeOf( member );
context.pushProperty( ReflectionHelper.getPropertyName( member ) );
- Object value = ReflectionHelper.getValue( member, context.peekValidatedBean() );
+ Object value = ReflectionHelper.getValue( member, context.peekCurrentBean() );
if ( value == null ) {
continue;
}
@@ -343,12 +343,12 @@
if ( !context.isValidatedAgainstCurrentGroup( actualValue ) ) {
context.replacePropertyIndex( propertyIndex );
- context.pushValidatedBean( actualValue );
+ context.pushCurrentBean( actualValue );
validateInContext(
context,
groupChainGenerator.getGroupChainFor( Arrays.asList( new Class<?>[] { context.getCurrentGroup() } ) )
);
- context.popValidatedBean();
+ context.popCurrentBean();
}
i++;
}
Copied: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators (from rev 16046, validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/incomplete)
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/NoGroups.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/incomplete/NoGroups.java 2009-02-26 16:26:54 UTC (rev 16046)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/NoGroups.java 2009-03-03 11:06:02 UTC (rev 16058)
@@ -15,7 +15,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.hibernate.validation.constraints.incomplete;
+package org.hibernate.validation.constraints.invalidvalidators;
import java.lang.annotation.Documented;
import static java.lang.annotation.ElementType.FIELD;
@@ -29,7 +29,7 @@
* @author Hardy Ferentschik
*/
@Documented
-@Constraint(validatedBy = NoGroupsConstraintValidator.class)
+@Constraint(validatedBy = NoGroupsValidator.class)
@Target({ METHOD, FIELD })
@Retention(RUNTIME)
public @interface NoGroups {
Deleted: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/NoGroupsConstraintValidator.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/incomplete/NoGroupsConstraintValidator.java 2009-02-26 16:26:54 UTC (rev 16046)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/NoGroupsConstraintValidator.java 2009-03-03 11:06:02 UTC (rev 16058)
@@ -1,34 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.validation.constraints.incomplete;
-
-import javax.validation.ConstraintValidator;
-import javax.validation.ConstraintValidatorContext;
-
-/**
- * @author Hardy Ferentschik
- */
-public class NoGroupsConstraintValidator implements ConstraintValidator<NoGroups, Object> {
-
- public void initialize(NoGroups parameters) {
- }
-
- public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) {
- return false;
- }
-}
\ No newline at end of file
Added: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/NoGroupsValidator.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/NoGroupsValidator.java (rev 0)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/NoGroupsValidator.java 2009-03-03 11:06:02 UTC (rev 16058)
@@ -0,0 +1,34 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.validation.constraints.invalidvalidators;
+
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class NoGroupsValidator implements ConstraintValidator<NoGroups, Object> {
+
+ public void initialize(NoGroups parameters) {
+ }
+
+ public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) {
+ return false;
+ }
+}
\ No newline at end of file
Property changes on: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/NoGroupsValidator.java
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/NoMessage.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/incomplete/NoMessage.java 2009-02-26 16:26:54 UTC (rev 16046)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/NoMessage.java 2009-03-03 11:06:02 UTC (rev 16058)
@@ -15,7 +15,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.hibernate.validation.constraints.incomplete;
+package org.hibernate.validation.constraints.invalidvalidators;
import java.lang.annotation.Documented;
import static java.lang.annotation.ElementType.FIELD;
@@ -29,7 +29,7 @@
* @author Hardy Ferentschik
*/
@Documented
-@Constraint(validatedBy = NoMessageConstraintValidator.class)
+@Constraint(validatedBy = NoMessageValidator.class)
@Target({ METHOD, FIELD })
@Retention(RUNTIME)
public @interface NoMessage {
Deleted: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/NoMessageConstraintValidator.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/incomplete/NoMessageConstraintValidator.java 2009-02-26 16:26:54 UTC (rev 16046)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/NoMessageConstraintValidator.java 2009-03-03 11:06:02 UTC (rev 16058)
@@ -1,34 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.validation.constraints.incomplete;
-
-import javax.validation.ConstraintValidator;
-import javax.validation.ConstraintValidatorContext;
-
-/**
- * @author Hardy Ferentschik
- */
-public class NoMessageConstraintValidator implements ConstraintValidator<NoMessage, Object> {
-
- public void initialize(NoMessage parameters) {
- }
-
- public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) {
- return false;
- }
-}
\ No newline at end of file
Added: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/NoMessageValidator.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/NoMessageValidator.java (rev 0)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/NoMessageValidator.java 2009-03-03 11:06:02 UTC (rev 16058)
@@ -0,0 +1,34 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.validation.constraints.invalidvalidators;
+
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class NoMessageValidator implements ConstraintValidator<NoMessage, Object> {
+
+ public void initialize(NoMessage parameters) {
+ }
+
+ public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) {
+ return false;
+ }
+}
\ No newline at end of file
Property changes on: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/NoMessageValidator.java
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/ValidProperty.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/incomplete/ValidProperty.java 2009-02-26 16:26:54 UTC (rev 16046)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/invalidvalidators/ValidProperty.java 2009-03-03 11:06:02 UTC (rev 16058)
@@ -15,7 +15,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.hibernate.validation.constraints.incomplete;
+package org.hibernate.validation.constraints.invalidvalidators;
import java.lang.annotation.Documented;
import static java.lang.annotation.ElementType.FIELD;
@@ -29,7 +29,7 @@
* @author Hardy Ferentschik
*/
@Documented
-@Constraint(validatedBy = NoGroupsConstraintValidator.class)
+@Constraint(validatedBy = NoGroupsValidator.class)
@Target({ METHOD, FIELD })
@Retention(RUNTIME)
public @interface ValidProperty {
Added: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/ConstraintValidatorContextTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/ConstraintValidatorContextTest.java (rev 0)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/ConstraintValidatorContextTest.java 2009-03-03 11:06:02 UTC (rev 16058)
@@ -0,0 +1,78 @@
+// $Id:$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.validation.constraints.validatorcontext;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import javax.validation.ConstraintViolation;
+import javax.validation.Validator;
+
+import static org.junit.Assert.assertEquals;
+import org.junit.Test;
+
+import org.hibernate.validation.util.TestUtil;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class ConstraintValidatorContextTest {
+
+ @Test
+ public void testNoCustomization() {
+ Validator validator = TestUtil.getValidator();
+
+ DummyBean bean = new DummyBean( "foobar" );
+
+ Set<ConstraintViolation<DummyBean>> constraintViolations = validator.validate( bean );
+ assertEquals( "Wrong number of constraints", 1, constraintViolations.size() );
+ ConstraintViolation constraintViolation = constraintViolations.iterator().next();
+ assertEquals( "Wrong message", "dummy message", constraintViolation.getMessage() );
+ }
+
+ /**
+ * @todo Is this the right behaviour? The spec is not quite clear about this.
+ */
+ @Test
+ public void testDisableDefaultErrorWithoutCustomError() {
+ Validator validator = TestUtil.getValidator();
+
+ DummyBean bean = new DummyBean( "foobar" );
+ DummyValidator.disableDefaultError( true );
+
+ Set<ConstraintViolation<DummyBean>> constraintViolations = validator.validate( bean );
+ assertEquals( "Wrong number of constraints", 0, constraintViolations.size() );
+ }
+
+ @Test
+ public void testDisableDefaultErrorWithCustomErrors() {
+ Validator validator = TestUtil.getValidator();
+
+ DummyBean bean = new DummyBean( "foobar" );
+ DummyValidator.disableDefaultError( true );
+ Map<String, String> errors = new HashMap<String, String>();
+ errors.put( "message1", "property1" );
+ DummyValidator.setErrorMessages( errors );
+
+ Set<ConstraintViolation<DummyBean>> constraintViolations = validator.validate( bean );
+ assertEquals( "Wrong number of constraints", 1, constraintViolations.size() );
+ ConstraintViolation constraintViolation = constraintViolations.iterator().next();
+ assertEquals( "Wrong message", "message1", constraintViolation.getMessage() );
+ assertEquals( "Wrong property", "property1", constraintViolation.getPropertyPath() );
+ }
+}
Property changes on: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/ConstraintValidatorContextTest.java
___________________________________________________________________
Name: svn:keywords
+ Id
Copied: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/Dummy.java (from rev 16046, validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/incomplete/NoGroups.java)
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/Dummy.java (rev 0)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/Dummy.java 2009-03-03 11:06:02 UTC (rev 16058)
@@ -0,0 +1,39 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.validation.constraints.validatorcontext;
+
+import java.lang.annotation.Documented;
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+import javax.validation.Constraint;
+
+/**
+ * @author Hardy Ferentschik
+ */
+@Documented
+@Constraint(validatedBy = DummyValidator.class)
+@Target({ METHOD, FIELD })
+@Retention(RUNTIME)
+public @interface Dummy {
+ String message() default "dummy message";
+
+ Class<?>[] groups() default { };
+}
\ No newline at end of file
Added: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/DummyBean.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/DummyBean.java (rev 0)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/DummyBean.java 2009-03-03 11:06:02 UTC (rev 16058)
@@ -0,0 +1,31 @@
+// $Id:$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.validation.constraints.validatorcontext;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class DummyBean {
+
+ @Dummy
+ String value;
+
+ public DummyBean(String value) {
+ this.value = value;
+ }
+}
Property changes on: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/DummyBean.java
___________________________________________________________________
Name: svn:keywords
+ Id
Copied: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/DummyValidator.java (from rev 16046, validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/incomplete/NoGroupsConstraintValidator.java)
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/DummyValidator.java (rev 0)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/DummyValidator.java 2009-03-03 11:06:02 UTC (rev 16058)
@@ -0,0 +1,58 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.validation.constraints.validatorcontext;
+
+import java.util.Map;
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class DummyValidator implements ConstraintValidator<Dummy, String> {
+
+ private static boolean disableDefaultError;
+
+ private static Map<String, String> errorMessages;
+
+
+ public void initialize(Dummy parameters) {
+ }
+
+ public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
+ if ( disableDefaultError ) {
+ constraintValidatorContext.disableDefaultError();
+ }
+
+ if ( errorMessages != null ) {
+ for ( Map.Entry<String, String> entry : errorMessages.entrySet() ) {
+ constraintValidatorContext.addError( entry.getKey(), entry.getValue() );
+ }
+ }
+
+ return false;
+ }
+
+ public static void disableDefaultError(boolean b) {
+ disableDefaultError = b;
+ }
+
+ public static void setErrorMessages(Map<String, String> errorMessages) {
+ DummyValidator.errorMessages = errorMessages;
+ }
+}
\ No newline at end of file
Property changes on: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/validatorcontext/DummyValidator.java
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ConstraintHelperTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ConstraintHelperTest.java 2009-03-02 17:10:46 UTC (rev 16057)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ConstraintHelperTest.java 2009-03-03 11:06:02 UTC (rev 16058)
@@ -1,4 +1,4 @@
-// $Id:$
+// $Id$
/*
* JBoss, Home of Professional Open Source
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
@@ -29,9 +29,9 @@
import org.junit.BeforeClass;
import org.junit.Test;
-import org.hibernate.validation.constraints.incomplete.NoGroups;
-import org.hibernate.validation.constraints.incomplete.NoMessage;
-import org.hibernate.validation.constraints.incomplete.ValidProperty;
+import org.hibernate.validation.constraints.invalidvalidators.NoGroups;
+import org.hibernate.validation.constraints.invalidvalidators.NoMessage;
+import org.hibernate.validation.constraints.invalidvalidators.ValidProperty;
import org.hibernate.validation.eg.Engine;
import org.hibernate.validation.eg.Order;
import org.hibernate.validation.util.ReflectionHelper;
15 years, 10 months
Hibernate SVN: r16057 - beanvalidation/trunk/validation-api.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-03-02 12:10:46 -0500 (Mon, 02 Mar 2009)
New Revision: 16057
Modified:
beanvalidation/trunk/validation-api/pom.xml
Log:
changed pom as prep for rlease
Modified: beanvalidation/trunk/validation-api/pom.xml
===================================================================
--- beanvalidation/trunk/validation-api/pom.xml 2009-03-02 17:05:58 UTC (rev 16056)
+++ beanvalidation/trunk/validation-api/pom.xml 2009-03-02 17:10:46 UTC (rev 16057)
@@ -6,7 +6,7 @@
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
- <version>1.0.Beta4-SNAPSHOT</version>
+ <version>1.0.Beta4</version>
<packaging>jar</packaging>
<name>Bean Validation API</name>
15 years, 10 months
Hibernate SVN: r16056 - validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-03-02 12:05:58 -0500 (Mon, 02 Mar 2009)
New Revision: 16056
Removed:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintValidatorContextImpl.java
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintViolationImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ExecutionContext.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java
Log:
- HV-114 Let the ExecutionContext take the role of ConstraintValidatorContextImpl
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java 2009-03-02 16:08:45 UTC (rev 16055)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java 2009-03-02 17:05:58 UTC (rev 16056)
@@ -89,39 +89,27 @@
return descriptor;
}
- public <T, V> void validateConstraints(V value, Class<T> beanClass, ExecutionContext<T> executionContext, List<ConstraintViolationImpl<T>> constraintViolations) {
+ public <T, V> void validateConstraints(V value, ExecutionContext<T> executionContext, List<ConstraintViolationImpl<T>> constraintViolations) {
for ( ConstraintTree<?> tree : getChildren() ) {
- tree.validateConstraints( value, beanClass, executionContext, constraintViolations );
+ tree.validateConstraints( value, executionContext, constraintViolations );
}
- final Object leafBeanInstance = executionContext.peekValidatedObject();
if ( log.isTraceEnabled() ) {
log.trace( "Validating value {} against constraint defined by {}", value, descriptor );
}
ConstraintValidator<A, V> validator = getInitalizedValidator(
value, executionContext.getConstraintValidatorFactory()
);
- ConstraintValidatorContextImpl constraintContext = new ConstraintValidatorContextImpl( descriptor );
- if ( !validator.isValid( value, constraintContext ) ) {
- for ( ConstraintValidatorContextImpl.ErrorMessage error : constraintContext.getErrorMessages() ) {
- final String message = error.getMessage();
- createConstraintViolation(
- value, beanClass, executionContext, leafBeanInstance, message, descriptor, constraintViolations
- );
- }
+ executionContext.setConstraintDescriptor( descriptor );
+ if ( !validator.isValid( value, executionContext ) ) {
+ constraintViolations.addAll( executionContext.createConstraintViolations( value ) );
}
if ( reportAsSingleViolation() && constraintViolations.size() > 0 ) {
constraintViolations.clear();
final String message = ( String ) getParent().getDescriptor().getParameters().get( "message" );
- createConstraintViolation(
- value,
- beanClass,
- executionContext,
- leafBeanInstance,
- message,
- getParent().descriptor,
- constraintViolations
- );
+ final String property = executionContext.peekPropertyPath();
+ ExecutionContext<T>.ErrorMessage error = executionContext.new ErrorMessage( message, property );
+ constraintViolations.add(executionContext.createConstraintViolation( value, error ));
}
}
@@ -130,25 +118,6 @@
&& getParent().getDescriptor().isReportAsSingleViolation();
}
- private <T> void createConstraintViolation(Object value, Class<T> beanClass, ExecutionContext<T> executionContext, Object leafBeanInstance, String messageTemplate, ConstraintDescriptor descriptor, List<ConstraintViolationImpl<T>> constraintViolations) {
- String interpolatedMessage = executionContext.getMessageResolver().interpolate(
- messageTemplate,
- descriptor,
- leafBeanInstance
- );
- ConstraintViolationImpl<T> failingConstraintViolation = new ConstraintViolationImpl<T>(
- messageTemplate,
- interpolatedMessage,
- executionContext.getRootBean(),
- beanClass,
- leafBeanInstance,
- value,
- executionContext.peekPropertyPath(), //FIXME use error.getProperty()
- descriptor
- );
- constraintViolations.add( failingConstraintViolation );
- }
-
/**
* @param value The value to be validated.
* @param constraintFactory constraint factory used to instantiate the constraint validator.
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintValidatorContextImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintValidatorContextImpl.java 2009-03-02 16:08:45 UTC (rev 16055)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintValidatorContextImpl.java 2009-03-02 17:05:58 UTC (rev 16056)
@@ -1,84 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.validation.engine;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import javax.validation.ConstraintDescriptor;
-import javax.validation.ConstraintValidatorContext;
-
-/**
- * @author Emmanuel Bernard
- */
-public class ConstraintValidatorContextImpl implements ConstraintValidatorContext {
- private final ConstraintDescriptor constraintDescriptor;
- private final List<ErrorMessage> errorMessages;
- private boolean defaultDisabled;
-
- public ConstraintValidatorContextImpl(ConstraintDescriptor constraintDescriptor) {
- this.constraintDescriptor = constraintDescriptor;
- this.errorMessages = new ArrayList<ErrorMessage>(3);
- }
-
- public void disableDefaultError() {
- defaultDisabled = true;
- }
-
- public String getDefaultErrorMessage() {
- return ( String ) constraintDescriptor.getParameters().get("message");
- }
-
- public void addError(String message) {
- //FIXME get the default property if property-level
- errorMessages.add( new ErrorMessage( message, null ) );
- }
-
- public void addError(String message, String property) {
- //FIXME: make sure the property is valid
- errorMessages.add( new ErrorMessage( message, property ) );
- }
-
- public List<ErrorMessage> getErrorMessages() {
- List<ErrorMessage> returnedErrorMessages = new ArrayList<ErrorMessage>( errorMessages.size() + 1 );
- Collections.copy( returnedErrorMessages, errorMessages );
- if ( ! defaultDisabled ) {
- //FIXME get the default property if property-level
- returnedErrorMessages.add( new ErrorMessage( getDefaultErrorMessage(), null) );
- }
- return returnedErrorMessages;
- }
-
- public static class ErrorMessage {
- private final String message;
- private final String property;
-
- private ErrorMessage(String message, String property) {
- this.message = message;
- this.property = property;
- }
-
- public String getMessage() {
- return message;
- }
-
- public String getProperty() {
- return property;
- }
- }
-}
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintViolationImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintViolationImpl.java 2009-03-02 16:08:45 UTC (rev 16055)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintViolationImpl.java 2009-03-02 17:05:58 UTC (rev 16056)
@@ -27,7 +27,6 @@
public class ConstraintViolationImpl<T> implements ConstraintViolation<T> {
private String interpolatedMessage;
private T rootBean;
- private Class<T> beanClass;
private Object value;
private String propertyPath;
private Object leafBeanInstance;
@@ -35,13 +34,12 @@
private String rawMessage;
- public ConstraintViolationImpl(String messageTemplate, String interpolatedMessage, T rootBean, Class<T> beanClass,
+ public ConstraintViolationImpl(String messageTemplate, String interpolatedMessage, T rootBean,
Object leafBeanInstance, Object value,
String propertyPath, ConstraintDescriptor constraintDescriptor) {
this.rawMessage = messageTemplate;
this.interpolatedMessage = interpolatedMessage;
this.rootBean = rootBean;
- this.beanClass = beanClass;
this.value = value;
this.propertyPath = propertyPath;
this.leafBeanInstance = leafBeanInstance;
@@ -99,9 +97,6 @@
ConstraintViolationImpl that = ( ConstraintViolationImpl ) o;
- if ( beanClass != null ? !beanClass.equals( that.beanClass ) : that.beanClass != null ) {
- return false;
- }
if ( interpolatedMessage != null ? !interpolatedMessage.equals( that.interpolatedMessage ) : that.interpolatedMessage != null ) {
return false;
}
@@ -122,7 +117,6 @@
public int hashCode() {
int result = interpolatedMessage != null ? interpolatedMessage.hashCode() : 0;
result = 31 * result + ( rootBean != null ? rootBean.hashCode() : 0 );
- result = 31 * result + ( beanClass != null ? beanClass.hashCode() : 0 );
result = 31 * result + ( value != null ? value.hashCode() : 0 );
result = 31 * result + ( propertyPath != null ? propertyPath.hashCode() : 0 );
return result;
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-03-02 16:08:45 UTC (rev 16055)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ExecutionContext.java 2009-03-02 17:05:58 UTC (rev 16056)
@@ -18,10 +18,13 @@
package org.hibernate.validation.engine;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
+import javax.validation.ConstraintDescriptor;
+import javax.validation.ConstraintValidatorContext;
import javax.validation.ConstraintValidatorFactory;
import javax.validation.MessageInterpolator;
import javax.validation.TraversableResolver;
@@ -29,15 +32,18 @@
import org.hibernate.validation.util.IdentitySet;
/**
- * Context object keeping track of all processed objects and all failing constraints.
- * At the same time it keeps track of the currently validated object, the current group and property path.
- * Currently the validated object and the property path are processed in a stack fashion.
+ * Context object keeping track of all processed objects and failing constraints.
+ * It also keeps track of the currently validated object, group and property path.
*
* @author Hardy Ferentschik
* @author Emmanuel Bernard
+ * @todo Look for ways to improve this data structure. It is quite fragile and depends on the right oder of calls
+ * in order to work.
*/
-public class ExecutionContext<T> {
+public class ExecutionContext<T> implements ConstraintValidatorContext {
+ private static final String PROPERTY_ROOT = "";
+
/**
* The root bean of the validation.
*/
@@ -55,9 +61,9 @@
private final List<ConstraintViolationImpl<T>> failingConstraintViolations;
/**
- * The current property path.
+ * Keep track of the property path/
*/
- private String propertyPath;
+ private List<String> propertyPath;
/**
* The current group which is getting processed.
@@ -65,9 +71,15 @@
private Class<?> currentGroup;
/**
+ * Reference to a <code>ValidatedProperty</code> keeping track of the property we are currently validating,
+ * together with required meta data.
+ */
+ private ValidatedProperty currentValidatedProperty;
+
+ /**
* Stack for keeping track of the currently validated object.
*/
- private Stack<Object> validatedObjectStack = new Stack<Object>();
+ private Stack<Object> validatedBeanStack = new Stack<Object>();
/**
* The message resolver which should be used in this context.
@@ -79,6 +91,9 @@
*/
private final ConstraintValidatorFactory constraintValidatorFactory;
+ /**
+ * Allows a JPA provider to decide whether a property should be validated.
+ */
private final TraversableResolver traversableResolver;
public ExecutionContext(T object, MessageInterpolator messageResolver, ConstraintValidatorFactory constraintValidatorFactory, TraversableResolver traversableResolver) {
@@ -91,9 +106,9 @@
this.constraintValidatorFactory = constraintValidatorFactory;
this.traversableResolver = traversableResolver;
- validatedObjectStack.push( object );
+ validatedBeanStack.push( object );
processedObjects = new HashMap<Class<?>, IdentitySet>();
- propertyPath = "";
+ propertyPath = new ArrayList<String>();
failingConstraintViolations = new ArrayList<ConstraintViolationImpl<T>>();
}
@@ -105,22 +120,52 @@
return constraintValidatorFactory;
}
- public Object peekValidatedObject() {
- return validatedObjectStack.peek();
+ public void disableDefaultError() {
+ assert currentValidatedProperty != null;
+ currentValidatedProperty.disableDefaultError();
}
- public Class<?> peekValidatedObjectType() {
- return validatedObjectStack.peek().getClass();
+ public String getDefaultErrorMessage() {
+ assert currentValidatedProperty != null;
+ return currentValidatedProperty.getDefaultErrorMessage();
}
- public void pushValidatedObject(Object validatedObject) {
- validatedObjectStack.push( validatedObject );
+ public void addError(String message) {
+ assert currentValidatedProperty != null;
+ currentValidatedProperty.addError( message );
}
- public void popValidatedObject() {
- validatedObjectStack.pop();
+ public void addError(String message, String property) {
+ assert currentValidatedProperty != null;
+ currentValidatedProperty.addError( message, property );
}
+ public List<ErrorMessage> getErrorMessages() {
+ assert currentValidatedProperty != null;
+ return currentValidatedProperty.getErrorMessages();
+ }
+
+ public void setConstraintDescriptor(ConstraintDescriptor constraintDescriptor) {
+ assert currentValidatedProperty != null;
+ currentValidatedProperty.setConstraintDescriptor( constraintDescriptor );
+ }
+
+ public Object peekValidatedBean() {
+ return validatedBeanStack.peek();
+ }
+
+ public Class<?> peekValidatedBeanType() {
+ return validatedBeanStack.peek().getClass();
+ }
+
+ public void pushValidatedBean(Object validatedBean) {
+ validatedBeanStack.push( validatedBean );
+ }
+
+ public void popValidatedBean() {
+ validatedBeanStack.pop();
+ }
+
public T getRootBean() {
return rootBean;
}
@@ -135,16 +180,16 @@
public void markProcessedForCurrentGroup() {
if ( processedObjects.containsKey( currentGroup ) ) {
- processedObjects.get( currentGroup ).add( validatedObjectStack.peek() );
+ processedObjects.get( currentGroup ).add( validatedBeanStack.peek() );
}
else {
IdentitySet set = new IdentitySet();
- set.add( validatedObjectStack.peek() );
+ set.add( validatedBeanStack.peek() );
processedObjects.put( currentGroup, set );
}
}
- public boolean isProcessedForCurrentGroup(Object value) {
+ public boolean isValidatedAgainstCurrentGroup(Object value) {
final IdentitySet objectsProcessedInCurrentGroups = processedObjects.get( currentGroup );
return objectsProcessedInCurrentGroups != null && objectsProcessedInCurrentGroups.contains( value );
}
@@ -176,48 +221,49 @@
* @param property the new property to add to the current path.
*/
public void pushProperty(String property) {
- if ( propertyPath.length() == 0 ) {
- propertyPath = property;
- }
- else {
- propertyPath = propertyPath + "." + property;
- }
+ propertyPath.add( property );
+ currentValidatedProperty = new ValidatedProperty( peekPropertyPath(), getCurrentGroup() );
}
/**
* Drops the last level of the current property path of this context.
*/
public void popProperty() {
- int lastIndex = propertyPath.lastIndexOf( '.' );
- if ( lastIndex != -1 ) {
- propertyPath = propertyPath.substring( 0, lastIndex );
+ if ( propertyPath.size() > 0 ) {
+ propertyPath.remove( propertyPath.size() - 1 );
+ currentValidatedProperty = null;
}
- else {
- propertyPath = "";
- }
}
- public void appendIndexToPropertyPath(String index) {
- propertyPath += index;
+ public void markCurrentPropertyAsIndexed() {
+ String property = peekProperty();
+ property += "[]";
+ popProperty();
+ pushProperty( property );
}
public void replacePropertyIndex(String index) {
- // replace the last occurance of [<oldIndex>] with [<index>]
- propertyPath = propertyPath.replaceAll( "\\[[0-9]*\\]$", "[" + index + "]" );
+ // replace the last occurance of [<oldIndex>] with [<index>]
+ String property = peekProperty();
+ property = property.replaceAll( "\\[[0-9]*\\]$", "[" + index + "]" );
+ popProperty();
+ pushProperty( property );
}
public String peekPropertyPath() {
- return propertyPath;
+ StringBuilder builder = new StringBuilder();
+ for ( String s : propertyPath ) {
+ builder.append( s ).append( "." );
+ }
+ builder.delete( builder.lastIndexOf( "." ), builder.length() );
+ return builder.toString();
}
public String peekProperty() {
- int lastIndex = propertyPath.lastIndexOf( '.' );
- if ( lastIndex != -1 ) {
- return propertyPath.substring( 0, lastIndex );
+ if ( propertyPath.size() == 0 ) {
+ return PROPERTY_ROOT;
}
- else {
- return "";
- }
+ return propertyPath.get( propertyPath.size() - 1 );
}
public boolean isValidationRequired(MetaConstraint metaConstraint) {
@@ -227,11 +273,107 @@
Class<?> rootBeanClass = rootBean == null ? null : rootBean.getClass();
return traversableResolver.isTraversable(
- peekValidatedObject(),
+ peekValidatedBean(),
peekProperty(),
rootBeanClass,
peekPropertyPath(),
metaConstraint.getElementType()
);
}
+
+ public List<ConstraintViolationImpl<T>> createConstraintViolations(Object value) {
+ List<ConstraintViolationImpl<T>> constraintViolations = new ArrayList<ConstraintViolationImpl<T>>();
+ for ( ErrorMessage error : currentValidatedProperty.getErrorMessages() ) {
+ constraintViolations.add( createConstraintViolation( value, error ) );
+ }
+ return constraintViolations;
+ }
+
+ public ConstraintViolationImpl<T> createConstraintViolation(Object value, ErrorMessage error) {
+ ConstraintDescriptor descriptor = currentValidatedProperty.getConstraintDescriptor();
+ String messageTemplate = error.getMessage();
+ String interpolatedMessage = getMessageResolver().interpolate(
+ messageTemplate,
+ descriptor,
+ peekValidatedBean()
+ );
+ return new ConstraintViolationImpl<T>(
+ messageTemplate,
+ interpolatedMessage,
+ getRootBean(),
+ peekValidatedBean(),
+ value,
+ error.getProperty(),
+ descriptor
+ );
+ }
+
+ class ValidatedProperty {
+
+ private final List<ErrorMessage> errorMessages = new ArrayList<ErrorMessage>( 3 );
+ private ConstraintDescriptor constraintDescriptor;
+ private boolean defaultDisabled;
+ private String property;
+ private Class<?> group;
+
+ private ValidatedProperty(String property, Class<?> group) {
+ this.property = property;
+ this.group = group;
+ }
+
+ public void setConstraintDescriptor(ConstraintDescriptor constraintDescriptor) {
+ this.constraintDescriptor = constraintDescriptor;
+ }
+
+ public ConstraintDescriptor getConstraintDescriptor() {
+ return constraintDescriptor;
+ }
+
+ void disableDefaultError() {
+ defaultDisabled = true;
+ }
+
+ public boolean isDefaultErrorDisabled() {
+ return defaultDisabled;
+ }
+
+ public String getDefaultErrorMessage() {
+ return ( String ) constraintDescriptor.getParameters().get( "message" );
+ }
+
+ public void addError(String message) {
+ errorMessages.add( new ErrorMessage( message, property ) );
+ }
+
+ public void addError(String message, String property) {
+ errorMessages.add( new ErrorMessage( message, property ) );
+ }
+
+ public List<ErrorMessage> getErrorMessages() {
+ List<ErrorMessage> returnedErrorMessages = new ArrayList<ErrorMessage>( errorMessages.size() + 1 );
+ Collections.copy( returnedErrorMessages, errorMessages );
+ if ( !defaultDisabled ) {
+ returnedErrorMessages.add( new ErrorMessage( getDefaultErrorMessage(), property ) );
+ }
+ return returnedErrorMessages;
+ }
+ }
+
+ public class ErrorMessage {
+ private final String message;
+ private final String property;
+
+ public ErrorMessage(String message, String property) {
+ this.message = message;
+ this.property = property;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public String getProperty() {
+ return property;
+ }
+ }
}
\ No newline at end of file
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java 2009-03-02 16:08:45 UTC (rev 16055)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java 2009-03-02 17:05:58 UTC (rev 16056)
@@ -191,11 +191,11 @@
return constraintTree;
}
- public <T> boolean validateConstraint(Class<T> beanClass, ExecutionContext<T> executionContext) {
- final Object leafBeanInstance = executionContext.peekValidatedObject();
+ public <T> boolean validateConstraint(ExecutionContext<T> executionContext) {
+ final Object leafBeanInstance = executionContext.peekValidatedBean();
Object value = getValue( leafBeanInstance );
List<ConstraintViolationImpl<T>> constraintViolations = new ArrayList<ConstraintViolationImpl<T>>();
- constraintTree.validateConstraints( value, beanClass, executionContext, constraintViolations );
+ constraintTree.validateConstraints( value, executionContext, constraintViolations );
if ( constraintViolations.size() > 0 ) {
executionContext.addConstraintFailures( constraintViolations );
return false;
@@ -203,9 +203,9 @@
return true;
}
- public <T> boolean validateConstraint(Class<T> beanClass, Object value, ExecutionContext<T> executionContext) {
+ public <T> boolean validateConstraint(Object value, ExecutionContext<T> executionContext) {
List<ConstraintViolationImpl<T>> constraintViolations = new ArrayList<ConstraintViolationImpl<T>>();
- constraintTree.validateConstraints( value, beanClass, executionContext, constraintViolations );
+ constraintTree.validateConstraints( value, executionContext, constraintViolations );
if ( constraintViolations.size() > 0 ) {
executionContext.addConstraintFailures( constraintViolations );
return false;
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-03-02 16:08:45 UTC (rev 16055)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java 2009-03-02 17:05:58 UTC (rev 16056)
@@ -183,7 +183,7 @@
* @return List of invalid constraints.
*/
private <T> List<ConstraintViolationImpl<T>> validateInContext(ExecutionContext<T> context, GroupChain groupChain) {
- if ( context.peekValidatedObject() == null ) {
+ if ( context.peekValidatedBean() == null ) {
return Collections.emptyList();
}
@@ -228,7 +228,7 @@
private <T> void validateConstraints(ExecutionContext<T> executionContext) {
//casting rely on the fact that root object is at the top of the stack
@SuppressWarnings(" unchecked")
- BeanMetaData<T> beanMetaData = getBeanMetaData( ( Class<T> ) executionContext.peekValidatedObjectType() );
+ BeanMetaData<T> beanMetaData = getBeanMetaData( ( Class<T> ) executionContext.peekValidatedBeanType() );
if ( executionContext.getCurrentGroup().getName().equals( Default.class.getName() ) ) {
List<Class<?>> defaultGroupSequence = beanMetaData.getDefaultGroupSequence();
if ( log.isTraceEnabled() && defaultGroupSequence.size() > 0 && defaultGroupSequence.get( 0 ) != Default.class ) {
@@ -265,7 +265,7 @@
for ( MetaConstraint<T, ?> metaConstraint : beanMetaData.geMetaConstraintList() ) {
executionContext.pushProperty( metaConstraint.getPropertyName() );
if ( executionContext.isValidationRequired( metaConstraint ) ) {
- boolean tmp = metaConstraint.validateConstraint( beanMetaData.getBeanClass(), executionContext );
+ boolean tmp = metaConstraint.validateConstraint( executionContext );
validationSuccessful = validationSuccessful && tmp;
}
executionContext.popProperty();
@@ -275,12 +275,12 @@
}
private <T> void validateCascadedConstraints(ExecutionContext<T> context) {
- List<Member> cascadedMembers = getBeanMetaData( context.peekValidatedObjectType() )
+ List<Member> cascadedMembers = getBeanMetaData( context.peekValidatedBeanType() )
.getCascadedMembers();
for ( Member member : cascadedMembers ) {
Type type = ReflectionHelper.typeOf( member );
context.pushProperty( ReflectionHelper.getPropertyName( member ) );
- Object value = ReflectionHelper.getValue( member, context.peekValidatedObject() );
+ Object value = ReflectionHelper.getValue( member, context.peekValidatedBean() );
if ( value == null ) {
continue;
}
@@ -309,12 +309,12 @@
( Iterable<?> ) value :
map.entrySet();
iter = elements.iterator();
- context.appendIndexToPropertyPath( "[]" );
+ context.markCurrentPropertyAsIndexed();
}
else if ( ReflectionHelper.isArray( type ) ) {
List<?> arrayList = Arrays.asList( value );
iter = arrayList.iterator();
- context.appendIndexToPropertyPath( "[]" );
+ context.markCurrentPropertyAsIndexed();
}
else {
List<Object> list = new ArrayList<Object>();
@@ -340,15 +340,15 @@
actualValue = ( ( Map.Entry ) actualValue ).getValue();
}
- if ( !context.isProcessedForCurrentGroup( actualValue ) ) {
+ if ( !context.isValidatedAgainstCurrentGroup( actualValue ) ) {
context.replacePropertyIndex( propertyIndex );
- context.pushValidatedObject( actualValue );
+ context.pushValidatedBean( actualValue );
validateInContext(
context,
groupChainGenerator.getGroupChainFor( Arrays.asList( new Class<?>[] { context.getCurrentGroup() } ) )
);
- context.popValidatedObject();
+ context.popValidatedBean();
}
i++;
}
@@ -420,9 +420,10 @@
context.pushProperty( propertyIter.getOriginalProperty() );
context.setCurrentGroup( groupClass );
if ( context.isValidationRequired( metaConstraint ) ) {
- metaConstraint.validateConstraint( ( Class<T> ) object.getClass(), context );
+ metaConstraint.validateConstraint( context );
failingConstraintViolations.addAll( context.getFailingConstraints() );
}
+ context.popProperty();
}
if ( failingConstraintViolations.size() > numberOfConstraintViolationsBefore ) {
break;
@@ -495,11 +496,11 @@
);
context.pushProperty( propertyIter.getOriginalProperty() );
context.setCurrentGroup( groupClass );
-
if ( context.isValidationRequired( metaConstraint ) ) {
- metaConstraint.validateConstraint( beanType, value, context );
+ metaConstraint.validateConstraint( value, context );
failingConstraintViolations.addAll( context.getFailingConstraints() );
}
+ context.popProperty();
}
if ( failingConstraintViolations.size() > numberOfConstraintViolations ) {
break;
15 years, 10 months
Hibernate SVN: r16055 - 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-03-02 11:08:45 -0500 (Mon, 02 Mar 2009)
New Revision: 16055
Added:
core/trunk/envers/src/test/java/org/hibernate/envers/test/entities/components/ComponentSetTestEntity.java
core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/components/collections/
core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/components/collections/CollectionOfComponents.java
core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/hashcode/
core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/hashcode/ChangingHashcode.java
core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/hashcode/WikiImage.java
core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/hashcode/WikiPage.java
Modified:
core/trunk/envers/src/main/java/org/hibernate/envers/configuration/metadata/reader/AuditedPropertiesReader.java
core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/AbstractCollectionMapper.java
core/trunk/envers/src/main/java/org/hibernate/envers/event/AuditEventListener.java
Log:
* a disabled tests for collecitons of components
* fixing a bug whit auditing collections when the hashcode of the elements in the colleciton changes
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/configuration/metadata/reader/AuditedPropertiesReader.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/configuration/metadata/reader/AuditedPropertiesReader.java 2009-03-02 14:36:20 UTC (rev 16054)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/configuration/metadata/reader/AuditedPropertiesReader.java 2009-03-02 16:08:45 UTC (rev 16055)
@@ -251,7 +251,7 @@
public Class<? extends Annotation> annotationType() { return this.getClass(); }
};
- private class ComponentPropertiesSource implements PersistentPropertiesSource {
+ private static class ComponentPropertiesSource implements PersistentPropertiesSource {
private final XClass xclass;
private final Component component;
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-03-02 14:36:20 UTC (rev 16054)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/AbstractCollectionMapper.java 2009-03-02 16:08:45 UTC (rev 16055)
@@ -114,13 +114,16 @@
Set<Object> added = new HashSet<Object>();
if (newColl != null) { added.addAll(newCollection); }
- if (oldColl != null) { added.removeAll(oldCollection); }
+ // Re-hashing the old collection as the hash codes of the elements there may have changed, and the
+ // removeAll in AbstractSet has an implementation that is hashcode-change sensitive (as opposed to addAll).
+ if (oldColl != null) { added.removeAll(new HashSet(oldCollection)); }
addCollectionChanges(collectionChanges, added, RevisionType.ADD, id);
Set<Object> deleted = new HashSet<Object>();
if (oldColl != null) { deleted.addAll(oldCollection); }
- if (newColl != null) { deleted.removeAll(newCollection); }
+ // The same as above - re-hashing new collection.
+ if (newColl != null) { deleted.removeAll(new HashSet(newCollection)); }
addCollectionChanges(collectionChanges, deleted, RevisionType.DEL, id);
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-03-02 14:36:20 UTC (rev 16054)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/event/AuditEventListener.java 2009-03-02 16:08:45 UTC (rev 16055)
@@ -57,7 +57,6 @@
import org.hibernate.event.PreCollectionUpdateEvent;
import org.hibernate.event.PreCollectionUpdateEventListener;
import org.hibernate.persister.entity.EntityPersister;
-import org.hibernate.persister.collection.AbstractCollectionPersister;
import org.hibernate.proxy.HibernateProxy;
/**
Copied: core/trunk/envers/src/test/java/org/hibernate/envers/test/entities/components/ComponentSetTestEntity.java (from rev 15911, core/trunk/envers/src/test/java/org/hibernate/envers/test/entities/components/ComponentTestEntity.java)
===================================================================
--- core/trunk/envers/src/test/java/org/hibernate/envers/test/entities/components/ComponentSetTestEntity.java (rev 0)
+++ core/trunk/envers/src/test/java/org/hibernate/envers/test/entities/components/ComponentSetTestEntity.java 2009-03-02 16:08:45 UTC (rev 16055)
@@ -0,0 +1,100 @@
+/*
+ * 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.entities.components;
+
+import javax.persistence.Embedded;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+import org.hibernate.envers.Audited;
+
+import java.util.Set;
+import java.util.HashSet;
+
+/**
+ * @author Adam Warski (adam at warski dot org)
+ */
+@Entity
+@Audited
+public class ComponentSetTestEntity {
+ @Id
+ @GeneratedValue
+ private Integer id;
+
+ @Embedded
+ @Audited
+ private Set<Component1> comps = new HashSet<Component1>();
+
+ public ComponentSetTestEntity() {
+ }
+
+ public ComponentSetTestEntity(Integer id) {
+ this.id = id;
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Set<Component1> getComps() {
+ return comps;
+ }
+
+ public void setComps(Set<Component1> comps) {
+ this.comps = comps;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof ComponentSetTestEntity)) return false;
+
+ ComponentSetTestEntity that = (ComponentSetTestEntity) o;
+
+ if (comps != null ? !comps.equals(that.comps) : that.comps != null) return false;
+ if (id != null ? !id.equals(that.id) : that.id != null) return false;
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = id != null ? id.hashCode() : 0;
+ result = 31 * result + (comps != null ? comps.hashCode() : 0);
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ return "ComponentSetTestEntity{" +
+ "id=" + id +
+ ", comps=" + comps +
+ '}';
+ }
+}
\ No newline at end of file
Property changes on: core/trunk/envers/src/test/java/org/hibernate/envers/test/entities/components/ComponentSetTestEntity.java
___________________________________________________________________
Name: svn:mergeinfo
+
Added: core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/components/collections/CollectionOfComponents.java
===================================================================
--- core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/components/collections/CollectionOfComponents.java (rev 0)
+++ core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/components/collections/CollectionOfComponents.java 2009-03-02 16:08:45 UTC (rev 16055)
@@ -0,0 +1,87 @@
+/*
+ * 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.components.collections;
+
+import java.util.Arrays;
+import java.util.Set;
+import javax.persistence.EntityManager;
+
+import org.hibernate.envers.test.AbstractEntityTest;
+import org.hibernate.envers.test.entities.components.Component1;
+import org.hibernate.envers.test.entities.components.ComponentSetTestEntity;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+import org.hibernate.ejb.Ejb3Configuration;
+
+/**
+ * TODO: enable and implement
+ * @author Adam Warski (adam at warski dot org)
+ */
+public class CollectionOfComponents extends AbstractEntityTest {
+ private Integer id1;
+
+ public void configure(Ejb3Configuration cfg) {
+ cfg.addAnnotatedClass(ComponentSetTestEntity.class);
+ }
+
+ @BeforeClass(dependsOnMethods = "init")
+ public void initData() {
+ // Revision 1
+ EntityManager em = getEntityManager();
+ em.getTransaction().begin();
+
+ ComponentSetTestEntity cte1 = new ComponentSetTestEntity();
+
+ em.persist(cte1);
+
+ em.getTransaction().commit();
+
+ // Revision 2
+ em = getEntityManager();
+ em.getTransaction().begin();
+
+ cte1 = em.find(ComponentSetTestEntity.class, cte1.getId());
+
+ cte1.getComps().add(new Component1("a", "b"));
+
+ em.getTransaction().commit();
+
+ id1 = cte1.getId();
+ }
+
+ @Test(enabled = false)
+ public void testRevisionsCounts() {
+ assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(ComponentSetTestEntity.class, id1));
+ }
+
+ @Test(enabled = false)
+ public void testHistoryOfId1() {
+ assert getAuditReader().find(ComponentSetTestEntity.class, id1, 1).getComps().size() == 0;
+
+ Set<Component1> comps1 = getAuditReader().find(ComponentSetTestEntity.class, id1, 2).getComps();
+ assert comps1.size() == 1;
+ assert comps1.contains(new Component1("a", "b"));
+ }
+}
\ No newline at end of file
Copied: core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/hashcode/ChangingHashcode.java (from rev 16053, core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/ids/CompositeIds.java)
===================================================================
--- core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/hashcode/ChangingHashcode.java (rev 0)
+++ core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/hashcode/ChangingHashcode.java 2009-03-02 16:08:45 UTC (rev 16055)
@@ -0,0 +1,103 @@
+/*
+ * 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.hashcode;
+
+import java.util.Arrays;
+import javax.persistence.EntityManager;
+
+import org.hibernate.envers.test.AbstractEntityTest;
+import org.hibernate.envers.test.tools.TestTools;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+import org.hibernate.ejb.Ejb3Configuration;
+
+/**
+ * @author Adam Warski (adam at warski dot org)
+ */
+public class ChangingHashcode extends AbstractEntityTest {
+ private Long pageId;
+ private Long imageId;
+
+ public void configure(Ejb3Configuration cfg) {
+ cfg.addAnnotatedClass(WikiPage.class);
+ cfg.addAnnotatedClass(WikiImage.class);
+ }
+
+ @BeforeClass(dependsOnMethods = "init")
+ public void initData() {
+ // Revision 1
+ EntityManager em = getEntityManager();
+ em.getTransaction().begin();
+
+ WikiPage page = new WikiPage("title", "content");
+ em.persist(page);
+
+ em.getTransaction().commit();
+
+ // Revision 2
+ em = getEntityManager();
+ em.getTransaction().begin();
+
+ WikiImage image = new WikiImage("name1");
+ em.persist(image);
+
+ page = em.find(WikiPage.class, page.getId());
+ page.getImages().add(image);
+
+ em.getTransaction().commit();
+
+ // Revision 3
+ em = getEntityManager();
+ em.getTransaction().begin();
+
+ image = em.find(WikiImage.class, image.getId());
+ image.setName("name2");
+
+ em.getTransaction().commit();
+
+ pageId = page.getId();
+ imageId = image.getId();
+ }
+
+ @Test
+ public void testRevisionsCounts() {
+ assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(WikiPage.class, pageId));
+ assert Arrays.asList(2, 3).equals(getAuditReader().getRevisions(WikiImage.class, imageId));
+ }
+
+ @Test
+ public void testHistoryOfImage() {
+ assert getAuditReader().find(WikiImage.class, imageId, 1) == null;
+ assert getAuditReader().find(WikiImage.class, imageId, 2).equals(new WikiImage("name1"));
+ assert getAuditReader().find(WikiImage.class, imageId, 3).equals(new WikiImage("name2"));
+ }
+
+ @Test
+ public void testHistoryOfPage() {
+ assert getAuditReader().find(WikiPage.class, pageId, 1).getImages().size() == 0;
+ assert getAuditReader().find(WikiPage.class, pageId, 2).getImages().equals(TestTools.makeSet(new WikiImage("name1")));
+ assert getAuditReader().find(WikiPage.class, pageId, 3).getImages().equals(TestTools.makeSet(new WikiImage("name2")));
+ }
+}
\ No newline at end of file
Added: core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/hashcode/WikiImage.java
===================================================================
--- core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/hashcode/WikiImage.java (rev 0)
+++ core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/hashcode/WikiImage.java 2009-03-02 16:08:45 UTC (rev 16055)
@@ -0,0 +1,65 @@
+package org.hibernate.envers.test.integration.hashcode;
+
+import org.hibernate.envers.Audited;
+
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Entity;
+import javax.persistence.Basic;
+
+/**
+ * @author Adam Warski (adam at warski dot org)
+ */
+@Entity
+@Audited
+public class WikiImage {
+ @Id
+ @GeneratedValue
+ private Long id;
+
+ @Basic
+ private String name;
+
+ public WikiImage() {
+ }
+
+ public WikiImage(String name) {
+ this.name = name;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof WikiImage)) return false;
+
+ WikiImage wikiImage = (WikiImage) o;
+
+ if (name != null ? !name.equals(wikiImage.name) : wikiImage.name != null) return false;
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ return name != null ? name.hashCode() : 0;
+ }
+
+ @Override
+ public String toString() {
+ return "WikiImage{" +
+ "name='" + name + '\'' +
+ '}';
+ }
+}
Added: core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/hashcode/WikiPage.java
===================================================================
--- core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/hashcode/WikiPage.java (rev 0)
+++ core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/hashcode/WikiPage.java 2009-03-02 16:08:45 UTC (rev 16055)
@@ -0,0 +1,109 @@
+package org.hibernate.envers.test.integration.hashcode;
+
+import org.hibernate.annotations.CollectionOfElements;
+import org.hibernate.envers.Audited;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+import javax.persistence.Basic;
+import java.util.Set;
+import java.util.HashSet;
+
+/**
+ * @author Adam Warski (adam at warski dot org)
+ */
+@Entity
+@Audited
+public class WikiPage {
+ @Id
+ @GeneratedValue
+ private Long id;
+
+ @Basic
+ private String title;
+
+ @Basic
+ private String content;
+
+ @CollectionOfElements
+ private Set<String> links = new HashSet<String>();
+
+ @OneToMany
+ private Set<WikiImage> images = new HashSet<WikiImage>();
+
+ public WikiPage() {
+ }
+
+ public WikiPage(String title, String content) {
+ this.title = title;
+ this.content = content;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public String getContent() {
+ return content;
+ }
+
+ public void setContent(String content) {
+ this.content = content;
+ }
+
+ public Set<String> getLinks() {
+ return links;
+ }
+
+ public void setLinks(Set<String> links) {
+ this.links = links;
+ }
+
+ public Set<WikiImage> getImages() {
+ return images;
+ }
+
+ public void setImages(Set<WikiImage> images) {
+ this.images = images;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof WikiPage)) return false;
+
+ WikiPage wikiPage = (WikiPage) o;
+
+ if (content != null ? !content.equals(wikiPage.content) : wikiPage.content != null) return false;
+ if (title != null ? !title.equals(wikiPage.title) : wikiPage.title != null) return false;
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = title != null ? title.hashCode() : 0;
+ result = 31 * result + (content != null ? content.hashCode() : 0);
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ return "WikiPage{" +
+ "title='" + title + '\'' +
+ ", content='" + content + '\'' +
+ ", links=" + links +
+ ", images=" + images +
+ '}';
+ }
+}
15 years, 10 months
Hibernate SVN: r16054 - in branches/Branch_3_2/HibernateExt/tools/src: test/org/hibernate/tool/hbm2x/hbm2hbmxml and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: max.andersen(a)jboss.com
Date: 2009-03-02 09:36:20 -0500 (Mon, 02 Mar 2009)
New Revision: 16054
Added:
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest.java
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Car.hbm.xml
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Car.java
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/CarPart.java
Modified:
branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/JDBCBinder.java
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Cfg2HbmAllTests.java
Log:
backref tests and changed back to use "all" as default for cascades to not break seam/jpa users.
Modified: branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/JDBCBinder.java
===================================================================
--- branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/JDBCBinder.java 2009-03-02 10:31:56 UTC (rev 16053)
+++ branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/JDBCBinder.java 2009-03-02 14:36:20 UTC (rev 16054)
@@ -65,9 +65,9 @@
private Settings settings;
private ConnectionProvider connectionProvider;
private static final Log log = LogFactory.getLog(JDBCBinder.class);
-
+
private final Mappings mappings;
-
+
private final JDBCMetaDataConfiguration cfg;
private ReverseEngineeringStrategy revengStrategy;
@@ -83,54 +83,54 @@
}
/**
- *
+ *
*/
public void readFromDatabase(String catalog, String schema, Mapping mapping) {
-
+
this.connectionProvider = settings.getConnectionProvider();
-
+
try {
-
- DatabaseCollector collector = readDatabaseSchema(catalog, schema);
+
+ DatabaseCollector collector = readDatabaseSchema(catalog, schema);
createPersistentClasses(collector, mapping); //move this to a different step!
- }
+ }
catch (SQLException e) {
throw settings.getSQLExceptionConverter().convert(e, "Reading from database", null);
- }
+ }
finally {
if(connectionProvider!=null) connectionProvider.close();
}
-
+
}
/**
* Read JDBC Metadata from the database. Does not create any classes or other ORM releated structures.
- *
+ *
* @param catalog
* @param schema
- * @return
+ * @return
* @throws SQLException
*/
public DatabaseCollector readDatabaseSchema(String catalog, String schema) throws SQLException {
// use default from settings if nothing else specified.
catalog = catalog!=null ? catalog : settings.getDefaultCatalogName();
schema = schema!=null ? schema : settings.getDefaultSchemaName();
-
+
JDBCReader reader = JDBCReaderFactory.newJDBCReader(cfg.getProperties(),settings,revengStrategy);
- DatabaseCollector dbs = new MappingsDatabaseCollector(mappings);
+ DatabaseCollector dbs = new MappingsDatabaseCollector(mappings);
reader.readDatabaseSchema(dbs, catalog, schema);
return dbs;
}
-
+
/**
* @param manyToOneCandidates
* @param mappings2
*/
private void createPersistentClasses(DatabaseCollector collector, Mapping mapping) {
Map manyToOneCandidates = collector.getOneToManyCandidates();
-
+
for (Iterator iter = mappings.iterateTables(); iter.hasNext();) {
Table table = (Table) iter.next();
if(table.getColumnSpan()==0) {
@@ -144,23 +144,23 @@
continue;
// TODO: just create one big embedded composite id instead.
}*/
-
+
if(revengStrategy.isManyToManyTable(table)) {
log.debug( "Ignoring " + table + " as class since rev.eng. says it is a many-to-many" );
continue;
- }
-
+ }
+
RootClass rc = new RootClass();
TableIdentifier tableIdentifier = TableIdentifier.create(table);
String className = revengStrategy.tableToClassName( tableIdentifier );
rc.setEntityName( className );
- rc.setClassName( className );
+ rc.setClassName( className );
rc.setProxyInterfaceName( rc.getEntityName() ); // TODO: configurable ?
rc.setLazy(true);
-
+
rc.setMetaAttributes( safeMeta(revengStrategy.tableToMetaAttributes( tableIdentifier )) );
-
-
+
+
rc.setDiscriminatorValue( rc.getEntityName() );
rc.setTable(table);
try {
@@ -169,13 +169,13 @@
// TODO: detect this and generate a "permutation" of it ?
PersistentClass class1 = mappings.getClass(dme.getName());
Table table2 = class1.getTable();
- throw new JDBCBinderException("Duplicate class name '" + rc.getEntityName() + "' generated for '" + table + "'. Same name where generated for '" + table2 + "'");
+ throw new JDBCBinderException("Duplicate class name '" + rc.getEntityName() + "' generated for '" + table + "'. Same name where generated for '" + table2 + "'");
}
mappings.addImport( rc.getEntityName(), rc.getEntityName() );
-
+
Set processed = new HashSet();
-
-
+
+
PrimaryKeyInfo pki = bindPrimaryKeyToProperties(table, rc, processed, mapping, collector);
bindColumnsToVersioning(table, rc, processed, mapping);
bindOutgoingForeignKeys(table, rc, processed);
@@ -183,29 +183,29 @@
List incomingForeignKeys = (List) manyToOneCandidates.get( rc.getEntityName() );
bindIncomingForeignKeys(rc, processed, incomingForeignKeys, mapping);
updatePrimaryKey(rc, pki);
-
+
}
-
+
}
private void updatePrimaryKey(RootClass rc, PrimaryKeyInfo pki) {
SimpleValue idValue = (SimpleValue) rc.getIdentifierProperty().getValue();
-
+
Properties defaultStrategyProperties = new Properties();
- Property constrainedOneToOne = getConstrainedOneToOne(rc);
+ Property constrainedOneToOne = getConstrainedOneToOne(rc);
if(constrainedOneToOne!=null) {
if(pki.suggestedStrategy==null) {
- idValue.setIdentifierGeneratorStrategy("foreign");
+ idValue.setIdentifierGeneratorStrategy("foreign");
}
-
+
if(pki.suggestedProperties==null) {
defaultStrategyProperties.setProperty("property", constrainedOneToOne.getName());
idValue.setIdentifierGeneratorProperties(defaultStrategyProperties);
}
}
-
-
-
+
+
+
}
private Property getConstrainedOneToOne(RootClass rc) {
@@ -221,7 +221,7 @@
}
return null;
}
-
+
private Map safeMeta(Map map) {
if(map==null) {
return new HashMap();
@@ -235,18 +235,18 @@
if(foreignKeys!=null) {
for (Iterator iter = foreignKeys.iterator(); iter.hasNext();) {
ForeignKey foreignKey = (ForeignKey) iter.next();
-
+
if(revengStrategy.excludeForeignKeyAsCollection(
- foreignKey.getName(),
- TableIdentifier.create(foreignKey.getTable() ),
- foreignKey.getColumns(),
+ foreignKey.getName(),
+ TableIdentifier.create(foreignKey.getTable() ),
+ foreignKey.getColumns(),
TableIdentifier.create(foreignKey.getReferencedTable() ),
foreignKey.getReferencedColumns())) {
log.debug("Rev.eng excluded one-to-many or one-to-one for foreignkey " + foreignKey.getName());
} else if (revengStrategy.isOneToOne(foreignKey)){
Property property = bindOneToOne(rc, foreignKey.getTable(), foreignKey, processed, false, true);
rc.addProperty(property);
- } else {
+ } else {
Property property = bindOneToMany(rc, foreignKey, processed, mapping);
rc.addProperty(property);
}
@@ -254,11 +254,11 @@
}
}
-
+
private Property bindOneToOne(PersistentClass rc, Table targetTable,
ForeignKey fk, Set processedColumns, boolean constrained, boolean inverseProperty) {
-
+
OneToOne value = new OneToOne(targetTable, rc);
value.setReferencedEntityName(revengStrategy
.tableToClassName(TableIdentifier.create(targetTable)));
@@ -286,63 +286,64 @@
}
value.setFetchMode(FetchMode.SELECT);
-
+
value.setConstrained(constrained);
value.setForeignKeyType( constrained ?
ForeignKeyDirection.FOREIGN_KEY_FROM_PARENT :
ForeignKeyDirection.FOREIGN_KEY_TO_PARENT );
-
+
return makeEntityProperty(propertyName, true, targetTable, fk, value, inverseProperty);
//return makeProperty(TableIdentifier.create(targetTable), propertyName, value,
// true, true, value.getFetchMode() != FetchMode.JOIN, null, null);
}
/**
- * @param mutable
+ * @param mutable
* @param table
* @param fk
- * @param columnsToBind
+ * @param columnsToBind
* @param processedColumns
* @param rc
- * @param propName
+ * @param propName
*/
private Property bindManyToOne(String propertyName, boolean mutable, Table table, ForeignKey fk, Set processedColumns) {
ManyToOne value = new ManyToOne(table);
value.setReferencedEntityName( fk.getReferencedEntityName() );
Iterator columns = fk.getColumnIterator();
- while ( columns.hasNext() ) {
+ while ( columns.hasNext() ) {
Column fkcolumn = (Column) columns.next();
checkColumn(fkcolumn);
value.addColumn(fkcolumn);
processedColumns.add(fkcolumn);
}
value.setFetchMode(FetchMode.SELECT);
-
+
return makeEntityProperty(propertyName, mutable, table, fk, value, false);
}
private Property makeCollectionProperty(String propertyName, boolean mutable,
Table table, ForeignKey fk, Collection value, boolean inverseProperty) {
AssociationInfo fkei = inverseProperty?revengStrategy.foreignKeyToInverseAssociationInfo(fk):revengStrategy.foreignKeyToAssociationInfo(fk);
-
+
String fetchMode = null;
String cascade = null;
boolean update = mutable;
boolean insert = mutable;
- if(fkei != null){
+ if(fkei != null){
cascade = fkei.getCascade();
+ if(cascade==null) cascade = "all"; //To ensure collections cascade to be compatible with Seam-gen and previous behavior.
if(fkei.getUpdate()!=null) {
update = fkei.getUpdate().booleanValue();
}
if(fkei.getInsert()!=null) {
insert = fkei.getInsert().booleanValue();
}
-
+
fetchMode = fkei.getFetch();
-
-
+
+
}
if(FetchMode.JOIN.toString().equalsIgnoreCase(fetchMode)) {
@@ -362,13 +363,13 @@
private Property makeEntityProperty(String propertyName, boolean mutable,
Table table, ForeignKey fk, ToOne value, boolean inverseProperty) {
AssociationInfo fkei = inverseProperty?revengStrategy.foreignKeyToInverseAssociationInfo(fk):revengStrategy.foreignKeyToAssociationInfo(fk);
-
+
String fetchMode = null;
String cascade = null;
boolean update = mutable;
boolean insert = mutable;
- if(fkei != null){
+ if(fkei != null){
cascade = fkei.getCascade();
if(fkei.getUpdate()!=null) {
update = fkei.getUpdate().booleanValue();
@@ -376,10 +377,10 @@
if(fkei.getInsert()!=null) {
insert = fkei.getInsert().booleanValue();
}
-
+
fetchMode = fkei.getFetch();
-
-
+
+
}
if(FetchMode.JOIN.toString().equalsIgnoreCase(fetchMode)) {
@@ -402,25 +403,25 @@
* @param object
*/
private Property bindOneToMany(PersistentClass rc, ForeignKey foreignKey, Set processed, Mapping mapping) {
-
+
Table collectionTable = foreignKey.getTable();
Collection collection = new org.hibernate.mapping.Set(rc); // MASTER TODO: allow overriding collection type
collection.setCollectionTable(collectionTable); // CHILD+
-
-
-
+
+
+
boolean manyToMany = revengStrategy.isManyToManyTable( collectionTable );
if(manyToMany) {
//log.debug("Rev.eng said here is a many-to-many");
// TODO: handle "the other side should influence the name"
}
-
+
if(manyToMany) {
-
+
ManyToOne element = new ManyToOne( collection.getCollectionTable() );
//TODO: find the other foreignkey and choose the other side.
Iterator foreignKeyIterator = foreignKey.getTable().getForeignKeyIterator();
@@ -428,30 +429,30 @@
while ( foreignKeyIterator.hasNext() ) {
Object next = foreignKeyIterator.next();
if(next!=foreignKey) {
- keys.add(next);
+ keys.add(next);
}
}
-
+
if(keys.size()>1) {
throw new JDBCBinderException("more than one other foreign key to choose from!"); // todo: handle better ?
}
-
+
ForeignKey fk = (ForeignKey) keys.get( 0 );
String tableToClassName = bindCollection( rc, foreignKey, fk, collection );
-
+
element.setReferencedEntityName( tableToClassName );
element.addColumn( fk.getColumn( 0 ) );
collection.setElement( element );
-
+
} else {
String tableToClassName = bindCollection( rc, foreignKey, null, collection );
-
+
OneToMany oneToMany = new OneToMany( collection.getOwner() );
-
+
oneToMany.setReferencedEntityName( tableToClassName ); // Child
mappings.addSecondPass( new JDBCCollectionSecondPass(mappings, collection) );
-
+
collection.setElement(oneToMany);
}
// bind keyvalue
@@ -469,7 +470,7 @@
SimpleValue keyValue = new DependantValue( collectionTable, referencedKeyValue );
//keyValue.setForeignKeyName("none"); // Avoid creating the foreignkey
//key.setCascadeDeleteEnabled( "cascade".equals( subnode.attributeValue("on-delete") ) );
- Iterator columnIterator = foreignKey.getColumnIterator();
+ Iterator columnIterator = foreignKey.getColumnIterator();
while ( columnIterator.hasNext() ) {
Column fkcolumn = (Column) columnIterator.next();
if(fkcolumn.getSqlTypeCode()!=null) { // TODO: user defined foreign ref columns does not have a type set.
@@ -477,18 +478,18 @@
}
keyValue.addColumn( fkcolumn );
}
-
+
collection.setKey(keyValue);
-
+
mappings.addCollection(collection);
-
- return makeCollectionProperty(StringHelper.unqualify( collection.getRole() ), true, rc.getTable(), foreignKey, collection, true);
+
+ return makeCollectionProperty(StringHelper.unqualify( collection.getRole() ), true, rc.getTable(), foreignKey, collection, true);
//return makeProperty(TableIdentifier.create( rc.getTable() ), StringHelper.unqualify( collection.getRole() ), collection, true, true, true, "none", null); // TODO: cascade isn't all by default
-
-
+
+
}
-
+
private String bindCollection(PersistentClass rc, ForeignKey fromForeignKey, ForeignKey toForeignKey, Collection collection) {
ForeignKey targetKey = fromForeignKey;
String collectionRole = null;
@@ -496,66 +497,66 @@
boolean collectionInverse = false;
TableIdentifier foreignKeyTable = null;
String tableToClassName;
-
+
if(toForeignKey!=null) {
targetKey = toForeignKey;
}
-
+
boolean uniqueReference = isUniqueReference(targetKey); // TODO: need to look one step further for many-to-many!
foreignKeyTable = TableIdentifier.create( targetKey.getTable() );
TableIdentifier foreignKeyReferencedTable = TableIdentifier.create( targetKey.getReferencedTable() );
-
+
if(toForeignKey==null) {
-
+
collectionRole = revengStrategy.foreignKeyToCollectionName(
- fromForeignKey.getName(),
- foreignKeyTable,
- fromForeignKey.getColumns(),
- foreignKeyReferencedTable,
- fromForeignKey.getReferencedColumns(),
+ fromForeignKey.getName(),
+ foreignKeyTable,
+ fromForeignKey.getColumns(),
+ foreignKeyReferencedTable,
+ fromForeignKey.getReferencedColumns(),
uniqueReference
);
-
+
tableToClassName = revengStrategy.tableToClassName( foreignKeyTable );
} else {
-
- collectionRole = revengStrategy.foreignKeyToManyToManyName(
+
+ collectionRole = revengStrategy.foreignKeyToManyToManyName(
fromForeignKey, TableIdentifier.create( fromForeignKey.getTable()), toForeignKey, uniqueReference );
-
+
tableToClassName = revengStrategy.tableToClassName( foreignKeyReferencedTable );
}
- collectionInverse = revengStrategy.isForeignKeyCollectionInverse(targetKey.getName(),
- foreignKeyTable,
- targetKey.getColumns(),
- foreignKeyReferencedTable,
+ collectionInverse = revengStrategy.isForeignKeyCollectionInverse(targetKey.getName(),
+ foreignKeyTable,
+ targetKey.getColumns(),
+ foreignKeyReferencedTable,
targetKey.getReferencedColumns());
-
- collectionLazy = revengStrategy.isForeignKeyCollectionLazy(targetKey.getName(),
- foreignKeyTable,
- targetKey.getColumns(),
- foreignKeyReferencedTable,
+
+ collectionLazy = revengStrategy.isForeignKeyCollectionLazy(targetKey.getName(),
+ foreignKeyTable,
+ targetKey.getColumns(),
+ foreignKeyReferencedTable,
targetKey.getReferencedColumns());
-
+
collectionRole = makeUnique(rc,collectionRole);
-
+
String fullRolePath = StringHelper.qualify(rc.getEntityName(), collectionRole);
if (mappings.getCollection(fullRolePath)!=null) {
log.debug(fullRolePath + " found twice!");
}
-
- collection.setRole(fullRolePath); // Master.setOfChildren+
+
+ collection.setRole(fullRolePath); // Master.setOfChildren+
collection.setInverse(collectionInverse); // TODO: allow overriding this
- collection.setLazy(collectionLazy);
+ collection.setLazy(collectionLazy);
collection.setFetchMode(FetchMode.SELECT);
-
-
+
+
return tableToClassName;
}
/** return true if this foreignkey is the only reference from this table to the same foreign table */
private boolean isUniqueReference(ForeignKey foreignKey) {
-
+
Iterator foreignKeyIterator = foreignKey.getTable().getForeignKeyIterator();
while ( foreignKeyIterator.hasNext() ) {
ForeignKey element = (ForeignKey) foreignKeyIterator.next();
@@ -567,22 +568,22 @@
}
static private class PrimaryKeyInfo {
-
+
String suggestedStrategy = null;
- Properties suggestedProperties = null;
+ Properties suggestedProperties = null;
}
-
-
+
+
private PrimaryKeyInfo bindPrimaryKeyToProperties(Table table, RootClass rc, Set processed, Mapping mapping, DatabaseCollector collector) {
SimpleValue id = null;
String idPropertyname = null;
-
+
PrimaryKeyInfo pki = new PrimaryKeyInfo();
-
+
List keyColumns = null;
if (table.getPrimaryKey()!=null) {
keyColumns = table.getPrimaryKey().getColumns();
- }
+ }
else {
log.debug("No primary key found for " + table + ", using all properties as the identifier.");
keyColumns = new ArrayList();
@@ -594,21 +595,21 @@
}
final TableIdentifier tableIdentifier = TableIdentifier.create(table);
-
+
String tableIdentifierStrategyName = "assigned";
-
+
boolean naturalId;
-
+
if (keyColumns.size()>1) {
log.debug("id strategy for " + rc.getEntityName() + " since it has a multiple column primary key");
naturalId = true;
-
+
id = handleCompositeKey(rc, processed, keyColumns, mapping);
idPropertyname = revengStrategy.tableToIdentifierPropertyName(tableIdentifier);
if(idPropertyname==null) {
idPropertyname = "id";
}
- }
+ }
else {
pki.suggestedStrategy = revengStrategy.getTableIdentifierStrategyName(tableIdentifier);
String suggestedStrategy = pki.suggestedStrategy;
@@ -621,31 +622,31 @@
} else {
tableIdentifierStrategyName = suggestedStrategy;
}
-
+
naturalId = "assigned".equals( tableIdentifierStrategyName );
Column pkc = (Column) keyColumns.get(0);
checkColumn(pkc);
-
+
id = bindColumnToSimpleValue(table, pkc, mapping, !naturalId);
idPropertyname = revengStrategy.tableToIdentifierPropertyName(tableIdentifier);
if(idPropertyname==null) {
idPropertyname = revengStrategy.columnToPropertyName(tableIdentifier, pkc.getName() );
}
-
+
processed.add(pkc);
- }
+ }
id.setIdentifierGeneratorStrategy(tableIdentifierStrategyName);
pki.suggestedProperties = revengStrategy.getTableIdentifierProperties(tableIdentifier);
- id.setIdentifierGeneratorProperties(pki.suggestedProperties);
+ id.setIdentifierGeneratorProperties(pki.suggestedProperties);
if(naturalId) {
id.setNullValue("undefined");
}
-
+
Property property = makeProperty(tableIdentifier, makeUnique(rc,idPropertyname), id, true, true, false, null, null);
- rc.setIdentifierProperty(property);
+ rc.setIdentifierProperty(property);
rc.setIdentifier(id);
-
+
return pki;
}
@@ -656,20 +657,20 @@
* @param primaryKey
*/
private void bindOutgoingForeignKeys(Table table, RootClass rc, Set processedColumns) {
-
- // Iterate the outgoing foreign keys and create many-to-one's
+
+ // Iterate the outgoing foreign keys and create many-to-one's
for(Iterator iterator = table.getForeignKeyIterator(); iterator.hasNext();) {
ForeignKey foreignKey = (ForeignKey) iterator.next();
-
+
boolean mutable = true;
if ( contains( foreignKey.getColumnIterator(), processedColumns ) ) {
if ( !cfg.preferBasicCompositeIds() ) continue; //it's in the pk, so skip this one
- mutable = false;
+ mutable = false;
}
-
- if(revengStrategy.excludeForeignKeyAsManytoOne(foreignKey.getName(),
- TableIdentifier.create(foreignKey.getTable() ),
- foreignKey.getColumns(),
+
+ if(revengStrategy.excludeForeignKeyAsManytoOne(foreignKey.getName(),
+ TableIdentifier.create(foreignKey.getTable() ),
+ foreignKey.getColumns(),
TableIdentifier.create(foreignKey.getReferencedTable() ),
foreignKey.getReferencedColumns())) {
// TODO: if many-to-one is excluded should the column be marked as processed so it won't show up at all ?
@@ -680,59 +681,59 @@
} else {
boolean isUnique = isUniqueReference(foreignKey);
String propertyName = revengStrategy.foreignKeyToEntityName(
- foreignKey.getName(),
- TableIdentifier.create(foreignKey.getTable() ),
- foreignKey.getColumns(),
+ foreignKey.getName(),
+ TableIdentifier.create(foreignKey.getTable() ),
+ foreignKey.getColumns(),
TableIdentifier.create(foreignKey.getReferencedTable() ),
- foreignKey.getReferencedColumns(),
+ foreignKey.getReferencedColumns(),
isUnique
);
-
+
Property property = bindManyToOne(
makeUnique(rc, propertyName),
mutable,
- table,
+ table,
foreignKey,
processedColumns
);
-
+
rc.addProperty(property);
}
}
}
-
+
/**
* @param table
* @param rc
* @param primaryKey
*/
private void bindColumnsToProperties(Table table, RootClass rc, Set processedColumns, Mapping mapping) {
-
+
for (Iterator iterator = table.getColumnIterator(); iterator.hasNext();) {
Column column = (Column) iterator.next();
if ( !processedColumns.contains(column) ) {
checkColumn(column);
-
+
String propertyName = revengStrategy.columnToPropertyName(TableIdentifier.create(table), column.getName() );
-
- Property property = bindBasicProperty(
- makeUnique(rc,propertyName),
- table,
- column,
+
+ Property property = bindBasicProperty(
+ makeUnique(rc,propertyName),
+ table,
+ column,
processedColumns,
mapping
);
-
+
rc.addProperty(property);
- }
+ }
}
}
-
+
private void bindColumnsToVersioning(Table table, RootClass rc, Set processed, Mapping mapping) {
TableIdentifier identifier = TableIdentifier.create(table);
-
+
String optimisticLockColumnName = revengStrategy.getOptimisticLockColumnName(identifier);
-
+
if(optimisticLockColumnName!=null) {
Column column = table.getColumn(new Column(optimisticLockColumnName));
if(column==null) {
@@ -748,7 +749,7 @@
boolean useIt = revengStrategy.useColumnForOptimisticLock(identifier, column.getName());
if(useIt && !processed.contains(column)) {
bindVersionProperty( table, identifier, column, rc, processed, mapping );
- return;
+ return;
}
}
log.debug("No columns reported while scanning for <version>/<timestamp> columns in " + identifier);
@@ -756,7 +757,7 @@
}
private void bindVersionProperty(Table table, TableIdentifier identifier, Column column, RootClass rc, Set processed, Mapping mapping) {
-
+
processed.add(column);
String propertyName = revengStrategy.columnToPropertyName( identifier, column.getName() );
Property property = bindBasicProperty(makeUnique(rc, propertyName), table, column, processed, mapping);
@@ -764,18 +765,18 @@
rc.setVersion(property);
rc.setOptimisticLockMode(Versioning.OPTIMISTIC_LOCK_VERSION);
log.debug("Column " + column.getName() + " will be used for <version>/<timestamp> columns in " + identifier);
-
+
}
private Property bindBasicProperty(String propertyName, Table table, Column column, Set processedColumns, Mapping mapping) {
SimpleValue value = bindColumnToSimpleValue( table, column, mapping, false );
-
+
return makeProperty(TableIdentifier.create( table ), propertyName, value, true, true, false, null, null);
}
private SimpleValue bindColumnToSimpleValue(Table table, Column column, Mapping mapping, boolean generatedIdentifier) {
- SimpleValue value = new SimpleValue(table);
+ SimpleValue value = new SimpleValue(table);
value.addColumn(column);
value.setTypeName(guessAndAlignType(table, column, mapping, generatedIdentifier));
return value;
@@ -804,50 +805,50 @@
/**
* @param column
- * @param generatedIdentifier
+ * @param generatedIdentifier
* @return
*/
private String guessAndAlignType(Table table, Column column, Mapping mapping, boolean generatedIdentifier) {
- // TODO: this method mutates the column if the types does not match...not good.
+ // TODO: this method mutates the column if the types does not match...not good.
// maybe we should copy the column instead before calling this method.
Integer sqlTypeCode = column.getSqlTypeCode();
String location = "Table: " + Table.qualify(table.getCatalog(), table.getSchema(), table.getQuotedName() ) + " column: " + column.getQuotedName();
if(sqlTypeCode==null) {
throw new JDBCBinderException("sqltype is null for " + location);
}
-
+
String preferredHibernateType = revengStrategy.columnToHibernateTypeName(
- TableIdentifier.create(table),
- column.getName(),
+ TableIdentifier.create(table),
+ column.getName(),
sqlTypeCode.intValue(),
column.getLength(), column.getPrecision(), column.getScale(), column.isNullable(), generatedIdentifier
);
-
+
Type wantedType = TypeFactory.heuristicType(preferredHibernateType);
-
+
if(wantedType!=null) {
int[] wantedSqlTypes = wantedType.sqlTypes(mapping);
-
+
if(wantedSqlTypes.length>1) {
- throw new JDBCBinderException("The type " + preferredHibernateType + " found on " + location + " spans multiple columns. Only single column types allowed.");
+ throw new JDBCBinderException("The type " + preferredHibernateType + " found on " + location + " spans multiple columns. Only single column types allowed.");
}
-
+
int wantedSqlType = wantedSqlTypes[0];
- if(wantedSqlType!=sqlTypeCode.intValue() ) {
+ if(wantedSqlType!=sqlTypeCode.intValue() ) {
log.debug("Sql type mismatch for " + location + " between DB and wanted hibernate type. Sql type set to " + typeCodeName( sqlTypeCode.intValue() ) + " instead of " + typeCodeName(wantedSqlType) );
column.setSqlTypeCode(new Integer(wantedSqlType));
}
- }
+ }
else {
log.debug("No Hibernate type found for " + preferredHibernateType + ". Most likely cause is a missing UserType class.");
}
-
-
-
+
+
+
if(preferredHibernateType==null) {
throw new JDBCBinderException("Could not find javatype for " + typeCodeName(sqlTypeCode.intValue()));
}
-
+
return preferredHibernateType;
}
@@ -858,25 +859,25 @@
/**
* Basically create an [classname]Id.class and add properties for it.
* @param rc
- * @param compositeKeyColumns
+ * @param compositeKeyColumns
* @param processed
* @return
*/
private SimpleValue handleCompositeKey(RootClass rc, Set processedColumns, List keyColumns, Mapping mapping) {
Component pkc = new Component(rc);
pkc.setMetaAttributes(Collections.EMPTY_MAP);
- pkc.setEmbedded(false);
-
+ pkc.setEmbedded(false);
+
String compositeIdName = revengStrategy.tableToCompositeIdName(TableIdentifier.create(rc.getTable()));
if(compositeIdName==null) {
compositeIdName = revengStrategy.classNameToCompositeIdName(rc.getClassName());
}
pkc.setComponentClassName(compositeIdName);
- Table table = rc.getTable();
- List list = null;
+ Table table = rc.getTable();
+ List list = null;
if (cfg.preferBasicCompositeIds() ) {
list = new ArrayList(keyColumns);
- }
+ }
else {
list = findForeignKeys(table.getForeignKeyIterator(), keyColumns);
}
@@ -886,22 +887,22 @@
if (element instanceof Column) {
Column column = (Column) element;
if ( processedColumns.contains(column) ) {
- throw new JDBCBinderException("Binding column twice for primary key should not happen: " + column);
- }
+ throw new JDBCBinderException("Binding column twice for primary key should not happen: " + column);
+ }
else {
checkColumn(column);
-
+
String propertyName = revengStrategy.columnToPropertyName( TableIdentifier.create(table), column.getName() );
property = bindBasicProperty( makeUnique(pkc, propertyName), table, column, processedColumns, mapping);
-
+
processedColumns.add(column);
}
- }
+ }
else if (element instanceof ForeignKeyForColumns) {
ForeignKeyForColumns fkfc = (ForeignKeyForColumns) element;
ForeignKey foreignKey = fkfc.key;
String propertyName = revengStrategy.foreignKeyToEntityName(
- foreignKey.getName(),
+ foreignKey.getName(),
TableIdentifier.create(foreignKey.getTable() ),
foreignKey.getColumns(), TableIdentifier.create(foreignKey.getReferencedTable() ), foreignKey.getReferencedColumns(), true
);
@@ -911,10 +912,10 @@
else {
throw new JDBCBinderException("unknown thing");
}
-
+
markAsUseInEquals(property);
pkc.addProperty(property);
-
+
}
return pkc;
@@ -934,22 +935,22 @@
/**
* @param foreignKeyIterator
* @param columns
- * @return
+ * @return
*/
private List findForeignKeys(Iterator foreignKeyIterator, List pkColumns) {
-
+
List tempList = new ArrayList();
while(foreignKeyIterator.hasNext()) {
tempList.add(foreignKeyIterator.next());
}
-
-// Collections.reverse(tempList);
-
+
+// Collections.reverse(tempList);
+
List result = new ArrayList();
Column myPkColumns[] = (Column[]) pkColumns.toArray(new Column[pkColumns.size()]);
-
+
for (int i = 0; i < myPkColumns.length; i++) {
-
+
boolean foundKey = false;
foreignKeyIterator = tempList.iterator();
while(foreignKeyIterator.hasNext()) {
@@ -961,23 +962,23 @@
foreignKeyIterator.remove();
foundKey=true;
break;
- }
+ }
}
if(!foundKey) {
- result.add(myPkColumns[i]);
+ result.add(myPkColumns[i]);
}
-
+
}
-
+
return result;
}
private List columnMatches(Column[] myPkColumns, int offset, ForeignKey key) {
-
+
if(key.getColumnSpan()>(myPkColumns.length-offset)) {
return null; // not enough columns in the key
}
-
+
List columns = new ArrayList();
for (int j = 0; j < key.getColumnSpan(); j++) {
Column column = myPkColumns[j+offset];
@@ -991,7 +992,7 @@
}
static class ForeignKeyForColumns {
-
+
protected final List columns;
protected final ForeignKey key;
@@ -1008,25 +1009,25 @@
prop.setValue(value);
prop.setInsertable(insertable);
prop.setUpdateable(updatable);
- prop.setLazy(lazy);
+ prop.setLazy(lazy);
prop.setCascade(cascade==null?"none":cascade);
- prop.setPropertyAccessorName(propertyAccessorName==null?"property":propertyAccessorName);
+ prop.setPropertyAccessorName(propertyAccessorName==null?"property":propertyAccessorName);
bindMeta(prop, table);
-
+
return prop;
}
-
+
private Property bindMeta(Property property, TableIdentifier identifier) {
Iterator columnIterator = property.getValue().getColumnIterator();
while(columnIterator.hasNext()) {
Column col = (Column) columnIterator.next();
-
+
Map map = revengStrategy.columnToMetaAttributes( identifier, col.getName() );
if(map!=null) { // TODO: merge from each column ?
property.setMetaAttributes( map );
}
}
-
+
return property;
}
@@ -1041,15 +1042,15 @@
private String makeUnique(PersistentClass clazz, String propertyName) {
List list = new ArrayList();
-
+
if( clazz.hasIdentifierProperty() ) {
list.add( clazz.getIdentifierProperty() );
}
-
+
if( clazz.isVersioned() ) {
list.add( clazz.getVersion() );
}
-
+
JoinedIterator iterator = new JoinedIterator( list.iterator(),clazz.getPropertyClosureIterator() );
return makeUnique(iterator, propertyName);
}
@@ -1062,18 +1063,18 @@
int cnt = 0;
String propertyName = originalPropertyName;
Set uniqueNames = new HashSet();
-
+
while ( props.hasNext() ) {
Property element = (Property) props.next();
uniqueNames.add( element.getName() );
}
-
- while( uniqueNames.contains(propertyName) ) {
+
+ while( uniqueNames.contains(propertyName) ) {
cnt++;
propertyName = originalPropertyName + "_" + cnt;
}
-
- return propertyName;
+
+ return propertyName;
}
public static void bindCollectionSecondPass(
@@ -1084,15 +1085,15 @@
if(collection.isOneToMany() ) {
OneToMany oneToMany = (OneToMany) collection.getElement();
- PersistentClass persistentClass = mappings.getClass(oneToMany.getReferencedEntityName() );
-
+ PersistentClass persistentClass = mappings.getClass(oneToMany.getReferencedEntityName() );
+
if (persistentClass==null) throw new MappingException(
"Association " + collection.getRole() + " references unmapped class: " + oneToMany.getReferencedEntityName()
);
-
- oneToMany.setAssociatedClass(persistentClass); // Child
+
+ oneToMany.setAssociatedClass(persistentClass); // Child
}
-
+
}
static class JDBCCollectionSecondPass extends CollectionSecondPass {
@@ -1109,9 +1110,9 @@
* @see org.hibernate.cfg.HbmBinder.SecondPass#secondPass(java.util.Map, java.util.Map)
*/
public void secondPass(Map persistentClasses, Map inheritedMetas) throws MappingException {
- JDBCBinder.bindCollectionSecondPass(collection, persistentClasses, mappings, inheritedMetas);
- }
-
+ JDBCBinder.bindCollectionSecondPass(collection, persistentClasses, mappings, inheritedMetas);
+ }
+
public void doSecondPass(Map persistentClasses) throws MappingException {
Value element = collection.getElement();
DependantValue dep = null;
@@ -1125,8 +1126,8 @@
if(dep!=null) {
dep.setForeignKeyName(oldFkName);
}
-
+
}
}
-
+
}
Added: branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest.java
===================================================================
--- branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest.java (rev 0)
+++ branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest.java 2009-03-02 14:36:20 UTC (rev 16054)
@@ -0,0 +1,90 @@
+/*******************************************************************************
+ * Copyright (c) 2007-2008 Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is made available under the terms of the
+ * Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributor:
+ * Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.hibernate.tool.hbm2x.hbm2hbmxml;
+
+import java.io.File;
+import java.util.Iterator;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.hibernate.cfg.Configuration;
+import org.hibernate.mapping.Backref;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.tool.NonReflectiveTestCase;
+import org.hibernate.tool.hbm2x.Exporter;
+import org.hibernate.tool.hbm2x.HibernateMappingExporter;
+
+/**
+ * @author Dmitry Geraskov
+ *
+ */
+public class BackrefTest extends NonReflectiveTestCase {
+
+ private String mappingFile = "Car.hbm.xml";
+
+ private Exporter hbmexporter;
+
+ /**
+ * @param name
+ */
+ public BackrefTest(String name) {
+ super(name, "cfg2hbmoutput");
+ }
+
+
+ protected String[] getMappings() {
+ return new String[] {
+ mappingFile
+ };
+ }
+
+ protected void setUp() throws Exception {
+ super.setUp();
+
+ hbmexporter = new HibernateMappingExporter(getCfg(), getOutputDir() );
+ hbmexporter.start();
+ }
+
+ public void testAllFilesExistence() {
+ assertFileAndExists(new File(getOutputDir().getAbsolutePath(), getBaseForMappings() + "Car.hbm.xml") );
+ assertFileAndExists(new File(getOutputDir().getAbsolutePath(), getBaseForMappings() + "CarPart.hbm.xml") );
+ }
+
+ public void testBackrefPresent() {
+ Configuration config = getCfg();
+ PersistentClass pc = config.getClassMapping("org.hibernate.tool.hbm2x.hbm2hbmxml.CarPart");
+ Iterator iterator = pc.getPropertyIterator();
+ boolean hasBackrefs = false;
+ while (iterator.hasNext() && !hasBackrefs) {
+ hasBackrefs = (iterator.next() instanceof Backref);
+ }
+ assertTrue("Class mapping should create Backref for this testcase", hasBackrefs);
+ }
+
+ public void testReadable() {
+ Configuration cfg = new Configuration();
+
+ cfg.addFile(new File(getOutputDir(), getBaseForMappings() + "Car.hbm.xml"));
+ cfg.addFile(new File(getOutputDir(), getBaseForMappings() + "CarPart.hbm.xml"));
+
+ cfg.buildMappings();
+ }
+
+ protected String getBaseForMappings() {
+ return "org/hibernate/tool/hbm2x/hbm2hbmxml/";
+ }
+
+ public static Test suite() {
+ return new TestSuite(BackrefTest.class);
+ }
+
+}
Added: branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Car.hbm.xml
===================================================================
--- branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Car.hbm.xml (rev 0)
+++ branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Car.hbm.xml 2009-03-02 14:36:20 UTC (rev 16054)
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+ "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+
+<hibernate-mapping package="org.hibernate.tool.hbm2x.hbm2hbmxml">
+
+ <class name="Car" lazy="false" node="car">
+ <id name="id" node="@id" type="long">
+ <generator class="increment"/>
+ </id>
+ <property name="model" type="string" node="model"/>
+ <set name="carParts" node="." cascade="all">
+ <key column="car" not-null="true"/>
+ <one-to-many class="CarPart" node="carPart" embed-xml="false"/>
+ </set>
+ </class>
+
+ <class name="CarPart" node="carPart">
+ <id name="id" node="@id" type="long">
+ <generator class="increment"/>
+ </id>
+ <property name="partName" type="string" node="partName"/>
+ </class>
+
+</hibernate-mapping>
\ No newline at end of file
Added: branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Car.java
===================================================================
--- branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Car.java (rev 0)
+++ branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Car.java 2009-03-02 14:36:20 UTC (rev 16054)
@@ -0,0 +1,45 @@
+package org.hibernate.tool.hbm2x.hbm2hbmxml;
+
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * @author Paco Hern�ndez
+ */
+public class Car implements java.io.Serializable {
+
+ private long id;
+ private String model;
+ private Set carParts = new HashSet();
+
+ /**
+ * @return Returns the id.
+ */
+ public long getId() {
+ return id;
+ }
+ /**
+ * @param id The id to set.
+ */
+ public void setId(long id) {
+ this.id = id;
+ }
+ /**
+ * @return Returns the model.
+ */
+ public String getModel() {
+ return model;
+ }
+ /**
+ * @param model The model to set.
+ */
+ public void setModel(String model) {
+ this.model = model;
+ }
+ public Set getCarParts() {
+ return carParts;
+ }
+ public void setCarParts(Set carParts) {
+ this.carParts = carParts;
+ }
+}
Added: branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/CarPart.java
===================================================================
--- branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/CarPart.java (rev 0)
+++ branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/CarPart.java 2009-03-02 14:36:20 UTC (rev 16054)
@@ -0,0 +1,35 @@
+package org.hibernate.tool.hbm2x.hbm2hbmxml;
+
+/**
+ * @author Paco Hern�ndez
+ */
+public class CarPart implements java.io.Serializable {
+
+ private long id;
+ private String partName;
+
+ /**
+ * @return Returns the id.
+ */
+ public long getId() {
+ return id;
+ }
+ /**
+ * @param id The id to set.
+ */
+ public void setId(long id) {
+ this.id = id;
+ }
+ /**
+ * @return Returns the typeName.
+ */
+ public String getPartName() {
+ return partName;
+ }
+ /**
+ * @param typeName The typeName to set.
+ */
+ public void setPartName(String typeName) {
+ this.partName = typeName;
+ }
+}
Modified: branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Cfg2HbmAllTests.java
===================================================================
--- branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Cfg2HbmAllTests.java 2009-03-02 10:31:56 UTC (rev 16053)
+++ branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Cfg2HbmAllTests.java 2009-03-02 14:36:20 UTC (rev 16054)
@@ -18,6 +18,7 @@
suite.addTest(OneToOneTest.suite());
suite.addTest(InheritanceTest.suite());
suite.addTest(SetElementTest.suite());
+ suite.addTest(BackrefTest.suite());
//$JUnit-END$
return suite;
}
15 years, 10 months
Hibernate SVN: r16053 - validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-03-02 05:31:56 -0500 (Mon, 02 Mar 2009)
New Revision: 16053
Modified:
validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation/ValidationMessages.properties
validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation/ValidationMessages_de.properties
Log:
HV-103 - updated resource bundles
Modified: validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation/ValidationMessages.properties
===================================================================
--- validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation/ValidationMessages.properties 2009-03-02 09:47:52 UTC (rev 16052)
+++ validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation/ValidationMessages.properties 2009-03-02 10:31:56 UTC (rev 16053)
@@ -4,8 +4,8 @@
validator.length=length must be between {min} and {max}
validator.notEmpty=may not be empty
validator.pattern=must match "{regexp}"
-validator.min=must be greater than {value}
-validator.max=must be less than {value}
+validator.min=must be greater than or equal to {value}
+validator.max=must be less than or equal to {value}
validator.null=must be null
validator.past=must be in the past
validator.future=must be in the future
Modified: validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation/ValidationMessages_de.properties
===================================================================
--- validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation/ValidationMessages_de.properties 2009-03-02 09:47:52 UTC (rev 16052)
+++ validator/trunk/hibernate-validator/src/main/resources/org/hibernate/validation/ValidationMessages_de.properties 2009-03-02 10:31:56 UTC (rev 16053)
@@ -4,8 +4,8 @@
validator.length=muss zwischen {min} und {max} liegen
validator.notEmpty=kann nicht leer sein
validator.pattern=muss auf Ausdruck "{regexp}" passen
-validator.min=muss gr\u00F6\u00DFer sein als {value}
-validator.max=muss kleiner sein als {value}
+validator.min=muss gr\u00F6ssergleich {value} sein
+validator.max=muss kleinergleich {value} sein
validator.null=muss null sein
validator.past=muss in der Vergangenheit liegen
validator.future=muss in der Zukunft liegen
15 years, 10 months
Hibernate SVN: r16052 - validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-03-02 04:47:52 -0500 (Mon, 02 Mar 2009)
New Revision: 16052
Modified:
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/MaxValidatorForNumberTest.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/MinValidatorForNumberTest.java
Log:
added additional test attached to HV-122
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/MaxValidatorForNumberTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/MaxValidatorForNumberTest.java 2009-02-28 04:55:29 UTC (rev 16051)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/MaxValidatorForNumberTest.java 2009-03-02 09:47:52 UTC (rev 16052)
@@ -39,7 +39,7 @@
@BeforeClass
public static void init() {
- AnnotationDescriptor<Max> descriptor = new AnnotationDescriptor( Max.class );
+ AnnotationDescriptor<Max> descriptor = new AnnotationDescriptor<Max>( Max.class );
descriptor.setValue( "value", 15l );
descriptor.setValue( "message", "{validator.max}" );
Max m = AnnotationFactory.create( descriptor );
@@ -50,7 +50,10 @@
@Test
public void testIsValid() {
+ byte b = 1;
+ Byte bWrapper = 127;
assertTrue( constraint.isValid( null, null ) );
+ assertTrue( constraint.isValid( b, null ) );
assertTrue( constraint.isValid( 15l, null ) );
assertTrue( constraint.isValid( 15, null ) );
assertTrue( constraint.isValid( 15.0, null ) );
@@ -60,6 +63,7 @@
assertTrue( constraint.isValid( 14.99, null ) );
assertTrue( constraint.isValid( -14.99, null ) );
assertFalse( constraint.isValid( 20, null ) );
+ assertFalse( constraint.isValid( bWrapper, null ) );
assertFalse( constraint.isValid( BigDecimal.valueOf( 156000000000.0 ), null ) );
assertFalse( constraint.isValid( BigInteger.valueOf( 10000000l ), null ) );
}
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/MinValidatorForNumberTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/MinValidatorForNumberTest.java 2009-02-28 04:55:29 UTC (rev 16051)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/constraints/MinValidatorForNumberTest.java 2009-03-02 09:47:52 UTC (rev 16052)
@@ -50,13 +50,17 @@
@Test
public void testIsValid() {
+ byte b = 1;
+ Byte bWrapper = 127;
assertTrue( constraint.isValid( null, null ) );
+ assertTrue( constraint.isValid( bWrapper, null ) );
assertTrue( constraint.isValid( 20, null ) );
assertTrue( constraint.isValid( 15l, null ) );
assertTrue( constraint.isValid( 15, null ) );
assertTrue( constraint.isValid( 15.0, null ) );
assertTrue( constraint.isValid( BigDecimal.valueOf( 156000000000.0 ), null ) );
assertTrue( constraint.isValid( BigInteger.valueOf( 10000000l ), null ) );
+ assertFalse( constraint.isValid( b, null ) );
assertFalse( constraint.isValid( BigDecimal.valueOf( -156000000000.0 ), null ) );
assertFalse( constraint.isValid( BigInteger.valueOf( -10000000l ), null ) );
assertFalse( constraint.isValid( 10, null ) );
15 years, 10 months