Hibernate SVN: r17199 - jpa-api/trunk/src/main/java/javax/persistence/spi.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2009-07-23 17:25:08 -0400 (Thu, 23 Jul 2009)
New Revision: 17199
Modified:
jpa-api/trunk/src/main/java/javax/persistence/spi/PersistenceProviderResolverHolder.java
Log:
EJB-454 implements the default PPR strategy
Modified: jpa-api/trunk/src/main/java/javax/persistence/spi/PersistenceProviderResolverHolder.java
===================================================================
--- jpa-api/trunk/src/main/java/javax/persistence/spi/PersistenceProviderResolverHolder.java 2009-07-23 18:54:27 UTC (rev 17198)
+++ jpa-api/trunk/src/main/java/javax/persistence/spi/PersistenceProviderResolverHolder.java 2009-07-23 21:25:08 UTC (rev 17199)
@@ -2,23 +2,166 @@
// EJB3 Specification Copyright 2004-2009 Sun Microsystems, Inc.
package javax.persistence.spi;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.lang.ref.WeakReference;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.WeakHashMap;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import javax.persistence.PersistenceException;
+
/**
* Holds the global PersistenceProviderResolver instance.
* If no PersistenceProviderResolver is set by the environment,
- * the default PersistenceProviderResolver is used. *
+ * the default PersistenceProviderResolver is used.
+ *
* Implementations must be thread-safe.
*/
public class PersistenceProviderResolverHolder {
+
+ private static volatile PersistenceProviderResolver resolver;
+
+ private static final PersistenceProviderResolver defaultResolver = new PersistenceProviderResolverPerClassLoader();
+
/**
* Returns the current persistence provider resolver
*/
public static PersistenceProviderResolver getPersistenceProviderResolver() {
- return null;
+ return resolver == null ? defaultResolver : resolver;
}
/**
* Defines the persistence provider resolver used
*/
public static void setPersistenceProviderResolver(PersistenceProviderResolver resolver) {
+ PersistenceProviderResolverHolder.resolver = resolver;
}
+
+ /**
+ * Cache PersistenceProviderResolver per classloader and use the current classloader as a
+ * key.
+ * Use CachingPersistenceProviderResolver for each PersistenceProviderResolver instance.
+ *
+ * @author Emmanuel Bernard
+ */
+ private static class PersistenceProviderResolverPerClassLoader implements PersistenceProviderResolver {
+
+ //FIXME use a ConcurrentHashMap with weak entry
+ private final WeakHashMap<ClassLoader, PersistenceProviderResolver> resolvers =
+ new WeakHashMap<ClassLoader, PersistenceProviderResolver>();
+ private volatile short barrier = 1;
+
+
+ public List<PersistenceProvider> getPersistenceProviders() {
+ ClassLoader cl = Thread.currentThread().getContextClassLoader();
+ if ( cl == null ) {
+ cl = PersistenceProviderResolverPerClassLoader.class.getClassLoader();
+ }
+ if (barrier == 1) {} //read barrier syncs state with other threads
+ PersistenceProviderResolver currentResolver = resolvers.get( cl );
+ if (currentResolver == null) {
+ currentResolver = new CachingPersistenceProviderResolver(cl);
+ resolvers.put( cl, currentResolver );
+ barrier = 1;
+ }
+ return currentResolver.getPersistenceProviders();
+ }
+
+ /**
+ * Resolve the list of Persistence providers for a given classloader and cache the results.
+ *
+ * Avoids to keep any reference from this class to the classloader being
+ * passed to the constructor.
+ *
+ * @author Emmanuel Bernard
+ */
+ private static class CachingPersistenceProviderResolver implements PersistenceProviderResolver {
+ //this assumes that the class loader keeps the list of classes loaded
+ private final List<WeakReference<Class<? extends PersistenceProvider>>> resolverClasses;
+
+ public CachingPersistenceProviderResolver(ClassLoader cl) {
+ //creates a hard reference to the cl :(
+ resolverClasses = new ArrayList<WeakReference<Class<? extends PersistenceProvider>>>();
+ try {
+ Enumeration<URL> resources = cl.getResources( "META-INF/services/" + PersistenceProvider.class.getName() );
+ Set<String> names = new HashSet<String>();
+ while ( resources.hasMoreElements() ) {
+ URL url = resources.nextElement();
+ InputStream is = url.openStream();
+ try {
+ names.addAll( providerNamesFromReader( new BufferedReader( new InputStreamReader( is ) ) ) );
+ }
+ finally {
+ is.close();
+ }
+ }
+ for ( String s : names ) {
+ @SuppressWarnings( "unchecked" )
+ Class<? extends PersistenceProvider> providerClass = (Class<? extends PersistenceProvider>) cl.loadClass( s );
+ WeakReference<Class<? extends PersistenceProvider>> reference
+ = new WeakReference<Class<? extends PersistenceProvider>>(providerClass);
+ //keep Hibernate atop
+ if ( s.endsWith( "HibernatePersistence" ) && resolverClasses.size() > 0 ) {
+ WeakReference<Class<? extends PersistenceProvider>> movedReference = resolverClasses.get( 0 );
+ resolverClasses.add( 0, reference );
+ resolverClasses.add( movedReference );
+ }
+ else {
+ resolverClasses.add( reference );
+ }
+ }
+ }
+ catch ( IOException e ) {
+ throw new PersistenceException( e );
+ }
+ catch ( ClassNotFoundException e ) {
+ throw new PersistenceException( e );
+ }
+ }
+
+ //TODO find a way to cache property instances
+ //problem #1: avoid hard ref with classloader (List<WR<PP>>?
+ //problem #2: avoid half GC lists
+ public List<PersistenceProvider> getPersistenceProviders() {
+ List<PersistenceProvider> providers = new ArrayList<PersistenceProvider>( resolverClasses.size() );
+ try {
+ for ( WeakReference<Class<? extends PersistenceProvider>> providerClass : resolverClasses ) {
+ providers.add( providerClass.get().newInstance() );
+ }
+ }
+ catch ( InstantiationException e ) {
+ throw new PersistenceException( e );
+ }
+ catch ( IllegalAccessException e ) {
+ throw new PersistenceException( e );
+ }
+ return providers;
+ }
+
+
+ private static final Pattern nonCommentPattern = Pattern.compile( "^([^#]+)" );
+
+ private static Set<String> providerNamesFromReader(BufferedReader reader) throws IOException {
+ Set<String> names = new HashSet<String>();
+ String line;
+ while ( ( line = reader.readLine() ) != null ) {
+ line = line.trim();
+ Matcher m = nonCommentPattern.matcher( line );
+ if ( m.find() ) {
+ names.add( m.group().trim() );
+ }
+ }
+ return names;
+ }
+ }
+ }
+
}
15 years, 4 months
Hibernate SVN: r17198 - core/trunk/entitymanager/src/main/docbook/en/modules.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2009-07-23 14:54:27 -0400 (Thu, 23 Jul 2009)
New Revision: 17198
Modified:
core/trunk/entitymanager/src/main/docbook/en/modules/batch.xml
Log:
minor documentation typo
Modified: core/trunk/entitymanager/src/main/docbook/en/modules/batch.xml
===================================================================
--- core/trunk/entitymanager/src/main/docbook/en/modules/batch.xml 2009-07-23 14:19:33 UTC (rev 17197)
+++ core/trunk/entitymanager/src/main/docbook/en/modules/batch.xml 2009-07-23 18:54:27 UTC (rev 17198)
@@ -78,7 +78,7 @@
entityManager.getTransaction().begin();
String ejbqlUpdate = "update Customer set name = :newName where name = :oldName"
-int updatedEntities = entityManager.createQuery( hqlUpdate )
+int updatedEntities = entityManager.createQuery( ejbqlUpdate )
.setParameter( "newName", newName )
.setParameter( "oldName", oldName )
.executeUpdate();
15 years, 4 months
Hibernate SVN: r17197 - beanvalidation/trunk/validation-api/src/main/java/javax/validation.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-07-23 10:19:33 -0400 (Thu, 23 Jul 2009)
New Revision: 17197
Modified:
beanvalidation/trunk/validation-api/src/main/java/javax/validation/Validation.java
Log:
reverted the formatting
Modified: beanvalidation/trunk/validation-api/src/main/java/javax/validation/Validation.java
===================================================================
--- beanvalidation/trunk/validation-api/src/main/java/javax/validation/Validation.java 2009-07-23 13:23:39 UTC (rev 17196)
+++ beanvalidation/trunk/validation-api/src/main/java/javax/validation/Validation.java 2009-07-23 14:19:33 UTC (rev 17197)
@@ -17,16 +17,16 @@
*/
package javax.validation;
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.net.URL;
+import java.io.InputStream;
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.io.IOException;
import javax.validation.bootstrap.GenericBootstrap;
import javax.validation.bootstrap.ProviderSpecificBootstrap;
import javax.validation.spi.BootstrapState;
@@ -65,7 +65,7 @@
* <li>
* The third approach allows you to specify explicitly and in
* a type safe fashion the expected provider.
- * <p/>
+ *
* Optionally you can choose a custom <code>ValidationProviderResolver</code>.
* <pre>{@code
* ACMEConfiguration configuration = Validation
@@ -103,7 +103,6 @@
* <code>Validation.byDefaultProvider().configure().buildValidatorFactory()</code>
*
* @return <code>ValidatorFactory</code> instance.
- *
* @throws ValidationException if the ValidatorFactory cannot be built
*/
public static ValidatorFactory buildDefaultValidatorFactory() {
@@ -125,7 +124,7 @@
* the first available provider will be returned.
*
* @return instance building a generic <code>Configuration</code>
- * compliant with the bootstrap state provided.
+ * compliant with the bootstrap state provided.
*/
public static GenericBootstrap byDefaultProvider() {
return new GenericBootstrapImpl();
@@ -151,10 +150,10 @@
* @param providerType the <code>ValidationProvider</code> implementation type
*
* @return instance building a provider specific <code>Configuration</code>
- * sub interface implementation.
+ * sub interface implementation.
*/
public static <T extends Configuration<T>, U extends ValidationProvider<T>>
- ProviderSpecificBootstrap<T> byProvider(Class<U> providerType) {
+ ProviderSpecificBootstrap<T> byProvider(Class<U> providerType) {
return new ProviderSpecificBootstrapImpl<T, U>( providerType );
}
@@ -230,7 +229,7 @@
}
public ValidationProviderResolver getDefaultValidationProviderResolver() {
- if ( defaultResolver == null ) {
+ if (defaultResolver == null) {
defaultResolver = new DefaultValidationProviderResolver();
}
return defaultResolver;
15 years, 4 months
Hibernate SVN: r17196 - beanvalidation/trunk/validation-tck/src/main/resources.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-07-23 09:23:39 -0400 (Thu, 23 Jul 2009)
New Revision: 17196
Modified:
beanvalidation/trunk/validation-tck/src/main/resources/tck-audit.xml
Log:
audit file updates
Modified: beanvalidation/trunk/validation-tck/src/main/resources/tck-audit.xml
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/resources/tck-audit.xml 2009-07-23 13:11:41 UTC (rev 17195)
+++ beanvalidation/trunk/validation-tck/src/main/resources/tck-audit.xml 2009-07-23 13:23:39 UTC (rev 17196)
@@ -756,7 +756,7 @@
raised</text>
</assertion>
</section>
- <section id="4.4.4.1" title="">
+ <section id="4.4.4.1" title="ValidationProviderResolver">
<assertion id="a">
<text>ValidationProviderResolver returns the list of Bean Validation providers available
at runtime and more specifically a ValidationProvider instance for each provider
@@ -778,30 +778,26 @@
file</text>
</assertion>
<assertion id="b">
- <text>The key uniquely identifying a Bean Validation provider is a provider specific sub
- interface of Configuration</text>
+ <text>The key uniquely identifying a Bean Validation provider is the ValidationProvider implementation
+ specific to this provider</text>
</assertion>
<assertion id="c">
- <text>Retrieve available providers using
- ValidationProviderResolver.getValidationProviders(). • The first
- ValidationProvider matching the requested provider is returned</text>
+ <text>The provider discovery mechanism retrieve all available providers using
+ ValidationProviderResolver.getValidationProviders() and returns the first
+ ValidationProvider matching the requested provider</text>
</assertion>
<assertion id="d">
- <text>Providers are evaluated in the order they are returned by
- ValidationProviderResolver</text>
- </assertion>
- <assertion id="e">
<text>When the default Bean Validation provider is requested, the first
ValidationProvider returned by the Valida- tionProviderResolver strategy is
returned</text>
</assertion>
- <assertion id="f">
+ <assertion id="e">
<text>Every Bean Validation provider must provide a ValidationProvider implementation
containing a public no-arg constructor and add the corresponding
META-INF/services/javax.validation.spi.ValidationProvider file descriptor in one of
its jars.</text>
</assertion>
- <assertion id="g">
+ <assertion id="f">
<text>If a problem occurs while building the ValidationFactory, a ValidationException is
raised</text>
</assertion>
@@ -817,8 +813,8 @@
providers</text>
</assertion>
<assertion id="c">
- <text>When building the Configuration object, if the ValidationProviderResolver either
- fail or if the expected provider is not found, a ValidationException is
+ <text>When building the Configuration object, if the ValidationProviderResolver
+ fais or if the expected provider is not found, a ValidationException is
raised</text>
</assertion>
</section>
15 years, 4 months
Hibernate SVN: r17195 - beanvalidation/trunk/validation-api/src/main/java/javax/validation.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-07-23 09:11:41 -0400 (Thu, 23 Jul 2009)
New Revision: 17195
Modified:
beanvalidation/trunk/validation-api/src/main/java/javax/validation/Validation.java
Log:
Formatting
Modified: beanvalidation/trunk/validation-api/src/main/java/javax/validation/Validation.java
===================================================================
--- beanvalidation/trunk/validation-api/src/main/java/javax/validation/Validation.java 2009-07-23 12:55:51 UTC (rev 17194)
+++ beanvalidation/trunk/validation-api/src/main/java/javax/validation/Validation.java 2009-07-23 13:11:41 UTC (rev 17195)
@@ -17,16 +17,16 @@
*/
package javax.validation;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.net.URL;
-import java.io.InputStream;
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.io.IOException;
import javax.validation.bootstrap.GenericBootstrap;
import javax.validation.bootstrap.ProviderSpecificBootstrap;
import javax.validation.spi.BootstrapState;
@@ -65,7 +65,7 @@
* <li>
* The third approach allows you to specify explicitly and in
* a type safe fashion the expected provider.
- *
+ * <p/>
* Optionally you can choose a custom <code>ValidationProviderResolver</code>.
* <pre>{@code
* ACMEConfiguration configuration = Validation
@@ -103,6 +103,7 @@
* <code>Validation.byDefaultProvider().configure().buildValidatorFactory()</code>
*
* @return <code>ValidatorFactory</code> instance.
+ *
* @throws ValidationException if the ValidatorFactory cannot be built
*/
public static ValidatorFactory buildDefaultValidatorFactory() {
@@ -124,7 +125,7 @@
* the first available provider will be returned.
*
* @return instance building a generic <code>Configuration</code>
- * compliant with the bootstrap state provided.
+ * compliant with the bootstrap state provided.
*/
public static GenericBootstrap byDefaultProvider() {
return new GenericBootstrapImpl();
@@ -150,10 +151,10 @@
* @param providerType the <code>ValidationProvider</code> implementation type
*
* @return instance building a provider specific <code>Configuration</code>
- * sub interface implementation.
+ * sub interface implementation.
*/
public static <T extends Configuration<T>, U extends ValidationProvider<T>>
- ProviderSpecificBootstrap<T> byProvider(Class<U> providerType) {
+ ProviderSpecificBootstrap<T> byProvider(Class<U> providerType) {
return new ProviderSpecificBootstrapImpl<T, U>( providerType );
}
@@ -229,7 +230,7 @@
}
public ValidationProviderResolver getDefaultValidationProviderResolver() {
- if (defaultResolver == null) {
+ if ( defaultResolver == null ) {
defaultResolver = new DefaultValidationProviderResolver();
}
return defaultResolver;
15 years, 4 months
Hibernate SVN: r17194 - in validator/trunk/hibernate-validator/src: main/java/org/hibernate/validation/metadata and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-07-23 08:55:51 -0400 (Thu, 23 Jul 2009)
New Revision: 17194
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintValidatorContextImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/GlobalExecutionContext.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/PathImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/MetaConstraint.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/PathImplTest.java
Log:
HV-190 Changes the PathImpl to not contain a ROOT_NODE per default. This had several other effects.
Modified: 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-07-23 12:35:38 UTC (rev 17193)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintValidatorContextImpl.java 2009-07-23 12:55:51 UTC (rev 17194)
@@ -97,8 +97,7 @@
}
public NodeBuilderDefinedContext addSubNode(String name) {
- PathImpl path = PathImpl.createNewRootPath();
- path.addNode( new NodeImpl( name ) );
+ PathImpl path = PathImpl.createNewPath( name );
return new NodeBuilderImpl( messageTemplate, path );
}
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/GlobalExecutionContext.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/GlobalExecutionContext.java 2009-07-23 12:35:38 UTC (rev 17193)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/GlobalExecutionContext.java 2009-07-23 12:55:51 UTC (rev 17194)
@@ -35,7 +35,7 @@
/**
* Context object keeping track of all important data for a top level {@link javax.validation.Validator#validate(Object, Class[])} },
* {@link javax.validation.Validator#validateValue(Class, String, Object, Class[])} } or {@link javax.validation.Validator#validateProperty(Object, String, Class[])} call.
- *
+ * <p/>
* we use this object to collect all failing constraints, but also to cache the caching traversable resolver for a full stack call.
*
* @author Hardy Ferentschik
@@ -221,7 +221,7 @@
}
for ( PathImpl p : pathSet ) {
- if ( p.isSubPathOf( path ) || path.isSubPathOf( p ) ) {
+ if ( p.isRootPath() || path.isRootPath() || p.isSubPathOf( path ) || path.isSubPathOf( p ) ) {
return true;
}
}
@@ -235,12 +235,19 @@
}
private void markProcessedForCurrentPath(Object value, PathImpl path) {
+ // hmm - not sure if the current definiton of Path and Node are consistent. Shouldn't a simple property
+ // of a entity have a parent node?
+ PathImpl parentPath = path.getPathWithoutLeafNode();
+ if ( parentPath == null ) {
+ parentPath = PathImpl.createNewPath( null );
+ }
+
if ( processedPaths.containsKey( value ) ) {
- processedPaths.get( value ).add( path.getPathWithoutLeafNode() );
+ processedPaths.get( value ).add( parentPath );
}
else {
Set<PathImpl> set = new HashSet<PathImpl>();
- set.add( path.getPathWithoutLeafNode() );
+ set.add( parentPath );
processedPaths.put( value, set );
}
}
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/PathImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/PathImpl.java 2009-07-23 12:35:38 UTC (rev 17193)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/PathImpl.java 2009-07-23 12:55:51 UTC (rev 17194)
@@ -38,8 +38,6 @@
private static final String PROPERTY_PATH_SEPERATOR = ".";
- private static final Node ROOT_NODE = new NodeImpl( ( String ) null );
-
private final List<Node> nodeList;
/**
@@ -57,18 +55,21 @@
}
if ( propertyPath.length() == 0 ) {
- return createNewRootPath();
+ return createNewPath( null );
}
return parseProperty( propertyPath );
}
- public static PathImpl createNewRootPath() {
- return new PathImpl();
+ public static PathImpl createNewPath(String name) {
+ PathImpl path = new PathImpl();
+ NodeImpl node = new NodeImpl( name );
+ path.addNode( node );
+ return path;
}
public static PathImpl createShallowCopy(PathImpl path) {
- return new PathImpl( path );
+ return path == null ? null : new PathImpl( path );
}
private PathImpl(PathImpl path) {
@@ -80,7 +81,6 @@
private PathImpl() {
nodeList = new ArrayList<Node>();
- nodeList.add( ROOT_NODE );
}
private PathImpl(List<Node> nodeList) {
@@ -90,12 +90,18 @@
}
}
+ public boolean isRootPath() {
+ return nodeList.size() == 1 && nodeList.get( 0 ).getName() == null;
+ }
+
public PathImpl getPathWithoutLeafNode() {
List<Node> nodes = new ArrayList<Node>( nodeList );
+ PathImpl path = null;
if ( nodes.size() > 1 ) {
nodes.remove( nodes.size() - 1 );
+ path = new PathImpl( nodes );
}
- return new PathImpl( nodes );
+ return path;
}
public void addNode(Node node) {
@@ -145,9 +151,6 @@
Iterator<Path.Node> iter = iterator();
while ( iter.hasNext() ) {
Node node = iter.next();
- if ( ROOT_NODE.equals( node ) ) {
- continue;
- }
builder.append( node.toString() );
if ( iter.hasNext() ) {
builder.append( PROPERTY_PATH_SEPERATOR );
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-07-23 12:35:38 UTC (rev 17193)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java 2009-07-23 12:55:51 UTC (rev 17194)
@@ -116,9 +116,7 @@
object, messageInterpolator, constraintValidatorFactory, getCachingTraversableResolver()
);
- List<ConstraintViolation<T>> list = validateInContext(
- object, context, groupChain, PathImpl.createNewRootPath()
- );
+ List<ConstraintViolation<T>> list = validateInContext( object, context, groupChain, null );
return new HashSet<ConstraintViolation<T>>( list );
}
@@ -317,10 +315,16 @@
private <T, U, V> boolean validateConstraint(GlobalExecutionContext<T> globalExecutionContext, LocalExecutionContext<U, V> localExecutionContext, MetaConstraint<U, ?> metaConstraint, PathImpl path) {
boolean validationSuccessful = true;
- PathImpl newPath = PathImpl.createShallowCopy( path );
- if ( !"".equals( metaConstraint.getPropertyName() ) ) {
+ PathImpl newPath;
+
+ if ( path == null ) {
+ newPath = PathImpl.createNewPath( metaConstraint.getPropertyName() );
+ }
+ else {
+ newPath = PathImpl.createShallowCopy( path );
newPath.addNode( new NodeImpl( metaConstraint.getPropertyName() ) );
}
+
localExecutionContext.setPropertyPath( newPath );
if ( isValidationRequired( globalExecutionContext, localExecutionContext, metaConstraint ) ) {
Object valueToValidate = metaConstraint.getValue( localExecutionContext.getCurrentBean() );
@@ -349,8 +353,14 @@
.getCascadedMembers();
for ( Member member : cascadedMembers ) {
Type type = ReflectionHelper.typeOf( member );
- PathImpl newPath = PathImpl.createShallowCopy( path );
- newPath.addNode( new NodeImpl( ReflectionHelper.getPropertyName( member ) ) );
+ PathImpl newPath;
+ if ( path == null ) {
+ newPath = PathImpl.createNewPath( ReflectionHelper.getPropertyName( member ) );
+ }
+ else {
+ newPath = PathImpl.createShallowCopy( path );
+ newPath.addNode( new NodeImpl( ReflectionHelper.getPropertyName( member ) ) );
+ }
localExecutionContext.setPropertyPath( newPath );
if ( isCascadeRequired( globalExecutionContext, localExecutionContext, member ) ) {
Object value = ReflectionHelper.getValue( member, localExecutionContext.getCurrentBean() );
@@ -665,9 +675,6 @@
*/
private <T> Object collectMetaConstraintsForPath(Class<T> clazz, Object value, Iterator<Path.Node> propertyIter, Set<MetaConstraint<T, ?>> metaConstraints) {
Path.Node elem = propertyIter.next();
- if ( elem.getName() == null ) { // skip root node
- elem = propertyIter.next();
- }
final BeanMetaData<T> metaData = getBeanMetaData( clazz );
if ( !propertyIter.hasNext() ) {
@@ -682,7 +689,7 @@
List<MetaConstraint<T, ? extends Annotation>> metaConstraintList = metaData.geMetaConstraintsAsList();
for ( MetaConstraint<T, ?> metaConstraint : metaConstraintList ) {
- if ( metaConstraint.getPropertyName().equals( elem.getName() ) ) {
+ if ( elem.getName() != null && elem.getName().equals( metaConstraint.getPropertyName() ) ) {
metaConstraints.add( metaConstraint );
}
}
@@ -744,12 +751,17 @@
boolean isReachable;
+ Path pathToObject = localContext.getPropertyPath().getPathWithoutLeafNode();
+ if ( pathToObject == null ) {
+ pathToObject = PathImpl.createNewPath( null );
+ }
+
try {
isReachable = globalContext.getTraversableResolver().isReachable(
localContext.getCurrentBean(),
localContext.getPropertyPath().getLeafNode(),
globalContext.getRootBeanClass(),
- localContext.getPropertyPath().getPathWithoutLeafNode(),
+ pathToObject,
metaConstraint.getElementType()
);
}
@@ -765,12 +777,17 @@
boolean isReachable;
boolean isCascadable;
+ Path pathToObject = localContext.getPropertyPath().getPathWithoutLeafNode();
+ if ( pathToObject == null ) {
+ pathToObject = PathImpl.createNewPath( null );
+ }
+
try {
isReachable = globalContext.getTraversableResolver().isReachable(
localContext.getCurrentBean(),
localContext.getPropertyPath().getLeafNode(),
globalContext.getRootBeanClass(),
- localContext.getPropertyPath().getPathWithoutLeafNode(),
+ pathToObject,
type
);
}
@@ -783,7 +800,7 @@
localContext.getCurrentBean(),
localContext.getPropertyPath().getLeafNode(),
globalContext.getRootBeanClass(),
- localContext.getPropertyPath().getPathWithoutLeafNode(),
+ pathToObject,
type
);
}
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/MetaConstraint.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/MetaConstraint.java 2009-07-23 12:35:38 UTC (rev 17193)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/metadata/MetaConstraint.java 2009-07-23 12:55:51 UTC (rev 17194)
@@ -48,7 +48,8 @@
private final Member member;
/**
- * The JavaBeans name for this constraint.
+ * The JavaBeans name of the field/property the constraint was placed on. {@code null} if this is a
+ * class level constraint.
*/
private final String propertyName;
@@ -71,7 +72,7 @@
public MetaConstraint(Class<T> beanClass, ConstraintDescriptor<A> constraintDescriptor) {
this.elementType = ElementType.TYPE;
this.member = null;
- this.propertyName = "";
+ this.propertyName = null;
this.beanClass = beanClass;
constraintTree = new ConstraintTree<A>( constraintDescriptor );
}
@@ -109,6 +110,10 @@
return beanClass;
}
+ /**
+ * @return The JavaBeans name of the field/property the constraint was placed on. {@code null} if this is a
+ * class level constraint.
+ */
public String getPropertyName() {
return propertyName;
}
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/PathImplTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/PathImplTest.java 2009-07-23 12:35:38 UTC (rev 17193)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/PathImplTest.java 2009-07-23 12:55:51 UTC (rev 17194)
@@ -38,12 +38,6 @@
assertTrue( propIter.hasNext() );
Path.Node elem = propIter.next();
- assertEquals( null, elem.getName() );
- assertFalse( elem.isInIterable() );
- assertEquals( property, path.toString() );
-
- assertTrue( propIter.hasNext() );
- elem = propIter.next();
assertEquals( "order", elem.getName() );
assertTrue( elem.isInIterable() );
assertEquals( new Integer( 3 ), elem.getIndex() );
@@ -71,12 +65,6 @@
assertTrue( propIter.hasNext() );
Path.Node elem = propIter.next();
- assertEquals( null, elem.getName() );
- assertFalse( elem.isInIterable() );
- assertEquals( property, path.toString() );
-
- assertTrue( propIter.hasNext() );
- elem = propIter.next();
assertEquals( "order", elem.getName() );
assertTrue( elem.isInIterable() );
assertEquals( "foo", elem.getKey() );
@@ -120,10 +108,4 @@
Path path = PathImpl.createPathFromString( "" );
assertTrue( path.iterator().hasNext() );
}
-
- @Test
- public void testRootPath() {
- Path path = PathImpl.createNewRootPath();
- assertEquals( path.toString(), "", "Wrong string representation of root property." );
- }
}
\ No newline at end of file
15 years, 4 months
Hibernate SVN: r17193 - in beanvalidation/trunk/validation-tck/src/main: java/org/hibernate/jsr303/tck/tests/validation and 3 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-07-23 08:35:38 -0400 (Thu, 23 Jul 2009)
New Revision: 17193
Added:
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/PropertyPathTest.java
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/ValidateWithGroupsTest.java
Removed:
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/ValidateWithGroups.java
Modified:
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/metadata/BeanDescriptorTest.java
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/ValidateTest.java
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Address.java
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/User.java
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/util/TestUtil.java
beanvalidation/trunk/validation-tck/src/main/resources/tck-audit.xml
Log:
tests for property path
Modified: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/metadata/BeanDescriptorTest.java
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/metadata/BeanDescriptorTest.java 2009-07-22 20:40:50 UTC (rev 17192)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/metadata/BeanDescriptorTest.java 2009-07-23 12:35:38 UTC (rev 17193)
@@ -42,11 +42,14 @@
* @author Hardy Ferentschik
*/
@Artifact(artifactType = ArtifactType.JSR303)
-(a)Classes({TestUtil.class, TestUtil.PathImpl.class, TestUtil.NodeImpl.class})
+@Classes({ TestUtil.class, TestUtil.PathImpl.class, TestUtil.NodeImpl.class })
public class BeanDescriptorTest extends AbstractTest {
@Test
- @SpecAssertion(section = "5.3", id = "a")
+ @SpecAssertions({
+ @SpecAssertion(section = "5.1", id = "b"),
+ @SpecAssertion(section = "5.3", id = "a")
+ })
public void testIsBeanConstrainedDueToValidAnnotation() {
Validator validator = TestUtil.getDefaultValidator();
BeanDescriptor beanDescriptor = validator.getConstraintsForClass( Customer.class );
@@ -57,7 +60,10 @@
}
@Test
- @SpecAssertion(section = "5.3", id = "a")
+ @SpecAssertions({
+ @SpecAssertion(section = "5.1", id = "b"),
+ @SpecAssertion(section = "5.3", id = "a")
+ })
public void testIsBeanConstrainedDueToConstraintOnEntity() {
Validator validator = TestUtil.getDefaultValidator();
@@ -68,7 +74,10 @@
}
@Test
- @SpecAssertion(section = "5.3", id = "a")
+ @SpecAssertions({
+ @SpecAssertion(section = "5.1", id = "b"),
+ @SpecAssertion(section = "5.3", id = "a")
+ })
public void testIsBeanConstrainedDueToConstraintProperty() {
Validator validator = TestUtil.getDefaultValidator();
@@ -79,7 +88,10 @@
}
@Test
- @SpecAssertion(section = "5.3", id = "a")
+ @SpecAssertions({
+ @SpecAssertion(section = "5.1", id = "b"),
+ @SpecAssertion(section = "5.3", id = "a")
+ })
public void testIsBeanConstrainedDueToConstraintOnInterface() {
Validator validator = TestUtil.getDefaultValidator();
@@ -90,7 +102,10 @@
}
@Test
- @SpecAssertion(section = "5.3", id = "a")
+ @SpecAssertions({
+ @SpecAssertion(section = "5.1", id = "b"),
+ @SpecAssertion(section = "5.3", id = "a")
+ })
public void testUnconstraintClass() {
Validator validator = TestUtil.getDefaultValidator();
BeanDescriptor beanDescriptor = validator.getConstraintsForClass( UnconstraintEntity.class );
@@ -99,7 +114,10 @@
}
@Test
- @SpecAssertion(section = "5.3", id = "b")
+ @SpecAssertions({
+ @SpecAssertion(section = "5.1", id = "b"),
+ @SpecAssertion(section = "5.3", id = "b")
+ })
public void testGetConstraintForConstrainedProperty() {
Validator validator = TestUtil.getDefaultValidator();
BeanDescriptor beanDescriptor = validator.getConstraintsForClass( Order.class );
@@ -112,6 +130,7 @@
@Test
@SpecAssertions({
@SpecAssertion(section = "5.3", id = "b"),
+ @SpecAssertion(section = "5.3", id = "b"),
@SpecAssertion(section = "5.4", id = "a")
})
public void testGetConstraintForUnConstrainedProperty() {
@@ -125,23 +144,21 @@
}
@Test
- @SpecAssertion(section = "5.3", id = "b")
+ @SpecAssertions({
+ @SpecAssertion(section = "5.1", id = "b"),
+ @SpecAssertion(section = "5.3", id = "b")
+ })
public void testGetConstraintsForNonExistingProperty() {
Validator validator = TestUtil.getDefaultValidator();
BeanDescriptor beanDescriptor = validator.getConstraintsForClass( Order.class );
assertNull( beanDescriptor.getConstraintsForProperty( "foobar" ), "There should be no descriptor" );
}
-
- @Test(expectedExceptions = IllegalArgumentException.class)
- public void testGetConstraintsForNullProperty() {
- Validator validator = TestUtil.getDefaultValidator();
- BeanDescriptor beanDescriptor = validator.getConstraintsForClass( Order.class );
- beanDescriptor.getConstraintsForProperty( null );
- }
-
@Test
- @SpecAssertion(section = "5.3", id = "b")
+ @SpecAssertions({
+ @SpecAssertion(section = "5.1", id = "b"),
+ @SpecAssertion(section = "5.3", id = "b")
+ })
public void testGetConstrainedProperties() {
Validator validator = TestUtil.getDefaultValidator();
BeanDescriptor beanDescriptor = validator.getConstraintsForClass( Order.class );
@@ -155,7 +172,10 @@
}
@Test
- @SpecAssertion(section = "5.3", id = "b")
+ @SpecAssertions({
+ @SpecAssertion(section = "5.1", id = "b"),
+ @SpecAssertion(section = "5.3", id = "b")
+ })
public void testGetConstrainedPropertiesForUnconstraintEntity() {
Validator validator = TestUtil.getDefaultValidator();
BeanDescriptor beanDescriptor = validator.getConstraintsForClass( UnconstraintEntity.class );
@@ -163,6 +183,7 @@
assertEquals( constraintProperties.size(), 0, "We should get the empty set." );
}
+ // TODO - enable or remove
@Test(enabled = false)
public void testGetConstrainedPropertiesImmutable() {
Validator validator = TestUtil.getDefaultValidator();
@@ -184,4 +205,12 @@
// success
}
}
+
+ // TODO - map or remove
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testGetConstraintsForNullProperty() {
+ Validator validator = TestUtil.getDefaultValidator();
+ BeanDescriptor beanDescriptor = validator.getConstraintsForClass( Order.class );
+ beanDescriptor.getConstraintsForProperty( null );
+ }
}
Copied: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/PropertyPathTest.java (from rev 17190, beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/ValidateTest.java)
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/PropertyPathTest.java (rev 0)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/PropertyPathTest.java 2009-07-23 12:35:38 UTC (rev 17193)
@@ -0,0 +1,269 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.jsr303.tck.tests.validation;
+
+import static java.lang.annotation.ElementType.TYPE;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import javax.validation.Constraint;
+import javax.validation.ConstraintPayload;
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+import javax.validation.ConstraintViolation;
+import javax.validation.Path;
+import javax.validation.Valid;
+import javax.validation.Validator;
+
+import org.jboss.test.audit.annotations.SpecAssertion;
+import org.jboss.test.audit.annotations.SpecAssertions;
+import org.jboss.testharness.AbstractTest;
+import org.jboss.testharness.impl.packaging.Artifact;
+import org.jboss.testharness.impl.packaging.ArtifactType;
+import org.jboss.testharness.impl.packaging.Classes;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+import org.testng.annotations.Test;
+
+import org.hibernate.jsr303.tck.util.TestUtil;
+import static org.hibernate.jsr303.tck.util.TestUtil.assertCorrectNumberOfViolations;
+
+/**
+ * Tests for the implementation of <code>Validator</code>.
+ *
+ * @author Hardy Ferentschik
+ */
+@Artifact(artifactType = ArtifactType.JSR303)
+@Classes({ TestUtil.class, TestUtil.PathImpl.class, TestUtil.NodeImpl.class })
+public class PropertyPathTest extends AbstractTest {
+
+ @Test
+ @SpecAssertions({
+ @SpecAssertion(section = "4.2", id = "f"),
+ @SpecAssertion(section = "4.2", id = "g"),
+ @SpecAssertion(section = "4.2", id = "m")
+ })
+ public void testPropertyPathWithConstraintViolationForRootObject() {
+ Validator validator = TestUtil.getDefaultValidator();
+ Set<ConstraintViolation<VerySpecialClass>> constraintViolations = validator.validate( new VerySpecialClass() );
+ assertCorrectNumberOfViolations( constraintViolations, 1 );
+ ConstraintViolation<VerySpecialClass> constraintViolation = constraintViolations.iterator().next();
+
+ Iterator<Path.Node> nodeIter = constraintViolation.getPropertyPath().iterator();
+ assertTrue( nodeIter.hasNext() );
+ Path.Node node = nodeIter.next();
+ assertEquals( node.getName(), null );
+ assertFalse( node.isInIterable() );
+ assertFalse( nodeIter.hasNext() );
+ }
+
+ @Test
+ @SpecAssertions({
+ @SpecAssertion(section = "4.2", id = "f"),
+ @SpecAssertion(section = "4.2", id = "h"),
+ @SpecAssertion(section = "4.2", id = "l")
+ })
+ public void testPropertyPathTraversedObject() {
+ Validator validator = TestUtil.getDefaultValidator();
+
+ Engine engine = new Engine();
+ engine.setSerialNumber( "ABCDEFGH1234" );
+ Set<ConstraintViolation<Engine>> constraintViolations = validator.validate( engine );
+ assertCorrectNumberOfViolations( constraintViolations, 1 );
+
+ ConstraintViolation<Engine> constraintViolation = constraintViolations.iterator().next();
+
+ Iterator<Path.Node> nodeIter = constraintViolation.getPropertyPath().iterator();
+ assertTrue( nodeIter.hasNext() );
+ Path.Node node = nodeIter.next();
+ assertEquals( node.getName(), "serialNumber" );
+ assertFalse( node.isInIterable() );
+ assertFalse( nodeIter.hasNext() );
+ }
+
+ @Test
+ @SpecAssertions({
+ @SpecAssertion(section = "4.2", id = "f"),
+ @SpecAssertion(section = "4.2", id = "i"),
+ @SpecAssertion(section = "4.2", id = "k")
+ })
+ public void testPropertyPathWithList() {
+ Validator validator = TestUtil.getDefaultValidator();
+
+ Actor clint = new ActorListBased( "Clint", "Eastwood" );
+ Actor morgan = new ActorListBased( "Morgan", null );
+ Actor charlie = new ActorListBased( "Charlie", "Sheen" );
+
+ clint.addPlayedWith( charlie );
+ charlie.addPlayedWith( clint );
+ charlie.addPlayedWith( morgan );
+ morgan.addPlayedWith( charlie );
+
+ Set<ConstraintViolation<Actor>> constraintViolations = validator.validate( clint );
+ checkActorViolations( constraintViolations );
+ }
+
+ @Test
+ @SpecAssertions({
+ @SpecAssertion(section = "4.2", id = "f"),
+ @SpecAssertion(section = "4.2", id = "i"),
+ @SpecAssertion(section = "4.2", id = "k")
+ })
+ public void testPropertyPathWithArray() {
+ Validator validator = TestUtil.getDefaultValidator();
+
+ Actor clint = new ActorArrayBased( "Clint", "Eastwood" );
+ Actor morgan = new ActorArrayBased( "Morgan", null );
+ Actor charlie = new ActorArrayBased( "Charlie", "Sheen" );
+
+ clint.addPlayedWith( charlie );
+ charlie.addPlayedWith( clint );
+ charlie.addPlayedWith( morgan );
+ morgan.addPlayedWith( charlie );
+
+ Set<ConstraintViolation<Actor>> constraintViolations = validator.validate( clint );
+ checkActorViolations( constraintViolations );
+ }
+
+ @Test
+ @SpecAssertions({
+ @SpecAssertion(section = "4.2", id = "f"),
+ @SpecAssertion(section = "4.2", id = "j"),
+ @SpecAssertion(section = "4.2", id = "k")
+ })
+ public void testPropertyPathWithMap() {
+ Validator validator = TestUtil.getDefaultValidator();
+
+ ActorDB db = new ActorDB();
+ Actor morgan = new ActorArrayBased( "Morgan", null );
+ Integer id = db.addActor( morgan );
+
+ Set<ConstraintViolation<ActorDB>> constraintViolations = validator.validate( db );
+ assertCorrectNumberOfViolations( constraintViolations, 1 );
+
+ ConstraintViolation<ActorDB> constraintViolation = constraintViolations.iterator().next();
+ Iterator<Path.Node> nodeIter = constraintViolation.getPropertyPath().iterator();
+ assertTrue( nodeIter.hasNext() );
+ Path.Node node = nodeIter.next();
+ assertEquals( node.getName(), "actors" );
+ assertEquals( node.getKey(), id );
+ assertTrue( node.isInIterable() );
+
+ node = nodeIter.next();
+ assertEquals( node.getName(), "lastName" );
+ assertFalse( node.isInIterable() );
+
+ assertFalse( nodeIter.hasNext() );
+ }
+
+ @Test
+ @SpecAssertions({
+ @SpecAssertion(section = "4.2", id = "f"),
+ @SpecAssertion(section = "4.2", id = "k")
+ })
+ public void testPropertyPathSet() {
+ Validator validator = TestUtil.getDefaultValidator();
+
+ Customer customer = new Customer();
+ customer.setFirstName( "John" );
+ customer.setLastName( "Doe" );
+ Order order = new Order();
+ customer.addOrder( order );
+
+ Set<ConstraintViolation<Customer>> constraintViolations = validator.validate( customer );
+ assertCorrectNumberOfViolations( constraintViolations, 1 );
+
+ ConstraintViolation<Customer> constraintViolation = constraintViolations.iterator().next();
+ Iterator<Path.Node> nodeIter = constraintViolation.getPropertyPath().iterator();
+ assertTrue( nodeIter.hasNext() );
+ Path.Node node = nodeIter.next();
+ assertEquals( node.getName(), "orders" );
+ assertTrue( node.isInIterable() );
+
+ node = nodeIter.next();
+ assertEquals( node.getName(), "orderNumber" );
+
+ assertFalse( nodeIter.hasNext() );
+ }
+
+ private void checkActorViolations(Set<ConstraintViolation<Actor>> constraintViolations) {
+ assertCorrectNumberOfViolations( constraintViolations, 1 );
+
+ ConstraintViolation<Actor> constraintViolation = constraintViolations.iterator().next();
+
+ Iterator<Path.Node> nodeIter = constraintViolation.getPropertyPath().iterator();
+ assertTrue( nodeIter.hasNext() );
+ Path.Node node = nodeIter.next();
+ assertEquals( node.getName(), "playedWith" );
+ assertEquals( node.getIndex(), new Integer( 0 ) );
+ assertTrue( node.isInIterable() );
+
+ node = nodeIter.next();
+ assertEquals( node.getName(), "playedWith" );
+ assertEquals( node.getIndex(), new Integer( 1 ) );
+ assertTrue( node.isInIterable() );
+
+ node = nodeIter.next();
+ assertEquals( node.getName(), "lastName" );
+ assertFalse( node.isInIterable() );
+
+ assertFalse( nodeIter.hasNext() );
+ }
+
+ @Special()
+ class VerySpecialClass {
+ }
+
+ @Constraint(validatedBy = { SpecialValidator.class })
+ @Target({ TYPE })
+ @Retention(RUNTIME)
+ public @interface Special {
+ public abstract String message() default "special validation failed";
+
+ public abstract Class<?>[] groups() default { };
+
+ public abstract Class<? extends ConstraintPayload>[] payload() default { };
+ }
+
+ public static class SpecialValidator implements ConstraintValidator<Special, VerySpecialClass> {
+ public void initialize(Special constraintAnnotation) {
+ }
+
+ public boolean isValid(VerySpecialClass clazz, ConstraintValidatorContext constraintValidatorContext) {
+ return false;
+ }
+ }
+
+ class ActorDB {
+ private int idGen = 0;
+
+ @Valid
+ Map<Integer, Actor> actors = new HashMap<Integer, Actor>();
+
+ public Integer addActor(Actor actor) {
+ Integer id = idGen++;
+ actors.put( id, actor );
+ return id;
+ }
+ }
+}
\ No newline at end of file
Modified: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/ValidateTest.java
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/ValidateTest.java 2009-07-22 20:40:50 UTC (rev 17192)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/ValidateTest.java 2009-07-23 12:35:38 UTC (rev 17193)
@@ -43,9 +43,9 @@
import org.hibernate.jsr303.tck.util.TestUtil;
import static org.hibernate.jsr303.tck.util.TestUtil.assertConstraintViolation;
+import static org.hibernate.jsr303.tck.util.TestUtil.assertCorrectConstraintTypes;
import static org.hibernate.jsr303.tck.util.TestUtil.assertCorrectNumberOfViolations;
import static org.hibernate.jsr303.tck.util.TestUtil.assertCorrectPropertyPaths;
-import static org.hibernate.jsr303.tck.util.TestUtil.assertCorrectConstraintTypes;
/**
* Tests for the implementation of <code>Validator</code>.
@@ -71,18 +71,43 @@
catch ( ValidationException e ) {
// success
}
+ }
+ @Test
+ @SpecAssertion(section = "5.1", id = "b")
+ public void testConstraintDescriptorWithoutExplicitGroup() {
+ Validator validator = TestUtil.getDefaultValidator();
+
+ BeanDescriptor beanDescriptor = validator.getConstraintsForClass( Order.class );
+ PropertyDescriptor propertyDescriptor = beanDescriptor.getConstraintsForProperty( "orderNumber" );
+ Set<ConstraintDescriptor<?>> descriptors = propertyDescriptor.getConstraintDescriptors();
+
+ assertEquals( descriptors.size(), 1, "There should be only one constraint descriptor" );
+ ConstraintDescriptor<?> descriptor = descriptors.iterator().next();
+ Set<Class<?>> groups = descriptor.getGroups();
+ assertTrue( groups.size() == 1, "There should be only one group" );
+ assertEquals(
+ groups.iterator().next(),
+ Default.class,
+ "The declared constraint does not explicitly define a group, hence Default is expected"
+ );
}
- @SpecAssertion(section = "4.1.1", id = "b")
@Test(expectedExceptions = IllegalArgumentException.class)
+ @SpecAssertion(section = "5.1", id = "c")
+ public void testNullParamterToGetConstraintsForClass() {
+ TestUtil.getDefaultValidator().getConstraintsForClass( null );
+ }
+
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ @SpecAssertion(section = "4.1.1", id = "b")
public void testValidateWithNullValue() {
Validator validator = TestUtil.getDefaultValidator();
validator.validate( null );
}
- @SpecAssertion(section = "4.1.1", id = "b")
@Test(expectedExceptions = IllegalArgumentException.class)
+ @SpecAssertion(section = "4.1.1", id = "b")
@SuppressWarnings("NullArgumentToVariableArgMethod")
public void testValidateWithNullGroup() {
Validator validator = TestUtil.getDefaultValidator();
@@ -124,7 +149,7 @@
Set<ConstraintViolation<Address>> constraintViolations = validator.validate( address );
assertCorrectNumberOfViolations( constraintViolations, 2 );
- assertCorrectConstraintTypes(constraintViolations, Size.class, NotEmpty.class );
+ assertCorrectConstraintTypes( constraintViolations, Size.class, NotEmpty.class );
}
@Test
@@ -134,14 +159,12 @@
@SpecAssertion(section = "4.2", id = "b"),
@SpecAssertion(section = "4.2", id = "c"),
@SpecAssertion(section = "4.2", id = "d"),
- @SpecAssertion(section = "4.2", id = "e"),
- @SpecAssertion(section = "4.2", id = "g")
+ @SpecAssertion(section = "4.2", id = "e")
})
public void testConstraintViolation() {
Validator validator = TestUtil.getDefaultValidator();
Engine engine = new Engine();
- engine.setSerialNumber( "mail(a)foobar.com" );
engine.setSerialNumber( "ABCDEFGH1234" );
Set<ConstraintViolation<Engine>> constraintViolations = validator.validate( engine );
assertCorrectNumberOfViolations( constraintViolations, 1 );
@@ -165,31 +188,8 @@
@Test
@SpecAssertions({
- @SpecAssertion(section = "4.2", id = "f"),
- @SpecAssertion(section = "4.2", id = "g")
+ @SpecAssertion(section = "2.4", id = "o")
})
- public void testValidateAssociation() {
- Validator validator = TestUtil.getDefaultValidator();
-
- Customer customer = new Customer();
- customer.setFirstName( "John" );
- customer.setLastName( "Doe" );
- Order order = new Order();
- customer.addOrder( order );
-
- Set<ConstraintViolation<Customer>> constraintViolations = validator.validate( customer );
- assertCorrectNumberOfViolations( constraintViolations, 1 );
- assertCorrectPropertyPaths( constraintViolations, "orders[].orderNumber" );
- ConstraintViolation constraintViolation = constraintViolations.iterator().next();
- assertEquals( constraintViolation.getRootBean(), customer, "Wrong root entity" );
- assertEquals( constraintViolation.getInvalidValue(), order.getOrderNumber(), "Wrong value" );
- }
-
- @Test
- @SpecAssertions({
- @SpecAssertion(section = "2.4", id = "o"),
- @SpecAssertion(section = "4.2", id = "h")
- })
public void testGraphValidationWithList() {
Validator validator = TestUtil.getDefaultValidator();
@@ -213,15 +213,16 @@
assertEquals( constraintViolation.getRootBean(), clint, "Wrong root entity" );
assertEquals( constraintViolation.getInvalidValue(), morgan.getLastName(), "Wrong value" );
assertCorrectPropertyPaths(
- constraintViolations, "playedWith[0].playedWith[1].lastName", "playedWith[1].lastName"
+ constraintViolations,
+ "playedWith[0].playedWith[1].lastName",
+ "playedWith[1].lastName"
);
}
@Test
@SpecAssertions({
@SpecAssertion(section = "2.4", id = "o"),
- @SpecAssertion(section = "3.1.3", id = "c"),
- @SpecAssertion(section = "4.2", id = "h")
+ @SpecAssertion(section = "3.1.3", id = "c")
})
public void testGraphValidationWithArray() {
Validator validator = TestUtil.getDefaultValidator();
@@ -244,16 +245,14 @@
assertEquals( constraintViolation.getRootBean(), clint, "Wrong root entity" );
assertEquals( constraintViolation.getInvalidValue(), morgan.getLastName(), "Wrong value" );
assertCorrectPropertyPaths(
- constraintViolations, "playedWith[0].playedWith[1].lastName", "playedWith[1].lastName"
+ constraintViolations,
+ "playedWith[0].playedWith[1].lastName",
+ "playedWith[1].lastName"
);
}
- @Test(expectedExceptions = IllegalArgumentException.class)
- public void testNullParamterToValidatorImplConstructor() {
- TestUtil.getDefaultValidator().getConstraintsForClass( null );
- }
-
@Test
+ @SpecAssertion(section = "4.1.1", id = "b")
@SuppressWarnings("NullArgumentToVariableArgMethod")
public void testPassingNullAsGroup() {
Validator validator = TestUtil.getDefaultValidator();
@@ -267,6 +266,32 @@
}
@Test
+ @SpecAssertion(section = "3.5", id = "b")
+ public void testOnlyFirstGroupInSequenceGetEvaluated() {
+ Validator validator = TestUtil.getDefaultValidator();
+ Car car = new Car( "USd-298" );
+
+ Set<ConstraintViolation<Car>> violations = validator.validateProperty(
+ car, "licensePlateNumber", First.class, Second.class
+ );
+ assertCorrectNumberOfViolations( violations, 1 );
+
+ car.setLicensePlateNumber( "USD-298" );
+ violations = validator.validateProperty(
+ car, "licensePlateNumber", First.class, Second.class
+ );
+ assertCorrectNumberOfViolations( violations, 0 );
+ }
+
+ @Test(expectedExceptions = ValidationException.class)
+ @SpecAssertion(section = "4.1.1", id = "k")
+ public void testUnexpectedExceptionsInValidateGetWrappedInValidationExceptions() {
+ Validator validator = TestUtil.getDefaultValidator();
+ validator.validate( new BadlyBehavedEntity() );
+ }
+
+ // TODO - map or remove
+ @Test
public void testValidationIsPolymorphic() {
Validator validator = TestUtil.getDefaultValidator();
@@ -293,6 +318,7 @@
assertCorrectNumberOfViolations( constraintViolations, 0 );
}
+ // TODO - map or remove
@Test
public void testObjectTraversion() {
Validator validator = TestUtil.getDefaultValidator();
@@ -312,50 +338,6 @@
assertCorrectNumberOfViolations( constraintViolations, 100 );
}
- @Test
- public void testConstraintDescriptorWithoutExplicitGroup() {
- Validator validator = TestUtil.getDefaultValidator();
-
- BeanDescriptor beanDescriptor = validator.getConstraintsForClass( Order.class );
- PropertyDescriptor propertyDescriptor = beanDescriptor.getConstraintsForProperty( "orderNumber" );
- Set<ConstraintDescriptor<?>> descriptors = propertyDescriptor.getConstraintDescriptors();
-
- assertEquals( descriptors.size(), 1, "There should be only one constraint descriptor" );
- ConstraintDescriptor<?> descriptor = descriptors.iterator().next();
- Set<Class<?>> groups = descriptor.getGroups();
- assertTrue( groups.size() == 1, "There should be only one group" );
- assertEquals(
- groups.iterator().next(),
- Default.class,
- "The declared constraint does not explicitly define a group, hence Default is expected"
- );
- }
-
- @Test
- @SpecAssertion(section = "3.5", id = "b")
- public void testOnlyFirstGroupInSequenceGetEvaluated() {
- Validator validator = TestUtil.getDefaultValidator();
- Car car = new Car( "USd-298" );
-
- Set<ConstraintViolation<Car>> violations = validator.validateProperty(
- car, "licensePlateNumber", First.class, Second.class
- );
- assertCorrectNumberOfViolations( violations, 1 );
-
- car.setLicensePlateNumber( "USD-298" );
- violations = validator.validateProperty(
- car, "licensePlateNumber", First.class, Second.class
- );
- assertCorrectNumberOfViolations( violations, 0 );
- }
-
- @Test(expectedExceptions = ValidationException.class)
- @SpecAssertion(section = "4.1.1", id = "k")
- public void testUnexpectedExceptionsInValidateGetWrappedInValidationExceptions() {
- Validator validator = TestUtil.getDefaultValidator();
- validator.validate( new BadlyBehavedEntity() );
- }
-
class Car {
@Pattern(regexp = "[A-Z][A-Z][A-Z]-[0-9][0-9][0-9]", groups = { First.class, Second.class })
private String licensePlateNumber;
Deleted: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/ValidateWithGroups.java
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/ValidateWithGroups.java 2009-07-22 20:40:50 UTC (rev 17192)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/ValidateWithGroups.java 2009-07-23 12:35:38 UTC (rev 17193)
@@ -1,130 +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.jsr303.tck.tests.validation;
-
-import java.util.Set;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validator;
-import javax.validation.constraints.NotNull;
-import javax.validation.groups.Default;
-
-import org.jboss.test.audit.annotations.SpecAssertion;
-import org.jboss.test.audit.annotations.SpecAssertions;
-import org.jboss.testharness.AbstractTest;
-import org.jboss.testharness.impl.packaging.Artifact;
-import org.jboss.testharness.impl.packaging.ArtifactType;
-import org.jboss.testharness.impl.packaging.Classes;
-import org.testng.annotations.Test;
-
-import org.hibernate.jsr303.tck.util.TestUtil;
-import static org.hibernate.jsr303.tck.util.TestUtil.assertCorrectConstraintTypes;
-import static org.hibernate.jsr303.tck.util.TestUtil.assertCorrectNumberOfViolations;
-import static org.hibernate.jsr303.tck.util.TestUtil.assertCorrectPropertyPaths;
-
-/**
- * Tests for the implementation of {@code Validator}.
- *
- * @author Hardy Ferentschik
- */
-@Artifact(artifactType = ArtifactType.JSR303)
-@Classes({ TestUtil.class, TestUtil.PathImpl.class, TestUtil.NodeImpl.class })
-public class ValidateWithGroups extends AbstractTest {
-
- @Test
- @SpecAssertions({
- @SpecAssertion(section = "4.1.2", id = "a"),
- @SpecAssertion(section = "4.1.2", id = "b")
- })
- public void testCorrectGroupsAreAppliedForValidate() {
- Validator validator = TestUtil.getDefaultValidator();
-
- Set<ConstraintViolation<Address>> constraintViolations = validator.validate( new Address() );
- assertCorrectNumberOfViolations( constraintViolations, 2 );
- assertCorrectConstraintTypes( constraintViolations, NotNull.class, NotEmpty.class );
- assertCorrectPropertyPaths( constraintViolations, "city", "zipCode" );
-
- constraintViolations = validator.validate( new Address(), Default.class );
- assertCorrectNumberOfViolations( constraintViolations, 2 );
- assertCorrectConstraintTypes( constraintViolations, NotNull.class, NotEmpty.class );
- assertCorrectPropertyPaths( constraintViolations, "city", "zipCode" );
-
- constraintViolations = validator.validate( new Address(), Address.Minimal.class );
- assertCorrectNumberOfViolations( constraintViolations, 2 );
- assertCorrectConstraintTypes( constraintViolations, NotEmpty.class, NotEmpty.class );
- assertCorrectPropertyPaths( constraintViolations, "street", "zipCode" );
-
- constraintViolations = validator.validate( new Address(), Default.class, Address.Minimal.class );
- assertCorrectNumberOfViolations( constraintViolations, 3 );
- assertCorrectConstraintTypes( constraintViolations, NotNull.class, NotEmpty.class, NotEmpty.class );
- assertCorrectPropertyPaths( constraintViolations, "city", "street", "zipCode" );
- }
-
- @Test
- @SpecAssertions({
- @SpecAssertion(section = "4.1.2", id = "a"),
- @SpecAssertion(section = "4.1.2", id = "b")
- })
- public void testCorrectGroupsAreAppliedForValidateProperty() {
- Validator validator = TestUtil.getDefaultValidator();
-
- Set<ConstraintViolation<Address>> constraintViolations = validator.validateProperty( new Address(), "city" );
- assertCorrectNumberOfViolations( constraintViolations, 1 );
- assertCorrectConstraintTypes( constraintViolations, NotNull.class );
- assertCorrectPropertyPaths( constraintViolations, "city" );
-
- constraintViolations = validator.validateProperty( new Address(), "city", Default.class );
- assertCorrectNumberOfViolations( constraintViolations, 1 );
- assertCorrectConstraintTypes( constraintViolations, NotNull.class );
- assertCorrectPropertyPaths( constraintViolations, "city" );
-
- constraintViolations = validator.validateProperty( new Address(), "city", Address.Minimal.class );
- assertCorrectNumberOfViolations( constraintViolations, 0 );
-
- constraintViolations = validator.validateProperty( new Address(), "street", Address.Minimal.class );
- assertCorrectNumberOfViolations( constraintViolations, 1 );
- assertCorrectConstraintTypes( constraintViolations, NotEmpty.class );
- assertCorrectPropertyPaths( constraintViolations, "street" );
- }
-
- @Test
- @SpecAssertions({
- @SpecAssertion(section = "4.1.2", id = "a"),
- @SpecAssertion(section = "4.1.2", id = "b")
- })
- public void testCorrectGroupsAreAppliedForValidateValue() {
- Validator validator = TestUtil.getDefaultValidator();
-
- Set<ConstraintViolation<Address>> constraintViolations = validator.validateValue( Address.class, "city", null );
- assertCorrectNumberOfViolations( constraintViolations, 1 );
- assertCorrectConstraintTypes( constraintViolations, NotNull.class );
- assertCorrectPropertyPaths( constraintViolations, "city" );
-
- constraintViolations = validator.validateValue( Address.class, "city", null, Default.class );
- assertCorrectNumberOfViolations( constraintViolations, 1 );
- assertCorrectConstraintTypes( constraintViolations, NotNull.class );
- assertCorrectPropertyPaths( constraintViolations, "city" );
-
- constraintViolations = validator.validateValue( Address.class, "city", null, Address.Minimal.class );
- assertCorrectNumberOfViolations( constraintViolations, 0 );
-
- constraintViolations = validator.validateValue( Address.class, "street", null, Address.Minimal.class );
- assertCorrectNumberOfViolations( constraintViolations, 1 );
- assertCorrectConstraintTypes( constraintViolations, NotEmpty.class );
- assertCorrectPropertyPaths( constraintViolations, "street" );
- }
-}
\ No newline at end of file
Copied: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/ValidateWithGroupsTest.java (from rev 17190, beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/ValidateWithGroups.java)
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/ValidateWithGroupsTest.java (rev 0)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/ValidateWithGroupsTest.java 2009-07-23 12:35:38 UTC (rev 17193)
@@ -0,0 +1,130 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.jsr303.tck.tests.validation;
+
+import java.util.Set;
+import javax.validation.ConstraintViolation;
+import javax.validation.Validator;
+import javax.validation.constraints.NotNull;
+import javax.validation.groups.Default;
+
+import org.jboss.test.audit.annotations.SpecAssertion;
+import org.jboss.test.audit.annotations.SpecAssertions;
+import org.jboss.testharness.AbstractTest;
+import org.jboss.testharness.impl.packaging.Artifact;
+import org.jboss.testharness.impl.packaging.ArtifactType;
+import org.jboss.testharness.impl.packaging.Classes;
+import org.testng.annotations.Test;
+
+import org.hibernate.jsr303.tck.util.TestUtil;
+import static org.hibernate.jsr303.tck.util.TestUtil.assertCorrectConstraintTypes;
+import static org.hibernate.jsr303.tck.util.TestUtil.assertCorrectNumberOfViolations;
+import static org.hibernate.jsr303.tck.util.TestUtil.assertCorrectPropertyPaths;
+
+/**
+ * Tests for the implementation of {@code Validator}.
+ *
+ * @author Hardy Ferentschik
+ */
+@Artifact(artifactType = ArtifactType.JSR303)
+@Classes({ TestUtil.class, TestUtil.PathImpl.class, TestUtil.NodeImpl.class })
+public class ValidateWithGroupsTest extends AbstractTest {
+
+ @Test
+ @SpecAssertions({
+ @SpecAssertion(section = "4.1.2", id = "a"),
+ @SpecAssertion(section = "4.1.2", id = "b")
+ })
+ public void testCorrectGroupsAreAppliedForValidate() {
+ Validator validator = TestUtil.getDefaultValidator();
+
+ Set<ConstraintViolation<Address>> constraintViolations = validator.validate( new Address() );
+ assertCorrectNumberOfViolations( constraintViolations, 2 );
+ assertCorrectConstraintTypes( constraintViolations, NotNull.class, NotEmpty.class );
+ assertCorrectPropertyPaths( constraintViolations, "city", "zipCode" );
+
+ constraintViolations = validator.validate( new Address(), Default.class );
+ assertCorrectNumberOfViolations( constraintViolations, 2 );
+ assertCorrectConstraintTypes( constraintViolations, NotNull.class, NotEmpty.class );
+ assertCorrectPropertyPaths( constraintViolations, "city", "zipCode" );
+
+ constraintViolations = validator.validate( new Address(), Address.Minimal.class );
+ assertCorrectNumberOfViolations( constraintViolations, 2 );
+ assertCorrectConstraintTypes( constraintViolations, NotEmpty.class, NotEmpty.class );
+ assertCorrectPropertyPaths( constraintViolations, "street", "zipCode" );
+
+ constraintViolations = validator.validate( new Address(), Default.class, Address.Minimal.class );
+ assertCorrectNumberOfViolations( constraintViolations, 3 );
+ assertCorrectConstraintTypes( constraintViolations, NotNull.class, NotEmpty.class, NotEmpty.class );
+ assertCorrectPropertyPaths( constraintViolations, "city", "street", "zipCode" );
+ }
+
+ @Test
+ @SpecAssertions({
+ @SpecAssertion(section = "4.1.2", id = "a"),
+ @SpecAssertion(section = "4.1.2", id = "b")
+ })
+ public void testCorrectGroupsAreAppliedForValidateProperty() {
+ Validator validator = TestUtil.getDefaultValidator();
+
+ Set<ConstraintViolation<Address>> constraintViolations = validator.validateProperty( new Address(), "city" );
+ assertCorrectNumberOfViolations( constraintViolations, 1 );
+ assertCorrectConstraintTypes( constraintViolations, NotNull.class );
+ assertCorrectPropertyPaths( constraintViolations, "city" );
+
+ constraintViolations = validator.validateProperty( new Address(), "city", Default.class );
+ assertCorrectNumberOfViolations( constraintViolations, 1 );
+ assertCorrectConstraintTypes( constraintViolations, NotNull.class );
+ assertCorrectPropertyPaths( constraintViolations, "city" );
+
+ constraintViolations = validator.validateProperty( new Address(), "city", Address.Minimal.class );
+ assertCorrectNumberOfViolations( constraintViolations, 0 );
+
+ constraintViolations = validator.validateProperty( new Address(), "street", Address.Minimal.class );
+ assertCorrectNumberOfViolations( constraintViolations, 1 );
+ assertCorrectConstraintTypes( constraintViolations, NotEmpty.class );
+ assertCorrectPropertyPaths( constraintViolations, "street" );
+ }
+
+ @Test
+ @SpecAssertions({
+ @SpecAssertion(section = "4.1.2", id = "a"),
+ @SpecAssertion(section = "4.1.2", id = "b")
+ })
+ public void testCorrectGroupsAreAppliedForValidateValue() {
+ Validator validator = TestUtil.getDefaultValidator();
+
+ Set<ConstraintViolation<Address>> constraintViolations = validator.validateValue( Address.class, "city", null );
+ assertCorrectNumberOfViolations( constraintViolations, 1 );
+ assertCorrectConstraintTypes( constraintViolations, NotNull.class );
+ assertCorrectPropertyPaths( constraintViolations, "city" );
+
+ constraintViolations = validator.validateValue( Address.class, "city", null, Default.class );
+ assertCorrectNumberOfViolations( constraintViolations, 1 );
+ assertCorrectConstraintTypes( constraintViolations, NotNull.class );
+ assertCorrectPropertyPaths( constraintViolations, "city" );
+
+ constraintViolations = validator.validateValue( Address.class, "city", null, Address.Minimal.class );
+ assertCorrectNumberOfViolations( constraintViolations, 0 );
+
+ constraintViolations = validator.validateValue( Address.class, "street", null, Address.Minimal.class );
+ assertCorrectNumberOfViolations( constraintViolations, 1 );
+ assertCorrectConstraintTypes( constraintViolations, NotEmpty.class );
+ assertCorrectPropertyPaths( constraintViolations, "street" );
+ }
+}
\ No newline at end of file
Property changes on: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/ValidateWithGroupsTest.java
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Address.java
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Address.java 2009-07-22 20:40:50 UTC (rev 17192)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/Address.java 2009-07-23 12:35:38 UTC (rev 17193)
@@ -79,4 +79,15 @@
public void setInhabitant(User inhabitant) {
this.inhabitant = inhabitant;
}
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder();
+ sb.append( "Address" );
+ sb.append( "{addressline1='" ).append( addressline1 ).append( '\'' );
+ sb.append( ", zipCode='" ).append( zipCode ).append( '\'' );
+ sb.append( ", city='" ).append( city ).append( '\'' );
+ sb.append( '}' );
+ return sb.toString();
+ }
}
\ No newline at end of file
Modified: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/User.java
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/User.java 2009-07-22 20:40:50 UTC (rev 17192)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/validation/graphnavigation/User.java 2009-07-23 12:35:38 UTC (rev 17193)
@@ -79,4 +79,16 @@
public void setLastName(String lastName) {
this.lastName = lastName;
}
+
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder();
+ sb.append( "User" );
+ sb.append( "{addresses=" ).append( addresses );
+ sb.append( ", lastName='" ).append( lastName ).append( '\'' );
+ sb.append( ", firstName='" ).append( firstName ).append( '\'' );
+ sb.append( '}' );
+ return sb.toString();
+ }
}
\ No newline at end of file
Modified: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/util/TestUtil.java
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/util/TestUtil.java 2009-07-22 20:40:50 UTC (rev 17192)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/util/TestUtil.java 2009-07-23 12:35:38 UTC (rev 17193)
@@ -113,6 +113,12 @@
propertyPathsOfViolations.add( violation.getPropertyPath() );
}
+ assertEquals(
+ propertyPaths.length,
+ propertyPathsOfViolations.size(),
+ "Wrong number of property paths. Expected: " + propertyPaths.length + " Actual: " + propertyPathsOfViolations.size()
+ );
+
for ( String propertyPath : propertyPaths ) {
Path expectedPath = PathImpl.createPathFromString( propertyPath );
boolean containsPath = false;
@@ -129,8 +135,9 @@
}
public static <T> void assertConstraintViolation(ConstraintViolation<T> violation, Class<?> rootBean, Object invalidValue, String propertyPath) {
- if ( !assertEqualPaths( violation.getPropertyPath(), PathImpl.createPathFromString( propertyPath ) ) ) {
- fail( "Property paths differ." );
+ Path expectedPath = PathImpl.createPathFromString( propertyPath );
+ if ( !assertEqualPaths( violation.getPropertyPath(), expectedPath ) ) {
+ fail( "Property paths differ. Actual: " + violation.getPropertyPath() + " Expected: " + expectedPath );
}
assertEquals(
@@ -224,8 +231,6 @@
private static final String PROPERTY_PATH_SEPERATOR = ".";
- private static final Node ROOT_NODE = new NodeImpl( ( String ) null );
-
private final List<Node> nodeList;
public static PathImpl createPathFromString(String propertyPath) {
@@ -234,19 +239,21 @@
}
if ( propertyPath.length() == 0 ) {
- return createNewRootPath();
+ return createNewPath( null );
}
return parseProperty( propertyPath );
}
- public static PathImpl createNewRootPath() {
- return new PathImpl();
+ public static PathImpl createNewPath(String name) {
+ PathImpl path = new PathImpl();
+ NodeImpl node = new NodeImpl( name );
+ path.addNode( node );
+ return path;
}
private PathImpl() {
nodeList = new ArrayList<Node>();
- nodeList.add( ROOT_NODE );
}
public void addNode(Node node) {
@@ -263,9 +270,6 @@
Iterator<Path.Node> iter = iterator();
while ( iter.hasNext() ) {
Node node = iter.next();
- if ( ROOT_NODE.equals( node ) ) {
- continue;
- }
builder.append( node.toString() );
if ( iter.hasNext() ) {
builder.append( PROPERTY_PATH_SEPERATOR );
Modified: beanvalidation/trunk/validation-tck/src/main/resources/tck-audit.xml
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/resources/tck-audit.xml 2009-07-22 20:40:50 UTC (rev 17192)
+++ beanvalidation/trunk/validation-tck/src/main/resources/tck-audit.xml 2009-07-23 12:35:38 UTC (rev 17193)
@@ -594,27 +594,37 @@
<text>getConstraintDescriptor provides access to the failing constraint metadata</text>
</assertion>
<assertion id="f">
- <text>if the association is not hosted by the root object (ie hosted on an associated
- object) a dot (.) is concatenated to the propertyPath</text>
- </assertion>
+ <text>getPropertyPath returns the Path object representing the navigation path from the root object to the failing
+ object</text>
+ </assertion>
<assertion id="g">
- <text>the name of the association property (field name or Java Bean property name) is
- concatenated to the propertyPath.</text>
- </assertion>
+ <text>If the failing object is the root object, the property path consists of a single Node with name set to null.</text>
+ </assertion>
<assertion id="h">
- <text>if the association is a List or an array, the index value surrounded by square
- brackets ([index]) is concatenated to the propertyPath (for example
- order.orderLines[1])</text>
- </assertion>
+ <text>If failing object is traversed, a Node object whose name equals the name of the association property (field name or Java Bean property
+ name) is added to Path.
+ </text>
+ </assertion>
<assertion id="i">
- <text>if the association is a Map, for a given map entry, the result of key.toString()
- surrounded by square brack- ets and quotes (["key.toString()"]) is concatenated to
- the propertyPath (for example item.evaluation["quality"])</text>
- </assertion>
+ <text>If the traversed association is a List or an array, the added Node object contains the index value in getIndex.
+ </text>
+ </assertion>
<assertion id="j">
- <text>If the propertyPath is empty, "" is returned (typically a class-level constraint
- on the root object)</text>
+ <text>If the association is a Map, the added Node object (representing a given map entry) contains the key value in getKey
+ </text>
+ </assertion>
+ <assertion id="k">
+ <text>For all Iterable or Map, the added Node object added is marked as inIterable (isInIterable)
+ </text>
</assertion>
+ <assertion id="l">
+ <text>For a property level constraint (field and getter) a Node object is added to Path whose name equals the name of the property.
+ </text>
+ </assertion>
+ <assertion id="m">
+ <text>For a class level constraint a Node object is added to Path whose name is null
+ </text>
+ </assertion>
</section>
<section id="4.3.1" title="Default message interpolation">
<assertion id="a">
@@ -892,6 +902,13 @@
it's superclasses and interfaces according to the constraint propagation rules) is
invalid, a ValidationException is raised</text>
</assertion>
+ <assertion id="b">
+ <text>Validator.getConstraintsForClass returns a BeanDescriptor object describing the bean level constraints
+ and providing access to the property level constraints metadata. </text>
+ </assertion>
+ <assertion id="c">
+ <text>Validator.getConstraintsForClass throws an IllegalArgumentException if the clazz parameter is null</text>
+ </assertion>
</section>
<section id="5.3" title="BeanDescriptor">
<assertion id="a">
15 years, 4 months
Hibernate SVN: r17192 - in core/trunk: annotations/src/main/java/org/hibernate/cfg/annotations and 7 other directories.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2009-07-22 16:40:50 -0400 (Wed, 22 Jul 2009)
New Revision: 17192
Modified:
core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java
core/trunk/annotations/src/main/java/org/hibernate/cfg/IndexColumn.java
core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java
core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/ListBinder.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/any/PropertyList.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/array/Contest.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/collectionelement/Boy.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/A.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/B.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/fetch/Person.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/indexcoll/Drawer.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/indexcoll/IndexedCollectionTest.java
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/emops/Race.java
Log:
ANN-860 implement @OrderColumn
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java 2009-07-22 13:45:15 UTC (rev 17191)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java 2009-07-22 20:40:50 UTC (rev 17192)
@@ -76,6 +76,7 @@
import javax.persistence.MapKeyColumn;
import javax.persistence.MapKeyJoinColumns;
import javax.persistence.MapKeyJoinColumn;
+import javax.persistence.OrderColumn;
import org.hibernate.AnnotationException;
import org.hibernate.AssertionFailure;
@@ -1473,13 +1474,28 @@
ManyToMany manyToManyAnn = property.getAnnotation( ManyToMany.class );
ElementCollection elementCollectionAnn = property.getAnnotation( ElementCollection.class );
CollectionOfElements collectionOfElementsAnn = property.getAnnotation( CollectionOfElements.class ); //legacy hibernate
- org.hibernate.annotations.IndexColumn indexAnn = property.getAnnotation(
- org.hibernate.annotations.IndexColumn.class
- );
- IndexColumn indexColumn = IndexColumn.buildColumnFromAnnotation(
- indexAnn, propertyHolder, inferredData, mappings
- );
+ final IndexColumn indexColumn;
+
+ if ( property.isAnnotationPresent( OrderColumn.class ) ) {
+ indexColumn = IndexColumn.buildColumnFromAnnotation(
+ property.getAnnotation(OrderColumn.class),
+ propertyHolder,
+ inferredData,
+ entityBinder.getSecondaryTables(),
+ mappings
+ );
+ }
+ else {
+ //if @IndexColumn is not there, the generated IndexColumn is an implicit column and not used.
+ //so we can leave the legacy processing as the default
+ indexColumn = IndexColumn.buildColumnFromAnnotation(
+ property.getAnnotation(org.hibernate.annotations.IndexColumn.class),
+ propertyHolder,
+ inferredData,
+ mappings
+ );
+ }
CollectionBinder collectionBinder = CollectionBinder.getCollectionBinder(
propertyHolder.getEntityName(),
property,
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/IndexColumn.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/IndexColumn.java 2009-07-22 13:45:15 UTC (rev 17191)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/IndexColumn.java 2009-07-22 20:40:50 UTC (rev 17192)
@@ -25,6 +25,8 @@
import java.util.Map;
+import javax.persistence.OrderColumn;
+
import org.hibernate.mapping.Join;
/**
@@ -82,7 +84,36 @@
this.base = base;
}
+ //JPA 2 @OrderColumn processing
public static IndexColumn buildColumnFromAnnotation(
+ OrderColumn ann,
+ PropertyHolder propertyHolder,
+ PropertyData inferredData,
+ Map<String, Join> secondaryTables,
+ ExtendedMappings mappings
+ ) {
+ IndexColumn column;
+ if ( ann != null ) {
+ String sqlType = BinderHelper.isDefault( ann.columnDefinition() ) ? null : ann.columnDefinition();
+ String name = BinderHelper.isDefault( ann.name() ) ? inferredData.getPropertyName() + "_ORDER" : ann.name();
+ //TODO move it to a getter based system and remove the constructor
+ column = new IndexColumn(
+ false, sqlType, 0, 0, 0, name, ann.nullable(),
+ false, ann.insertable(), ann.updatable(), ann.table(),
+ secondaryTables, propertyHolder, mappings
+ );
+ }
+ else {
+ column = new IndexColumn(
+ true, null, 0, 0, 0, null, true,
+ false, true, true, null, null, propertyHolder, mappings
+ );
+ }
+ return column;
+ }
+
+ //legacy @IndexColumn processing
+ public static IndexColumn buildColumnFromAnnotation(
org.hibernate.annotations.IndexColumn ann,
PropertyHolder propertyHolder,
PropertyData inferredData,
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java 2009-07-22 13:45:15 UTC (rev 17191)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java 2009-07-22 20:40:50 UTC (rev 17192)
@@ -268,7 +268,8 @@
else if ( java.util.List.class.equals( returnedClass ) ) {
if ( isIndexed ) {
if ( property.isAnnotationPresent( CollectionId.class ) ) {
- throw new AnnotationException( "List do not support @CollectionId and @IndexColumn at the same time: "
+ throw new AnnotationException(
+ "List do not support @CollectionId and @OrderColumn (or @IndexColumn) at the same time: "
+ StringHelper.qualify( entityName, property.getName() ) );
}
return new ListBinder();
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/ListBinder.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/ListBinder.java 2009-07-22 13:45:15 UTC (rev 17191)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/ListBinder.java 2009-07-22 20:40:50 UTC (rev 17192)
@@ -96,7 +96,7 @@
}
private void bindIndex(final ExtendedMappings mappings) {
- if ( indexColumn.isImplicit() == false ) {
+ if ( !indexColumn.isImplicit() ) {
PropertyHolder valueHolder = PropertyHolderBuilder.buildPropertyHolder(
this.collection,
StringHelper.qualify( this.collection.getRole(), "key" ),
@@ -130,7 +130,7 @@
else {
Collection coll = this.collection;
throw new AnnotationException(
- "List/array has to be annotated with an @IndexColumn: "
+ "List/array has to be annotated with an @OrderColumn (or @IndexColumn): "
+ coll.getRole()
);
}
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/any/PropertyList.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/any/PropertyList.java 2009-07-22 13:45:15 UTC (rev 17191)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/any/PropertyList.java 2009-07-22 20:40:50 UTC (rev 17192)
@@ -2,19 +2,19 @@
import java.util.ArrayList;
import java.util.List;
+import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+import javax.persistence.OrderColumn;
import javax.persistence.Table;
-import javax.persistence.JoinTable;
-import javax.persistence.Column;
-import javax.persistence.JoinColumn;
-import org.hibernate.annotations.ManyToAny;
+import org.hibernate.annotations.Any;
import org.hibernate.annotations.Cascade;
-import org.hibernate.annotations.IndexColumn;
-import org.hibernate.annotations.Any;
import org.hibernate.annotations.CascadeType;
+import org.hibernate.annotations.ManyToAny;
@Entity
@Table( name = "property_list" )
@@ -41,7 +41,7 @@
joinColumns = @JoinColumn(name = "obj_id"),
inverseJoinColumns = @JoinColumn(name = "property_id")
)
- @IndexColumn(name = "prop_index")
+ @OrderColumn(name = "prop_index")
public List<T> getGeneralProperties() {
return generalProperties;
}
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/array/Contest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/array/Contest.java 2009-07-22 13:45:15 UTC (rev 17191)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/array/Contest.java 2009-07-22 20:40:50 UTC (rev 17192)
@@ -8,6 +8,7 @@
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.ElementCollection;
+import javax.persistence.OrderColumn;
import org.hibernate.annotations.IndexColumn;
@@ -31,7 +32,7 @@
}
@OneToMany(cascade = CascadeType.ALL)
- @IndexColumn(name = "pos")
+ @OrderColumn(name = "pos")
public Competitor[] getResults() {
return results;
}
@@ -41,7 +42,7 @@
}
@ElementCollection
- @IndexColumn(name = "pos", base=1)
+ @IndexColumn(name = "pos", base=1) //legacy + base
public Month[] getHeldIn() {
return heldIn;
}
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/collectionelement/Boy.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/collectionelement/Boy.java 2009-07-22 13:45:15 UTC (rev 17191)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/collectionelement/Boy.java 2009-07-22 20:40:50 UTC (rev 17192)
@@ -7,7 +7,9 @@
import java.util.Set;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
+import javax.persistence.CollectionTable;
import javax.persistence.Column;
+import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
@@ -15,12 +17,9 @@
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
-import javax.persistence.JoinTable;
-import javax.persistence.ElementCollection;
-import javax.persistence.CollectionTable;
+import javax.persistence.OrderColumn;
import org.hibernate.annotations.CollectionOfElements;
-import org.hibernate.annotations.IndexColumn;
/**
* @author Emmanuel Bernard
@@ -94,7 +93,7 @@
joinColumns = @JoinColumn(name = "BoyId")
)
@Column(name = "favoriteNumber", nullable = false)
- @IndexColumn(name = "nbr_index")
+ @OrderColumn(name = "nbr_index")
public int[] getFavoriteNumbers() {
return favoriteNumbers;
}
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/A.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/A.java 2009-07-22 13:45:15 UTC (rev 17191)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/A.java 2009-07-22 20:40:50 UTC (rev 17192)
@@ -11,11 +11,10 @@
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
+import javax.persistence.OrderColumn;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
-import org.hibernate.annotations.IndexColumn;
-
@Entity
@Table( name = "A" )
public class A {
@@ -24,7 +23,7 @@
@SequenceGenerator( name = "aSequence", sequenceName = "seq_A" )
private int id;
@ElementCollection
- @IndexColumn( name = "ndx" )
+ @OrderColumn( name = "ndx" )
private List<B> listOfB;
public int getId() {
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/B.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/B.java 2009-07-22 13:45:15 UTC (rev 17191)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/B.java 2009-07-22 20:40:50 UTC (rev 17192)
@@ -4,16 +4,15 @@
import java.util.List;
import javax.persistence.Embeddable;
import javax.persistence.OneToMany;
+import javax.persistence.OrderColumn;
-import org.hibernate.annotations.IndexColumn;
-
@Embeddable
public class B {
private String name;
//@CollectionOfElements
@OneToMany
- @IndexColumn( name = "ndx" )
+ @OrderColumn( name = "ndx" )
private List<C> listOfC;
public List<C> getListOfC() {
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/fetch/Person.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/fetch/Person.java 2009-07-22 13:45:15 UTC (rev 17191)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/fetch/Person.java 2009-07-22 20:40:50 UTC (rev 17192)
@@ -12,13 +12,13 @@
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
+import javax.persistence.OrderColumn;
import javax.persistence.Table;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
-import org.hibernate.annotations.IndexColumn;
/**
@@ -118,7 +118,7 @@
@OneToMany(cascade=CascadeType.ALL)
@LazyCollection(LazyCollectionOption.EXTRA)
@Fetch(FetchMode.SUBSELECT)
- @IndexColumn(name="orderedStayIndex")
+ @OrderColumn(name="orderedStayIndex")
public List<Stay> getOrderedStay() {
return orderedStay;
}
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/indexcoll/Drawer.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/indexcoll/Drawer.java 2009-07-22 13:45:15 UTC (rev 17191)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/indexcoll/Drawer.java 2009-07-22 20:40:50 UTC (rev 17192)
@@ -6,9 +6,8 @@
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
+import javax.persistence.OrderColumn;
-import org.hibernate.annotations.IndexColumn;
-
/**
* @author Emmanuel Bernard
*/
@@ -33,7 +32,7 @@
* @return
*/
@OneToMany
- @IndexColumn(name = "from_bottom_position")
+ @OrderColumn //default name test
public List<Dress> getDresses() {
return dresses;
}
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/indexcoll/IndexedCollectionTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/indexcoll/IndexedCollectionTest.java 2009-07-22 13:45:15 UTC (rev 17191)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/indexcoll/IndexedCollectionTest.java 2009-07-22 20:40:50 UTC (rev 17192)
@@ -3,17 +3,16 @@
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import java.util.Iterator;
+import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
-import org.hibernate.Hibernate;
-import org.hibernate.mapping.PersistentClass;
+import org.hibernate.dialect.HSQLDialect;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.Column;
-import org.hibernate.dialect.HSQLDialect;
import org.hibernate.test.annotations.RequiresDialect;
import org.hibernate.test.annotations.TestCase;
@@ -25,33 +24,36 @@
public class IndexedCollectionTest extends TestCase {
public void testJPA2DefaultMapColumns() throws Exception {
- isDefaultKeyColumnPresent( "gasesDef" );
- isDefaultKeyColumnPresent( "gasesPerKeyDef" );
- isNotDefaultKeyColumnPresent( "gasesDefLeg" );
+ isDefaultKeyColumnPresent( Atmosphere.class.getName(), "gasesDef", "_KEY" );
+ isDefaultKeyColumnPresent( Atmosphere.class.getName(), "gasesPerKeyDef", "_KEY" );
+ isNotDefaultKeyColumnPresent( Atmosphere.class.getName(), "gasesDefLeg", "_KEY" );
}
- private void isDefaultKeyColumnPresent(String propertyName) {
- final Collection collection = getCfg().getCollectionMapping( Atmosphere.class.getName() + "." + propertyName );
- final Iterator columnIterator = collection.getCollectionTable().getColumnIterator();
- boolean hasDefault = false;
- while ( columnIterator.hasNext() ) {
- Column column = (Column) columnIterator.next();
- if ( (propertyName + "_KEY").equals( column.getName() ) ) hasDefault = true;
- }
- assertTrue( "Could not find " + propertyName + "_KEY", hasDefault);
+ public void testJPA2DefaultIndexColumns() throws Exception {
+ isDefaultKeyColumnPresent( Drawer.class.getName(), "dresses", "_ORDER" );
}
- private void isNotDefaultKeyColumnPresent(String propertyName) {
- final Collection collection = getCfg().getCollectionMapping( Atmosphere.class.getName() + "." + propertyName );
+ private void isDefaultKeyColumnPresent(String collectionRole, String propertyName, String suffix) {
+ assertTrue( "Could not find " + propertyName + suffix,
+ isDefaultColumnPresent(collectionRole, propertyName, suffix) );
+ }
+
+ private boolean isDefaultColumnPresent(String collectionRole, String propertyName, String suffix) {
+ final Collection collection = getCfg().getCollectionMapping( collectionRole + "." + propertyName );
final Iterator columnIterator = collection.getCollectionTable().getColumnIterator();
boolean hasDefault = false;
while ( columnIterator.hasNext() ) {
Column column = (Column) columnIterator.next();
- if ( (propertyName + "_KEY").equals( column.getName() ) ) hasDefault = true;
+ if ( (propertyName + suffix).equals( column.getName() ) ) hasDefault = true;
}
- assertFalse( "Could not find " + propertyName + "_KEY", hasDefault);
+ return hasDefault;
}
+ private void isNotDefaultKeyColumnPresent(String collectionRole, String propertyName, String suffix) {
+ assertFalse( "Could not find " + propertyName + suffix,
+ isDefaultColumnPresent(collectionRole, propertyName, suffix) );
+ }
+
public void testFkList() throws Exception {
Wardrobe w = new Wardrobe();
Drawer d1 = new Drawer();
Modified: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/emops/Race.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/emops/Race.java 2009-07-22 13:45:15 UTC (rev 17191)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/emops/Race.java 2009-07-22 20:40:50 UTC (rev 17192)
@@ -1,24 +1,23 @@
//$Id$
package org.hibernate.ejb.test.emops;
-import java.util.List;
import java.util.ArrayList;
-import javax.persistence.Id;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Entity;
-import javax.persistence.OneToMany;
+import java.util.List;
import javax.persistence.CascadeType;
+import javax.persistence.Entity;
import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+import javax.persistence.OrderColumn;
-import org.hibernate.annotations.IndexColumn;
-
/**
* @author Emmanuel Bernard
*/
@Entity
public class Race {
@Id @GeneratedValue public Integer id;
- @IndexColumn( name="index_" ) @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
+ @OrderColumn( name="index_" ) @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@org.hibernate.annotations.Cascade( { org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
public List<Competitor> competitors = new ArrayList<Competitor>();
public String name;
15 years, 4 months
Hibernate SVN: r17191 - beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/messageinterpolation.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-07-22 09:45:15 -0400 (Wed, 22 Jul 2009)
New Revision: 17191
Modified:
beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/messageinterpolation/MessageInterpolationTest.java
Log:
message interpolation test
Modified: beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/messageinterpolation/MessageInterpolationTest.java
===================================================================
--- beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/messageinterpolation/MessageInterpolationTest.java 2009-07-22 13:20:08 UTC (rev 17190)
+++ beanvalidation/trunk/validation-tck/src/main/java/org/hibernate/jsr303/tck/tests/messageinterpolation/MessageInterpolationTest.java 2009-07-22 13:45:15 UTC (rev 17191)
@@ -18,6 +18,8 @@
package org.hibernate.jsr303.tck.tests.messageinterpolation;
import java.util.Locale;
+import java.util.Set;
+import javax.validation.ConstraintViolation;
import javax.validation.MessageInterpolator;
import javax.validation.Validator;
import javax.validation.constraints.Max;
@@ -39,6 +41,8 @@
import org.testng.annotations.Test;
import org.hibernate.jsr303.tck.util.TestUtil;
+import static org.hibernate.jsr303.tck.util.TestUtil.assertCorrectConstraintViolationMessages;
+import static org.hibernate.jsr303.tck.util.TestUtil.assertCorrectNumberOfViolations;
import static org.hibernate.jsr303.tck.util.TestUtil.getDefaultMessageInterpolator;
import static org.hibernate.jsr303.tck.util.TestUtil.getDefaultValidator;
@@ -91,6 +95,18 @@
assertEquals( actual, expected, "Wrong substitution" );
}
+ @Test
+ @SpecAssertion(section = "4.3.1", id = "d")
+ public void testMessagesCanBeOverrridenAtConstraintLevel() {
+ Validator validator = TestUtil.getDefaultValidator();
+ Set<ConstraintViolation<DummyEntity>> constraintViolations = validator.validateProperty(
+ new DummyEntity(), "snafu"
+ );
+ assertCorrectNumberOfViolations( constraintViolations, 1 );
+ assertCorrectConstraintViolationMessages( constraintViolations, "messages can also be overridden at constraint declaration." );
+ }
+
+
@Test(enabled = false)
@SpecAssertions({
@SpecAssertion(section = "4.3.1", id = "f"),
@@ -236,5 +252,8 @@
@Max(value = 10, message = "{replace.in.user.bundle1}")
String fubar;
+
+ @NotNull(message = "messages can also be overridden at constraint declaration.")
+ String snafu;
}
}
15 years, 4 months