Hibernate SVN: r15842 - in validator/trunk: validation-api/src/main/java/javax/validation and 2 other directories.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2009-01-31 01:36:02 -0500 (Sat, 31 Jan 2009)
New Revision: 15842
Added:
validator/trunk/validation-api/src/main/resources/validation-configuration-1.0.xsd
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConfigurationImpl.java
validator/trunk/validation-api/src/main/java/javax/validation/Configuration.java
validator/trunk/validation-api/src/main/java/javax/validation/spi/ConfigurationState.java
Log:
BVAL-102 add XML configuration support
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConfigurationImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConfigurationImpl.java 2009-01-30 19:37:29 UTC (rev 15841)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConfigurationImpl.java 2009-01-31 06:36:02 UTC (rev 15842)
@@ -19,6 +19,8 @@
import java.io.InputStream;
import java.util.List;
+import java.util.Set;
+import java.util.Map;
import javax.validation.Configuration;
import javax.validation.ConstraintValidatorFactory;
import javax.validation.MessageInterpolator;
@@ -52,6 +54,7 @@
private final ValidationProvider provider;
private final ValidationProviderResolver providerResolver;
private TraversableResolver traversableResolver;
+ private boolean ignoreXmlConfiguration;
public ConfigurationImpl(BootstrapState state) {
if ( state.getValidationProviderResolver() == null ) {
@@ -75,6 +78,10 @@
this.traversableResolver = defaultTraversableResolver;
}
+ public HibernateValidatorConfiguration ignoreXmlConfiguration() {
+ return null; //To change body of implemented methods use File | Settings | File Templates.
+ }
+
public ConfigurationImpl messageInterpolator(MessageInterpolator interpolator) {
this.messageInterpolator = interpolator;
return this;
@@ -90,6 +97,14 @@
return this;
}
+ public HibernateValidatorConfiguration addMapping(InputStream stream) {
+ return null; //To change body of implemented methods use File | Settings | File Templates.
+ }
+
+ public HibernateValidatorConfiguration addProperty(String name, String value) {
+ return null; //To change body of implemented methods use File | Settings | File Templates.
+ }
+
public ValidatorFactory buildValidatorFactory() {
if ( isSpecificProvider() ) {
return provider.buildValidatorFactory( this );
@@ -118,10 +133,18 @@
return provider != null;
}
+ public boolean isIgnoreXmlConfiguration() {
+ return ignoreXmlConfiguration;
+ }
+
public MessageInterpolator getMessageInterpolator() {
return messageInterpolator;
}
+ public Set<InputStream> getMappingStreams() {
+ throw new UnsupportedOperationException( "TODO" );
+ }
+
public ConstraintValidatorFactory getConstraintValidatorFactory() {
return constraintValidatorFactory;
}
@@ -130,15 +153,12 @@
return traversableResolver;
}
- public ConfigurationImpl customConfiguration(InputStream stream) {
- return null; //To change body of implemented methods use File | Settings | File Templates.
+ public Map<String, String> getProperties() {
+ throw new UnsupportedOperationException( "TODO" );
}
public MessageInterpolator getDefaultMessageInterpolator() {
return defaultMessageInterpolator;
}
- public InputStream getConfigurationStream() {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
}
Modified: validator/trunk/validation-api/src/main/java/javax/validation/Configuration.java
===================================================================
--- validator/trunk/validation-api/src/main/java/javax/validation/Configuration.java 2009-01-30 19:37:29 UTC (rev 15841)
+++ validator/trunk/validation-api/src/main/java/javax/validation/Configuration.java 2009-01-31 06:36:02 UTC (rev 15842)
@@ -32,6 +32,12 @@
* .buildValidatorFactory();
* </pre>
* <p/>
+ *
+ * By default, the configuration information is retrieved from
+ * META-INF/validation.xml
+ * It is possible to override the configuration retrieved from the XML file
+ * by using one or more of the Configuration methods.
+ *
* The ValidationProviderResolver is specified at Configuration time
* (see {@link javax.validation.spi.ValidationProvider}).
* If none is explicitely requested, the default ValidationProviderResolver is used.
@@ -48,7 +54,16 @@
* @author Emmanuel Bernard
*/
public interface Configuration<T extends Configuration<T>> {
+
/**
+ * Ignore data from the META-INF/validation.xml file if this
+ * method is called.
+ * This method is typically useful for containers that parse
+ * META-INF/validation.xml themselves and pass the information
+ * via the Configuration methods.
+ */
+ T ignoreXmlConfiguration();
+ /**
* Defines the message interpolator used. Has priority over the configuration
* based message interpolator.
*
@@ -79,19 +94,43 @@
T constraintValidatorFactory(ConstraintValidatorFactory constraintValidatorFactory);
/**
- * Configure the ValidatorFactory based on <code>stream</code>
- * If not specified, META-INF/validation.xml is used
+ * Add a stream describing constaint mapping in the Bean Validation
+ * XML format.
* <p/>
* The stream should be closed by the client API after the
- * ValidatorFactory has been returned
+ * ValidatorFactory has been built. The Bean Validation provider
+ * must not close the stream.
*
- * @param stream configuration stream.
+ * @param stream XML mapping stream.
*
* @return <code>this</code> following the chaining method pattern.
*/
- T customConfiguration(InputStream stream);
+ T addMapping(InputStream stream);
/**
+ * Add a provider specific property. This property is equivalent to
+ * XML Configuration properties.
+ * If the underlying provider does not know how to handle the property,
+ * it must silently ignore it.
+ *
+ * Note: Using this non type-safe method is generally not recommended.
+ *
+ * It is more appropriate to use, if available, the type-safe equivalent provided
+ * by a specific provider in its Configuration subclass.
+ * <code>ValidatorFactory factory = Validation.byProvider(ACMEConfiguration.class)
+ * .configure()
+ * .providerSpecificProperty(ACMEState.FAST)
+ * .buildValidatorFactory();
+ * </code>
+ * This method is typically used by containers parsing META-INF/validation.xml
+ * themselves and injecting the state to the Configuration object.
+ *
+ * If a property with a given name is defined both via this method and in the
+ * XML configuration, the value set programmatically has priority.
+ */
+ T addProperty(String name, String value);
+
+ /**
* Return an implementation of the MessageInterpolator interface following the
* default MessageInterpolator defined in the specification:
* - use the ValidationMessages resource bundle to load keys
Modified: validator/trunk/validation-api/src/main/java/javax/validation/spi/ConfigurationState.java
===================================================================
--- validator/trunk/validation-api/src/main/java/javax/validation/spi/ConfigurationState.java 2009-01-30 19:37:29 UTC (rev 15841)
+++ validator/trunk/validation-api/src/main/java/javax/validation/spi/ConfigurationState.java 2009-01-31 06:36:02 UTC (rev 15842)
@@ -18,6 +18,8 @@
package javax.validation.spi;
import java.io.InputStream;
+import java.util.Set;
+import java.util.Map;
import javax.validation.ConstraintValidatorFactory;
import javax.validation.MessageInterpolator;
import javax.validation.TraversableResolver;
@@ -25,42 +27,80 @@
/**
* Contract between a <code>Configuration</code> and a
* </code>ValidatorProvider</code> to create a <code>ValidatorFactory</code>.
- * The configuration artifacts provided to the
- * <code>Configuration</code> are passed along.
+ * The configuration artifacts defined in the XML configuration and provided to the
+ * <code>Configuration</code> are merged and passed along via ConfigurationState.
*
* @author Emmanuel Bernard
* @author Hardy Ferentschik
*/
public interface ConfigurationState {
+
/**
- * Message interpolator as defined by the client programmatically
- * or null if undefined.
+ * returns true if Configuration.ignoreXMLConfiguration() has been called
+ * In this case, the ValiatorFactory must ignore META-INF/validation.xml
+ * @return true if META-INF/validation.xml should be ignored
+ */
+ boolean isIgnoreXmlConfiguration();
+
+ /**
+ * Message interpolator as defined in the following decresing priority:
+ * - set via the Configuration programmatic API
+ * - defined in META-INF/validation.xml provided that ignoredXmlConfiguration
+ * is false. In this case the instance is created via its no-arg constructor.
+ * - null if undefined.
*
* @return message provider instance or null if not defined
*/
MessageInterpolator getMessageInterpolator();
/**
- * Returns the configuration stream defined by the client programmatically
- * or null if undefined.
+ * Returns a set of stream corresponding to:
+ * - mapping XML streams passed programmatically in Configuration
+ * - mapping XML stream located in the resources defined in
+ * META-INF/validation.xml (constraint-mapping element)
*
- * @return the configuration input stream or null
+ * Streams represented in the XML configuration and opened by the
+ * configuration implementation must be closed by the configuration
+ * implementation after the ValidatorFactory creation (or if an exception
+ * occurs).
+ *
+ * @return set of input stream
*/
- InputStream getConfigurationStream();
+ Set<InputStream> getMappingStreams();
/**
- * Defines the constraint validator implementation factory as defined by
- * the client programmatically or null if undefined
+ * ConstraintValidatorFactory implementation as defined in the following
+ * decreasing priority:
+ * - set via the Configuration programmatic API
+ * - defined in META-INF/validation.xml provided that ignoredXmlConfiguration
+ * is false. In this case the instance is created via its no-arg constructor.
+ * - null if undefined.
*
* @return factory instance or null if not defined
*/
ConstraintValidatorFactory getConstraintValidatorFactory();
/**
- * Traversable resolver as defined by the client programmatically
- * or null if undefined.
+ * TraversableResolver as defined in the following decresing priority:
+ * - set via the Configuration programmatic API
+ * - defined in META-INF/validation.xml provided that ignoredXmlConfiguration
+ * is false. In this case the instance is created via its no-arg constructor.
+ * - null if undefined.
*
* @return traversable provider instance or null if not defined
*/
TraversableResolver getTraversableResolver();
+
+ /**
+ * return non type-safe properties defined via:
+ * - Configuration.addProperty(String, String)
+ * - META-INF/validation.xml provided that ignoredXmlConfiguration
+ * is false.
+ *
+ * If a property is defined both programmatically and in XML,
+ * the value defined programmatically has priority
+ *
+ * @return Map whose key is the property key and the value the property value
+ */
+ Map<String, String> getProperties();
}
Added: validator/trunk/validation-api/src/main/resources/validation-configuration-1.0.xsd
===================================================================
--- validator/trunk/validation-api/src/main/resources/validation-configuration-1.0.xsd (rev 0)
+++ validator/trunk/validation-api/src/main/resources/validation-configuration-1.0.xsd 2009-01-31 06:36:02 UTC (rev 15842)
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xs:schema attributeFormDefault="unqualified"
+ elementFormDefault="qualified"
+ targetNamespace="http://jboss.org/xml/ns/javax/validation/configuration"
+ xmlns:xs="http://www.w3.org/2001/XMLSchema"
+ version="1.0">
+ <xs:element name="validation-config" type="validation-configType"/>
+ <xs:complexType name="validation-configType">
+ <xs:sequence>
+ <xs:element type="xs:string" name="default-provider" minOccurs="0"/>
+ <xs:element type="xs:string" name="message-interpolator" minOccurs="0"/>
+ <xs:element type="xs:string" name="traversable-resolver" minOccurs="0"/>
+ <xs:element type="xs:string" name="constraint-validator-factory" minOccurs="0"/>
+ <xs:element type="xs:string" name="constraint-mapping" maxOccurs="unbounded" minOccurs="0"/>
+ <xs:element type="propertyType" name="property" maxOccurs="unbounded" minOccurs="0"/>
+ </xs:sequence>
+ </xs:complexType>
+ <xs:complexType name="propertyType">
+ <xs:attribute name="name" use="required" type="xs:string"/>
+ </xs:complexType>
+</xs:schema>
\ No newline at end of file
15 years, 11 months
Hibernate SVN: r15841 - validator/trunk/validation-api/src/main/resources.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2009-01-30 14:37:29 -0500 (Fri, 30 Jan 2009)
New Revision: 15841
Added:
validator/trunk/validation-api/src/main/resources/validation-mapping-1.0.xsd
Log:
BVAL-100 mapping schema
Added: validator/trunk/validation-api/src/main/resources/validation-mapping-1.0.xsd
===================================================================
--- validator/trunk/validation-api/src/main/resources/validation-mapping-1.0.xsd (rev 0)
+++ validator/trunk/validation-api/src/main/resources/validation-mapping-1.0.xsd 2009-01-30 19:37:29 UTC (rev 15841)
@@ -0,0 +1,144 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xs:schema attributeFormDefault="unqualified"
+ elementFormDefault="qualified"
+ targetNamespace="http://jboss.org/xml/ns/javax/validation/mapping"
+ xmlns:xs="http://www.w3.org/2001/XMLSchema"
+ version="1.0">
+ <xs:element name="constraint-mappings"
+ type="map:constraint-mappingsType"
+ xmlns:map="http://jboss.org/xml/ns/javax/validation/mapping"/>
+
+ <xs:complexType name="groupsType">
+ <xs:sequence>
+ <xs:element type="xs:string" name="value" maxOccurs="unbounded" minOccurs="0"/>
+ </xs:sequence>
+ </xs:complexType>
+ <xs:complexType name="groupSequenceType">
+ <xs:sequence>
+ <xs:element type="xs:string" name="value" maxOccurs="unbounded" minOccurs="0"/>
+ </xs:sequence>
+ </xs:complexType>
+ <xs:complexType name="constraint-mappingsType">
+ <xs:sequence>
+ <xs:element type="xs:string" name="default-package" minOccurs="0"/>
+ <xs:element type="map:beanType"
+ name="bean"
+ maxOccurs="unbounded"
+ minOccurs="0"
+ xmlns:map="http://jboss.org/xml/ns/javax/validation/mapping"/>
+ <xs:element type="map:constraint-definitionType"
+ name="constraint-definition"
+ maxOccurs="unbounded"
+ minOccurs="0"
+ xmlns:map="http://jboss.org/xml/ns/javax/validation/mapping"/>
+ </xs:sequence>
+ </xs:complexType>
+ <xs:complexType name="validated-byType">
+ <xs:sequence>
+ <xs:element type="xs:string" name="value" maxOccurs="unbounded" minOccurs="0"/>
+ </xs:sequence>
+ <xs:attribute type="xs:boolean" name="include-existing-validators" use="optional"/>
+ </xs:complexType>
+ <xs:complexType name="constraintType">
+ <xs:sequence>
+ <xs:element type="xs:string" name="message" minOccurs="0"/>
+ <xs:element type="map:groupsType"
+ name="groups"
+ minOccurs="0"
+ xmlns:map="http://jboss.org/xml/ns/javax/validation/mapping"/>
+ <xs:element type="map:elementType"
+ name="element"
+ maxOccurs="unbounded"
+ minOccurs="0"
+ xmlns:map="http://jboss.org/xml/ns/javax/validation/mapping"/>
+ </xs:sequence>
+ <xs:attribute type="xs:string" name="annotation" use="required"/>
+ </xs:complexType>
+ <xs:complexType name="elementType" mixed="true">
+ <xs:sequence>
+ <xs:element type="xs:string" name="value" maxOccurs="unbounded" minOccurs="0"/>
+ <xs:element type="map:annotationType"
+ name="annotation"
+ maxOccurs="unbounded"
+ minOccurs="0"
+ xmlns:map="http://jboss.org/xml/ns/javax/validation/mapping"/>
+ </xs:sequence>
+ <xs:attribute type="xs:string" name="name" use="required"/>
+ </xs:complexType>
+ <xs:complexType name="classType">
+ <xs:sequence>
+ <xs:element type="groupSequenceType" name="group-sequence" minOccurs="0"/>
+ <xs:element type="xs:simpleType" name="stop-constraint-inheritance" fixed="" minOccurs="0"/>
+ <xs:element type="map:constraintType"
+ name="constraint"
+ maxOccurs="unbounded"
+ minOccurs="0"
+ xmlns:map="http://jboss.org/xml/ns/javax/validation/mapping"/>
+ </xs:sequence>
+ <xs:attribute type="xs:boolean" name="ignore-annotations" use="optional"/>
+ </xs:complexType>
+ <xs:complexType name="beanType">
+ <xs:sequence>
+ <xs:element type="map:classType"
+ name="class"
+ minOccurs="0"
+ xmlns:map="http://jboss.org/xml/ns/javax/validation/mapping">
+ </xs:element>
+ <xs:element type="map:fieldType"
+ name="field"
+ minOccurs="0"
+ maxOccurs="unbounded"
+ xmlns:map="http://jboss.org/xml/ns/javax/validation/mapping"/>
+ <xs:element type="map:getterType"
+ name="getter"
+ minOccurs="0"
+ maxOccurs="unbounded"
+ xmlns:map="http://jboss.org/xml/ns/javax/validation/mapping"/>
+ </xs:sequence>
+ <xs:attribute type="xs:string" name="class" use="required"/>
+ <xs:attribute type="xs:boolean" name="ignore-annotations" use="optional"/>
+ </xs:complexType>
+ <xs:complexType name="annotationType">
+ <xs:sequence>
+ <xs:element type="map:elementType"
+ name="element"
+ maxOccurs="unbounded"
+ minOccurs="0"
+ xmlns:map="http://jboss.org/xml/ns/javax/validation/mapping"/>
+ </xs:sequence>
+ </xs:complexType>
+ <xs:complexType name="getterType">
+ <xs:sequence>
+ <xs:element type="xs:string" name="valid" minOccurs="0" fixed=""/>
+ <xs:element type="xs:string" name="stop-constraint-inheritance" minOccurs="0" fixed=""/>
+ <xs:element type="map:constraintType"
+ name="constraint"
+ minOccurs="0"
+ maxOccurs="unbounded"
+ xmlns:map="http://jboss.org/xml/ns/javax/validation/mapping"/>
+ </xs:sequence>
+ <xs:attribute type="xs:string" name="name" use="required"/>
+ <xs:attribute type="xs:boolean" name="ignore-annotations" use="optional"/>
+ </xs:complexType>
+ <xs:complexType name="constraint-definitionType">
+ <xs:sequence>
+ <xs:element type="map:validated-byType"
+ name="validated-by"
+ xmlns:map="http://jboss.org/xml/ns/javax/validation/mapping"/>
+ </xs:sequence>
+ <xs:attribute type="xs:string" name="annotation" use="required"/>
+ </xs:complexType>
+ <xs:complexType name="fieldType">
+ <xs:sequence>
+ <xs:element type="xs:string" name="valid" minOccurs="0" fixed=""/>
+ <xs:element type="xs:string" name="stop-constraint-inheritance" minOccurs="0" fixed=""/>
+ <xs:element type="map:constraintType"
+ name="constraint"
+ minOccurs="0"
+ maxOccurs="unbounded"
+ xmlns:map="http://jboss.org/xml/ns/javax/validation/mapping"/>
+ </xs:sequence>
+ <xs:attribute type="xs:string" name="name" use="required"/>
+ <xs:attribute type="xs:boolean" name="ignore-annotations" use="optional"/>
+ </xs:complexType>
+</xs:schema>
\ No newline at end of file
15 years, 11 months
Hibernate SVN: r15840 - validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-01-30 11:27:14 -0500 (Fri, 30 Jan 2009)
New Revision: 15840
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java
Log:
renamed a method
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-01-30 15:52:21 UTC (rev 15839)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java 2009-01-30 16:27:14 UTC (rev 15840)
@@ -1,4 +1,4 @@
-// $Id$
+// $Id: ValidatorImpl.java 15837 2009-01-30 15:49:57Z hardy.ferentschik $
/*
* JBoss, Home of Professional Open Source
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
@@ -66,7 +66,7 @@
private final ConstraintValidatorFactory constraintValidatorFactory;
private final MessageInterpolator messageInterpolator;
- public ValidatorImpl(ConstraintValidatorFactory constraintValidatorFactory, MessageInterpolator messageInterpolator) {
+ public ValidatorImpl(ConstraintValidatorFactory constraintValidatorFactory, MessageInterpolator messageInterpolator) {
this.constraintValidatorFactory = constraintValidatorFactory;
this.messageInterpolator = messageInterpolator;
}
@@ -79,7 +79,9 @@
throw new IllegalArgumentException( "Validation of a null object" );
}
- ValidationContext<T> context = new ValidationContext<T>( object, messageInterpolator, constraintValidatorFactory );
+ ValidationContext<T> context = new ValidationContext<T>(
+ object, messageInterpolator, constraintValidatorFactory
+ );
List<ConstraintViolationImpl<T>> list = validateInContext( context, Arrays.asList( groups ) );
return new HashSet<ConstraintViolation<T>>( list );
}
@@ -152,6 +154,22 @@
validationContext.markProcessedForCurrentGroup();
}
+ private <T> void validateCascadedConstraints(ValidationContext<T> context) {
+ List<Member> cascadedMembers = getBeanMetaData( context.peekValidatedObjectType() )
+ .getCascadedMembers();
+ for ( Member member : cascadedMembers ) {
+ Type type = ReflectionHelper.typeOf( member );
+ context.pushProperty( ReflectionHelper.getPropertyName( member ) );
+ Object value = ReflectionHelper.getValue( member, context.peekValidatedObject() );
+ if ( value == null ) {
+ continue;
+ }
+ Iterator<?> iter = createIteratorForCascadedValue( context, type, value );
+ validateCascadedConstraint( context, iter );
+ context.popProperty();
+ }
+ }
+
/**
* Called when processing cascaded constraints. This methods inspects the type of the cascaded constraints and in case
* of a list or array creates an iterator in order to validate each element.
@@ -159,12 +177,9 @@
* @param context the validation context.
* @param type the type of the cascaded field or property.
* @param value the actual value.
+ * @return An iterator over the value of a cascaded property.
*/
- private <T> void validateCascadedConstraint(ValidationContext<T> context, Type type, Object value) {
- if ( value == null ) {
- return;
- }
-
+ private <T> Iterator<?> createIteratorForCascadedValue(ValidationContext<T> context, Type type, Object value) {
Iterator<?> iter;
if ( ReflectionHelper.isCollection( type ) ) {
boolean isIterable = value instanceof Iterable;
@@ -185,22 +200,9 @@
list.add( value );
iter = list.iterator();
}
+ return iter;
+ }
- validateCascadedConstraint( context, iter );
- }
-
- private <T> void validateCascadedConstraints(ValidationContext<T> context) {
- List<Member> cascadedMembers = getBeanMetaData( context.peekValidatedObjectType() )
- .getCascadedMembers();
- for ( Member member : cascadedMembers ) {
- Type type = ReflectionHelper.typeOf( member );
- context.pushProperty( ReflectionHelper.getPropertyName( member ) );
- Object value = ReflectionHelper.getValue( member, context.peekValidatedObject() );
- validateCascadedConstraint( context, type, value );
- context.popProperty();
- }
- }
-
private <T> void validateCascadedConstraint(ValidationContext<T> context, Iterator<?> iter) {
Object actualValue;
String propertyIndex;
@@ -271,7 +273,9 @@
continue;
}
- ValidationContext<T> context = new ValidationContext<T>( object, messageInterpolator, constraintValidatorFactory );
+ ValidationContext<T> context = new ValidationContext<T>(
+ object, messageInterpolator, constraintValidatorFactory
+ );
metaConstraint.validateConstraint( object.getClass(), context );
failingConstraintViolations.addAll( context.getFailingConstraints() );
}
@@ -322,7 +326,9 @@
continue;
}
- ValidationContext<T> context = new ValidationContext<T>( ( T ) value, messageInterpolator, constraintValidatorFactory );
+ ValidationContext<T> context = new ValidationContext<T>(
+ ( T ) value, messageInterpolator, constraintValidatorFactory
+ );
context.pushProperty( propertyIter.getOriginalProperty() );
metaConstraint.validateConstraint( beanType, value, context );
failingConstraintViolations.addAll( context.getFailingConstraints() );
15 years, 11 months
Hibernate SVN: r15838 - in validator/trunk/hibernate-validator/src: main/java/org/hibernate/validation/util and 3 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-01-30 10:50:46 -0500 (Fri, 30 Jan 2009)
New Revision: 15838
Added:
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolatorTest.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/ValidatorTypeTest.java
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/constraints/SizeConstraintValidator.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/ReflectionHelper.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/annotationfactory/AnnotationDescriptor.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/annotationfactory/AnnotationFactory.java
Log:
- Refactored package structure to untangle inter packages references
- Refactored access to MessageResolver and ConstraintValidatorFactory
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/constraints/SizeConstraintValidator.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/constraints/SizeConstraintValidator.java 2009-01-30 15:49:57 UTC (rev 15837)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/constraints/SizeConstraintValidator.java 2009-01-30 15:50:46 UTC (rev 15838)
@@ -17,8 +17,8 @@
*/
package org.hibernate.validation.constraints;
+import java.lang.reflect.Array;
import java.util.Collection;
-import java.lang.reflect.Array;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.constraints.Size;
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/ReflectionHelper.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/ReflectionHelper.java 2009-01-30 15:49:57 UTC (rev 15837)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/ReflectionHelper.java 2009-01-30 15:50:46 UTC (rev 15838)
@@ -38,8 +38,8 @@
import java.util.List;
import java.util.Map;
import java.util.Properties;
+import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
-import javax.validation.Constraint;
import javax.validation.ValidationException;
import org.slf4j.Logger;
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/annotationfactory/AnnotationDescriptor.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/annotationfactory/AnnotationDescriptor.java 2009-01-30 15:49:57 UTC (rev 15837)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/annotationfactory/AnnotationDescriptor.java 2009-01-30 15:50:46 UTC (rev 15838)
@@ -18,8 +18,8 @@
package org.hibernate.validation.util.annotationfactory;
import java.lang.annotation.Annotation;
+import java.util.HashMap;
import java.util.Map;
-import java.util.HashMap;
/**
* Encapsulates the data you need to create an annotation. In
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/annotationfactory/AnnotationFactory.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/annotationfactory/AnnotationFactory.java 2009-01-30 15:49:57 UTC (rev 15837)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/annotationfactory/AnnotationFactory.java 2009-01-30 15:50:46 UTC (rev 15838)
@@ -18,10 +18,10 @@
package org.hibernate.validation.util.annotationfactory;
import java.lang.annotation.Annotation;
-import java.lang.reflect.Proxy;
+import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Constructor;
+import java.lang.reflect.Proxy;
/**
Copied: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolatorTest.java (from rev 15834, validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/impl/ResourceBundleMessageInterpolatorTest.java)
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolatorTest.java (rev 0)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolatorTest.java 2009-01-30 15:50:46 UTC (rev 15838)
@@ -0,0 +1,148 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.validation.engine;
+
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.ResourceBundle;
+import javax.validation.constraints.NotNull;
+import javax.validation.constraints.Size;
+
+import static org.junit.Assert.assertEquals;
+import org.junit.Before;
+import org.junit.Test;
+
+import org.hibernate.validation.util.annotationfactory.AnnotationDescriptor;
+import org.hibernate.validation.util.annotationfactory.AnnotationFactory;
+import org.hibernate.validation.engine.ResourceBundleMessageInterpolator;
+import org.hibernate.validation.engine.ConstraintDescriptorImpl;
+
+/**
+ * Tests for message resolution.
+ *
+ * @author Hardy Ferentschik
+ */
+public class ResourceBundleMessageInterpolatorTest {
+
+ private ResourceBundleMessageInterpolator interpolator;
+ private NotNull notNull;
+ private Size size;
+
+ @Before
+ public void setUp() {
+ interpolator = new ResourceBundleMessageInterpolator( new TestResources() );
+
+ AnnotationDescriptor descriptor = new AnnotationDescriptor( NotNull.class );
+ notNull = AnnotationFactory.create( descriptor );
+
+ descriptor = new AnnotationDescriptor( Size.class );
+ size = AnnotationFactory.create( descriptor );
+ }
+
+ @Test
+ public void testSuccessfulInterpolation() {
+ ConstraintDescriptorImpl desciptor = new ConstraintDescriptorImpl( notNull, new Class<?>[] { } );
+
+ String expected = "replacement worked";
+ String actual = interpolator.interpolate( "{foo}", desciptor, null );
+ assertEquals( "Wrong substitution", expected, actual );
+
+ expected = "replacement worked replacement worked";
+ actual = interpolator.interpolate( "{foo} {foo}", desciptor, null );
+ assertEquals( "Wrong substitution", expected, actual );
+
+ expected = "This replacement worked just fine";
+ actual = interpolator.interpolate( "This {foo} just fine", desciptor, null );
+ assertEquals( "Wrong substitution", expected, actual );
+
+ expected = "{} { replacement worked }";
+ actual = interpolator.interpolate( "{} { {foo} }", desciptor, null );
+ assertEquals( "Wrong substitution", expected, actual );
+ }
+
+ @Test
+ public void testUnSuccessfulInterpolation() {
+ ConstraintDescriptorImpl desciptor = new ConstraintDescriptorImpl( notNull, new Class<?>[] { } );
+ String expected = "foo"; // missing {}
+ String actual = interpolator.interpolate( "foo", desciptor, null );
+ assertEquals( "Wrong substitution", expected, actual );
+
+ expected = "#{foo {}";
+ actual = interpolator.interpolate( "#{foo {}", desciptor, null );
+ assertEquals( "Wrong substitution", expected, actual );
+ }
+
+ @Test
+ public void testUnkownTokenInterpolation() {
+ ConstraintDescriptorImpl desciptor = new ConstraintDescriptorImpl( notNull, new Class<?>[] { } );
+ String expected = "{bar}"; // unkown token {}
+ String actual = interpolator.interpolate( "{bar}", desciptor, null );
+ assertEquals( "Wrong substitution", expected, actual );
+ }
+
+ @Test
+ public void testDefaultInterpolation() {
+ ConstraintDescriptorImpl desciptor = new ConstraintDescriptorImpl( notNull, new Class<?>[] { } );
+ String expected = "may not be null";
+ String actual = interpolator.interpolate( notNull.message(), desciptor, null );
+ assertEquals( "Wrong substitution", expected, actual );
+
+ desciptor = new ConstraintDescriptorImpl( size, new Class<?>[] { } );
+ expected = "size must be between -2147483648 and 2147483647"; // unkown token {}
+ actual = interpolator.interpolate( size.message(), desciptor, null );
+ assertEquals( "Wrong substitution", expected, actual );
+ }
+
+
+ class TestResources extends ResourceBundle implements Enumeration<String> {
+ private Map<String, String> testResources;
+ Iterator<String> iter;
+
+ public TestResources() {
+ testResources = new HashMap<String, String>();
+ // add some test messages
+ testResources.put( "foo", "replacement worked" );
+
+ iter = testResources.keySet().iterator();
+ }
+
+ public Object handleGetObject(String key) {
+ return testResources.get( key );
+ }
+
+ public Enumeration<String> getKeys() {
+ return this;
+ }
+
+ public boolean hasMoreElements() {
+ return iter.hasNext();
+ }
+
+ public String nextElement() {
+ if ( hasMoreElements() ) {
+ return iter.next();
+ }
+ else {
+ throw new NoSuchElementException();
+ }
+ }
+ }
+}
Property changes on: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolatorTest.java
___________________________________________________________________
Name: svn:keywords
+ Id
Copied: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/ValidatorTypeTest.java (from rev 15834, validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/impl/ValidatorTypeTest.java)
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/ValidatorTypeTest.java (rev 0)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/ValidatorTypeTest.java 2009-01-30 15:50:46 UTC (rev 15838)
@@ -0,0 +1,75 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.validation.util;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Type;
+import java.util.Map;
+import java.util.Set;
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+import javax.validation.constraints.NotNull;
+
+import static org.junit.Assert.assertEquals;
+import org.junit.Test;
+
+import org.hibernate.validation.constraints.composition.FrenchZipcodeConstraintValidator;
+import org.hibernate.validation.util.ValidatorTypeHelper;
+
+/**
+ * Tests for message resolution.
+ *
+ * @author Emmanuel Bernard
+ */
+public class ValidatorTypeTest {
+
+ @Test
+ public void testTypeDiscovery() {
+ Map<Class<?>, Class<? extends ConstraintValidator<? extends Annotation, ?>>> validatorsTypes = ValidatorTypeHelper
+ .getValidatorsTypes( new Class[] { FrenchZipcodeConstraintValidator.class } );
+ assertEquals( FrenchZipcodeConstraintValidator.class, validatorsTypes.get( String.class ) );
+
+ Type type = ValidatorTypeHelper
+ .extractTypeLoose( TestValidator.class );
+
+
+ Type type2 = ValidatorTypeHelper
+ .extractTypeLoose( TestValidator2.class );
+ assertEquals( type, type2 );
+
+ }
+
+ public static class TestValidator implements ConstraintValidator<NotNull, Set<String>> {
+ public void initialize(NotNull constraintAnnotation) {
+ //To change body of implemented methods use File | Settings | File Templates.
+ }
+
+ public boolean isValid(Set<String> object, ConstraintValidatorContext constraintValidatorContext) {
+ return false; //To change body of implemented methods use File | Settings | File Templates.
+ }
+}
+
+ public static class TestValidator2 implements ConstraintValidator<NotNull, Set<String>> {
+ public void initialize(NotNull constraintAnnotation) {
+ }
+
+ public boolean isValid(Set<String> object, ConstraintValidatorContext constraintValidatorContext) {
+ return true;
+ }
+ }
+}
\ No newline at end of file
Property changes on: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/ValidatorTypeTest.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:mergeinfo
+
15 years, 11 months
Hibernate SVN: r15837 - in validator/trunk: hibernate-validator/src/main/java/org/hibernate/validation/engine and 9 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-01-30 10:49:57 -0500 (Fri, 30 Jan 2009)
New Revision: 15837
Added:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanDescriptorImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConfigurationImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintDescriptorImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintValidatorFactoryImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintViolationImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/DefaultTraversableResolver.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ElementDescriptorImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/HibernateValidationProvider.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/HibernateValidatorConfiguration.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolator.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorContextImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorFactoryImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/ValidatorTypeHelper.java
Removed:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/HibernateValidatorConfiguration.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/ValidatorConstants.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorFactoryImplementor.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/BeanDescriptorImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ConfigurationImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ConstraintDescriptorImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ConstraintValidatorFactoryImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ConstraintViolationImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/DefaultTraversableResolver.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ElementDescriptorImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/HibernateValidationProvider.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ResourceBundleMessageInterpolator.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ValidatorContextImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ValidatorFactoryImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ValidatorTypeHelper.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/impl/
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaData.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintValidatorContextImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidationContext.java
validator/trunk/hibernate-validator/src/main/resources/META-INF/services/javax.validation.spi.ValidationProvider
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/bootstrap/ValidationTest.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/TestUtil.java
validator/trunk/hibernate-validator/src/test/resources/log4j.properties
validator/trunk/validation-api/src/main/java/javax/validation/Validator.java
validator/trunk/validation-api/src/main/java/javax/validation/ValidatorFactory.java
Log:
- Refactored package structure to untangle inter packages references
- Refactored access to MessageResolver and ConstraintValidatorFactory
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/HibernateValidatorConfiguration.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/HibernateValidatorConfiguration.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/HibernateValidatorConfiguration.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -1,12 +0,0 @@
-package org.hibernate.validation;
-
-import javax.validation.Configuration;
-
-/**
- * Uniquely identify Hibernate Validator in the Bean Validation bootstrap strategy
- * Also contains Hibernate Validator specific configurations
- *
- * @author Emmanuel Bernard
- */
-public interface HibernateValidatorConfiguration extends Configuration<HibernateValidatorConfiguration> {
-}
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/ValidatorConstants.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/ValidatorConstants.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/ValidatorConstants.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -1,33 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.validation;
-
-/**
- * @author Hardy Ferentschik
- * TODO remove
- */
-public class ValidatorConstants {
-
- private ValidatorConstants() {
- }
-
- /**
- * The default group/sequence name used when no group parameter is passed to validate().
- */
- //public static final String DEFAULT_GROUP_NAME = "default";
-}
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanDescriptorImpl.java (from rev 15834, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/BeanDescriptorImpl.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanDescriptorImpl.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanDescriptorImpl.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -0,0 +1,33 @@
+package org.hibernate.validation.engine;
+
+import java.util.Collections;
+import java.util.Set;
+import javax.validation.BeanDescriptor;
+import javax.validation.PropertyDescriptor;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class BeanDescriptorImpl<T> extends ElementDescriptorImpl implements BeanDescriptor {
+ private final BeanMetaData<T> metadataBean;
+
+ public BeanDescriptorImpl(Class<T> returnType, BeanMetaData<T> metadataBean) {
+ super(returnType, false, "");
+ this.metadataBean = metadataBean;
+ }
+
+ /**
+ * @todo add child validation
+ */
+ public boolean isBeanConstrained() {
+ return metadataBean.geMetaConstraintList().size() > 0;
+ }
+
+ public PropertyDescriptor getConstraintsForProperty(String propertyName) {
+ return metadataBean.getPropertyDescriptors().get( propertyName );
+ }
+
+ public Set<String> getConstrainedProperties() {
+ return Collections.unmodifiableSet( metadataBean.getPropertyDescriptors().keySet() );
+ }
+}
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanDescriptorImpl.java
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaData.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaData.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaData.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -18,12 +18,12 @@
package org.hibernate.validation.engine;
import java.lang.reflect.Field;
+import java.lang.reflect.Member;
import java.lang.reflect.Method;
-import java.lang.reflect.Member;
import java.util.List;
import java.util.Map;
+import javax.validation.BeanDescriptor;
import javax.validation.ElementDescriptor;
-import javax.validation.BeanDescriptor;
import javax.validation.PropertyDescriptor;
/**
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataImpl.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataImpl.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -32,14 +32,9 @@
import javax.validation.PropertyDescriptor;
import javax.validation.Valid;
import javax.validation.ValidationException;
-import javax.validation.MessageInterpolator;
-import javax.validation.ConstraintValidatorFactory;
import org.slf4j.Logger;
-import org.hibernate.validation.impl.BeanDescriptorImpl;
-import org.hibernate.validation.impl.ConstraintDescriptorImpl;
-import org.hibernate.validation.impl.ElementDescriptorImpl;
import org.hibernate.validation.util.LoggerFactory;
import org.hibernate.validation.util.ReflectionHelper;
@@ -55,10 +50,6 @@
private static final Logger log = LoggerFactory.make();
- private final MessageInterpolator messageInterpolator;
-
- private final ConstraintValidatorFactory constraintValidatorFactory;
-
/**
* The root bean class for this validator.
*/
@@ -95,10 +86,8 @@
*/
private Map<Class<?>, List<Class<?>>> groupSequences = new HashMap<Class<?>, List<Class<?>>>();
- public BeanMetaDataImpl(Class<T> beanClass, MessageInterpolator messageInterpolator, ConstraintValidatorFactory constraintValidatorFactory) {
+ public BeanMetaDataImpl(Class<T> beanClass) {
this.beanClass = beanClass;
- this.messageInterpolator = messageInterpolator;
- this.constraintValidatorFactory = constraintValidatorFactory;
createMetaData();
}
@@ -197,9 +186,7 @@
List<ConstraintDescriptorImpl> fieldMetadata = findFieldLevelConstraints( field );
for ( ConstraintDescriptorImpl constraintDescription : fieldMetadata ) {
ReflectionHelper.setAccessibility( field );
- MetaConstraint metaConstraint = new MetaConstraint( field, constraintDescription,
- messageInterpolator, constraintValidatorFactory
- );
+ MetaConstraint metaConstraint = new MetaConstraint( field, constraintDescription );
metaConstraintList.add( metaConstraint );
}
if ( field.isAnnotationPresent( Valid.class ) ) {
@@ -214,9 +201,7 @@
List<ConstraintDescriptorImpl> methodMetadata = findMethodLevelConstraints( method );
for ( ConstraintDescriptorImpl constraintDescription : methodMetadata ) {
ReflectionHelper.setAccessibility( method );
- MetaConstraint metaConstraint = new MetaConstraint( method, constraintDescription,
- messageInterpolator, constraintValidatorFactory
- );
+ MetaConstraint metaConstraint = new MetaConstraint( method, constraintDescription );
metaConstraintList.add( metaConstraint );
}
if ( method.isAnnotationPresent( Valid.class ) ) {
@@ -229,9 +214,7 @@
private void initClassConstraints(Class clazz) {
List<ConstraintDescriptorImpl> classMetadata = findClassLevelConstraints( clazz );
for ( ConstraintDescriptorImpl constraintDescription : classMetadata ) {
- MetaConstraint metaConstraint = new MetaConstraint( clazz, constraintDescription,
- messageInterpolator, constraintValidatorFactory
- );
+ MetaConstraint metaConstraint = new MetaConstraint( clazz, constraintDescription );
metaConstraintList.add( metaConstraint );
}
}
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConfigurationImpl.java (from rev 15834, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ConfigurationImpl.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConfigurationImpl.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConfigurationImpl.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -0,0 +1,144 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.validation.engine;
+
+import java.io.InputStream;
+import java.util.List;
+import javax.validation.Configuration;
+import javax.validation.ConstraintValidatorFactory;
+import javax.validation.MessageInterpolator;
+import javax.validation.TraversableResolver;
+import javax.validation.ValidationException;
+import javax.validation.ValidationProviderResolver;
+import javax.validation.ValidatorFactory;
+import javax.validation.bootstrap.DefaultValidationProviderResolver;
+import javax.validation.spi.BootstrapState;
+import javax.validation.spi.ConfigurationState;
+import javax.validation.spi.ValidationProvider;
+
+import org.hibernate.validation.Version;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class ConfigurationImpl implements HibernateValidatorConfiguration, ConfigurationState {
+
+ static {
+ Version.touch();
+ }
+
+ //FIXME not sure why it is like that. We should cache these instances somehow. Static?
+ private final MessageInterpolator defaultMessageInterpolator = new ResourceBundleMessageInterpolator();
+ private final TraversableResolver defaultTraversableResolver = new DefaultTraversableResolver();
+
+ private MessageInterpolator messageInterpolator;
+ private ConstraintValidatorFactory constraintValidatorFactory = new ConstraintValidatorFactoryImpl();
+ private String configurationFile = "META-INF/validation.xml";
+ private final ValidationProvider provider;
+ private final ValidationProviderResolver providerResolver;
+ private TraversableResolver traversableResolver;
+
+ public ConfigurationImpl(BootstrapState state) {
+ if ( state.getValidationProviderResolver() == null ) {
+ this.providerResolver = new DefaultValidationProviderResolver();
+ }
+ else {
+ this.providerResolver = state.getValidationProviderResolver();
+ }
+ this.provider = null;
+ this.messageInterpolator = defaultMessageInterpolator;
+ this.traversableResolver = defaultTraversableResolver;
+ }
+
+ public ConfigurationImpl(ValidationProvider provider) {
+ if ( provider == null ) {
+ throw new ValidationException( "Assertion error: inconsistent ConfigurationImpl construction" );
+ }
+ this.provider = provider;
+ this.providerResolver = null;
+ this.messageInterpolator = defaultMessageInterpolator;
+ this.traversableResolver = defaultTraversableResolver;
+ }
+
+ public ConfigurationImpl messageInterpolator(MessageInterpolator interpolator) {
+ this.messageInterpolator = interpolator;
+ return this;
+ }
+
+ public ConfigurationImpl traversableResolver(TraversableResolver resolver) {
+ this.traversableResolver = resolver;
+ return this;
+ }
+
+ public ConfigurationImpl constraintValidatorFactory(ConstraintValidatorFactory constraintValidatorFactory) {
+ this.constraintValidatorFactory = constraintValidatorFactory;
+ return this;
+ }
+
+ public ValidatorFactory buildValidatorFactory() {
+ if ( isSpecificProvider() ) {
+ return provider.buildValidatorFactory( this );
+ }
+ else {
+ //read provider name from configuration
+ Class<? extends Configuration<?>> providerClass = null;
+
+ if ( providerClass != null ) {
+ for ( ValidationProvider provider : providerResolver.getValidationProviders() ) {
+ if ( provider.isSuitable( providerClass ) ) {
+ return provider.buildValidatorFactory( this );
+ }
+ }
+ throw new ValidationException( "Unable to find provider: " + providerClass );
+ }
+ else {
+ List<ValidationProvider> providers = providerResolver.getValidationProviders();
+ assert providers.size() != 0; //I run therefore I am
+ return providers.get( 0 ).buildValidatorFactory( this );
+ }
+ }
+ }
+
+ private boolean isSpecificProvider() {
+ return provider != null;
+ }
+
+ public MessageInterpolator getMessageInterpolator() {
+ return messageInterpolator;
+ }
+
+ public ConstraintValidatorFactory getConstraintValidatorFactory() {
+ return constraintValidatorFactory;
+ }
+
+ public TraversableResolver getTraversableResolver() {
+ return traversableResolver;
+ }
+
+ public ConfigurationImpl customConfiguration(InputStream stream) {
+ return null; //To change body of implemented methods use File | Settings | File Templates.
+ }
+
+ public MessageInterpolator getDefaultMessageInterpolator() {
+ return defaultMessageInterpolator;
+ }
+
+ public InputStream getConfigurationStream() {
+ return null; //To change body of implemented methods use File | Settings | File Templates.
+ }
+}
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConfigurationImpl.java
___________________________________________________________________
Name: svn:executable
+ *
Name: svn:keywords
+ Id
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintDescriptorImpl.java (from rev 15834, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ConstraintDescriptorImpl.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintDescriptorImpl.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintDescriptorImpl.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -0,0 +1,298 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.validation.engine;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.validation.Constraint;
+import javax.validation.ConstraintDescriptor;
+import javax.validation.ConstraintValidator;
+import javax.validation.OverridesParameter;
+import javax.validation.OverridesParameters;
+import javax.validation.ReportAsViolationFromCompositeConstraint;
+import javax.validation.ValidationException;
+import javax.validation.groups.Default;
+
+import org.slf4j.Logger;
+
+import org.hibernate.validation.util.LoggerFactory;
+import org.hibernate.validation.util.ReflectionHelper;
+import org.hibernate.validation.util.annotationfactory.AnnotationDescriptor;
+import org.hibernate.validation.util.annotationfactory.AnnotationFactory;
+
+/**
+ * Describe a single constraint.
+ *
+ * @author Emmanuel Bernard
+ * @author Hardy Ferentschik
+ */
+public class ConstraintDescriptorImpl<U extends Annotation> implements ConstraintDescriptor {
+ private static final Logger log = LoggerFactory.make();
+ private static final Class<?>[] DEFAULT_GROUP = new Class<?>[] { Default.class };
+ private static final int OVERRIDES_PARAMETER_DEFAULT_INDEX = -1;
+
+ private final U annotation;
+ private final Class<? extends ConstraintValidator<U,?>>[] constraintClasses;
+ private final Set<Class<?>> groups;
+ private final Map<String, Object> parameters;
+ private final Set<ConstraintDescriptor> composingConstraints = new HashSet<ConstraintDescriptor>();
+ private final Map<ClassIndexWrapper, Map<String, Object>> overrideParameters = new HashMap<ClassIndexWrapper, Map<String, Object>>();
+ private final boolean isReportAsSingleInvalidConstraint;
+
+ public ConstraintDescriptorImpl(U annotation, Class<?>[] groups) {
+ this( annotation, new HashSet<Class<?>>() );
+ if ( groups.length == 0 ) {
+ groups = DEFAULT_GROUP;
+ }
+ this.groups.addAll( Arrays.asList( groups ) );
+ }
+
+ public ConstraintDescriptorImpl(U annotation, Set<Class<?>> groups) {
+ this.annotation = annotation;
+ this.groups = groups;
+ this.parameters = getAnnotationParameters( annotation );
+
+ this.isReportAsSingleInvalidConstraint = annotation.annotationType().isAnnotationPresent(
+ ReportAsViolationFromCompositeConstraint.class
+ );
+
+
+ if ( ReflectionHelper.isBuiltInConstraintAnnotation( annotation ) ) {
+ this.constraintClasses = (Class<? extends ConstraintValidator<U,?>>[])
+ ReflectionHelper.getBuiltInConstraints( annotation );
+ }
+ else {
+ Constraint constraint = annotation.annotationType()
+ .getAnnotation( Constraint.class );
+ this.constraintClasses = (Class<? extends ConstraintValidator<U,?>>[])
+ constraint.validatedBy();
+ }
+
+ parseOverrideParameters();
+ parseComposingConstraints();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public U getAnnotation() {
+ return annotation;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Set<Class<?>> getGroups() {
+ return groups;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Class<? extends ConstraintValidator<U,?>>[]
+ getConstraintValidatorClasses() {
+ return constraintClasses;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Map<String, Object> getParameters() {
+ return parameters;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Set<ConstraintDescriptor> getComposingConstraints() {
+ return composingConstraints;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isReportAsViolationFromCompositeConstraint() {
+ return isReportAsSingleInvalidConstraint;
+ }
+
+ @Override
+ public String toString() {
+ return "ConstraintDescriptorImpl{" +
+ "annotation=" + annotation +
+ ", constraintClasses=" + constraintClasses +
+ ", groups=" + groups +
+ ", parameters=" + parameters +
+ ", composingConstraints=" + composingConstraints +
+ ", isReportAsSingleInvalidConstraint=" + isReportAsSingleInvalidConstraint +
+ '}';
+ }
+
+ private Map<String, Object> getAnnotationParameters(Annotation annotation) {
+ Method[] declaredMethods = annotation.annotationType().getDeclaredMethods();
+ Map<String, Object> parameters = new HashMap<String, Object>( declaredMethods.length );
+ for ( Method m : declaredMethods ) {
+ try {
+ parameters.put( m.getName(), m.invoke( annotation ) );
+ }
+ catch ( IllegalAccessException e ) {
+ throw new ValidationException( "Unable to read annotation parameters: " + annotation.getClass(), e );
+ }
+ catch ( InvocationTargetException e ) {
+ throw new ValidationException( "Unable to read annotation parameters: " + annotation.getClass(), e );
+ }
+ }
+ return Collections.unmodifiableMap( parameters );
+ }
+
+ private void addOverrideParameter(Map<ClassIndexWrapper, Map<String, Object>> overrideParameters, Object value, OverridesParameter... parameters) {
+
+ for ( OverridesParameter parameter : parameters ) {
+ ClassIndexWrapper wrapper = new ClassIndexWrapper( parameter.constraint(), parameter.index() );
+ Map<String, Object> map = overrideParameters.get( wrapper );
+ if ( map == null ) {
+ map = new HashMap<String, Object>();
+ overrideParameters.put( wrapper, map );
+ }
+ map.put( parameter.parameter(), value );
+ }
+ }
+
+ private Object getMethodValue(Annotation annotation, Method m) {
+ Object value;
+ try {
+ value = m.invoke( annotation );
+ }
+ // should never happen
+ catch ( IllegalAccessException e ) {
+ throw new ValidationException( "Unable to retrieve annotation parameter value." );
+ }
+ catch ( InvocationTargetException e ) {
+ throw new ValidationException( "Unable to retrieve annotation parameter value." );
+ }
+ return value;
+ }
+
+ private void parseOverrideParameters() {
+ // check for overrides
+ for ( Method m : annotation.annotationType().getMethods() ) {
+ if ( m.getAnnotation( OverridesParameter.class ) != null ) {
+ addOverrideParameter(
+ overrideParameters, getMethodValue( annotation, m ), m.getAnnotation( OverridesParameter.class )
+ );
+ }
+ else if ( m.getAnnotation( OverridesParameters.class ) != null ) {
+ addOverrideParameter(
+ overrideParameters,
+ getMethodValue( annotation, m ),
+ m.getAnnotation( OverridesParameters.class ).value()
+ );
+ }
+ }
+ }
+
+ private void parseComposingConstraints() {
+ for ( Annotation declaredAnnotation : annotation.annotationType().getDeclaredAnnotations() ) {
+ if ( ReflectionHelper.isConstraintAnnotation( declaredAnnotation ) || ReflectionHelper.isBuiltInConstraintAnnotation(
+ declaredAnnotation
+ ) ) {
+ ConstraintDescriptorImpl descriptor = createComposingConstraintDescriptor(
+ OVERRIDES_PARAMETER_DEFAULT_INDEX,
+ declaredAnnotation
+ );
+ composingConstraints.add( descriptor );
+ log.debug( "Adding composing constraint: " + descriptor );
+ }
+ else if ( ReflectionHelper.isMultiValueConstraint( declaredAnnotation ) ) {
+ List<Annotation> multiValueConstraints = ReflectionHelper.getMultiValueConstraints( declaredAnnotation );
+ int index = 1;
+ for ( Annotation constraintAnnotation : multiValueConstraints ) {
+ ConstraintDescriptorImpl descriptor = createComposingConstraintDescriptor(
+ index, constraintAnnotation
+ );
+ composingConstraints.add( descriptor );
+ log.debug( "Adding composing constraint: " + descriptor );
+ index++;
+ }
+ }
+ }
+ }
+
+ private ConstraintDescriptorImpl createComposingConstraintDescriptor(int index, Annotation constraintAnnotation) {
+ AnnotationDescriptor annotationDescriptor = new AnnotationDescriptor(
+ constraintAnnotation.annotationType(), getAnnotationParameters( constraintAnnotation )
+ );
+ Map<String, Object> overrides = overrideParameters.get(
+ new ClassIndexWrapper(
+ constraintAnnotation.annotationType(), index
+ )
+ );
+ if ( overrides != null ) {
+ for ( Map.Entry<String, Object> entry : overrides.entrySet() ) {
+ annotationDescriptor.setValue( entry.getKey(), entry.getValue() );
+ }
+ }
+ Annotation annotationProxy = AnnotationFactory.create( annotationDescriptor );
+ return new ConstraintDescriptorImpl( annotationProxy, groups );
+ }
+
+ private class ClassIndexWrapper {
+ final Class<?> clazz;
+ final int index;
+
+ ClassIndexWrapper(Class<?> clazz, int index) {
+ this.clazz = clazz;
+ this.index = index;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if ( this == o ) {
+ return true;
+ }
+ if ( o == null || getClass() != o.getClass() ) {
+ return false;
+ }
+
+ ClassIndexWrapper that = ( ClassIndexWrapper ) o;
+
+ if ( index != that.index ) {
+ return false;
+ }
+ if ( clazz != null ? !clazz.equals( that.clazz ) : that.clazz != null ) {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = clazz != null ? clazz.hashCode() : 0;
+ result = 31 * result + index;
+ return result;
+ }
+ }
+}
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintDescriptorImpl.java
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintTree.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -17,18 +17,14 @@
*/
package org.hibernate.validation.engine;
-import java.util.List;
import java.util.ArrayList;
-import java.lang.annotation.Annotation;
-import javax.validation.ConstraintValidator;
+import java.util.List;
import javax.validation.ConstraintDescriptor;
+import javax.validation.ConstraintValidator;
import javax.validation.ValidationException;
-import javax.validation.ConstraintValidatorFactory;
-import javax.validation.MessageInterpolator;
import org.slf4j.Logger;
-import org.hibernate.validation.impl.ConstraintViolationImpl;
import org.hibernate.validation.util.LoggerFactory;
/**
@@ -43,27 +39,19 @@
private final ConstraintTree parent;
private final List<ConstraintTree> children;
- private ConstraintValidator constraintValidator;
private final ConstraintDescriptor descriptor;
- private final ConstraintValidatorFactory constraintValidatorFactory;
- private final MessageInterpolator messageInterpolator;
- public ConstraintTree(ConstraintDescriptor descriptor, ConstraintValidatorFactory constraintValidatorFactory, MessageInterpolator messageInterpolator) {
- this( descriptor, null, constraintValidatorFactory, messageInterpolator );
+ public ConstraintTree(ConstraintDescriptor descriptor) {
+ this( descriptor, null );
}
- private ConstraintTree(ConstraintDescriptor descriptor, ConstraintTree parent, ConstraintValidatorFactory constraintValidatorFactory, MessageInterpolator messageInterpolator) {
+ private ConstraintTree(ConstraintDescriptor descriptor, ConstraintTree parent) {
this.parent = parent;
this.descriptor = descriptor;
- this.constraintValidatorFactory = constraintValidatorFactory;
- this.messageInterpolator = messageInterpolator;
- this.constraintValidator = getConstraintValidator( descriptor );
children = new ArrayList<ConstraintTree>( descriptor.getComposingConstraints().size() );
for ( ConstraintDescriptor composingDescriptor : descriptor.getComposingConstraints() ) {
- ConstraintTree treeNode = new ConstraintTree(
- composingDescriptor, this, constraintValidatorFactory, messageInterpolator
- );
+ ConstraintTree treeNode = new ConstraintTree( composingDescriptor, this );
children.add( treeNode );
}
}
@@ -84,10 +72,6 @@
return children.size() > 0;
}
- public ConstraintValidator getConstraint() {
- return constraintValidator;
- }
-
public ConstraintDescriptor getDescriptor() {
return descriptor;
}
@@ -102,7 +86,7 @@
if ( log.isTraceEnabled() ) {
log.trace( "Validating value {} against constraint defined by {}", value, descriptor );
}
- if ( !constraintValidator.isValid( value, constraintContext ) ) {
+ if ( !getConstraintValidator( descriptor, validationContext ).isValid( value, constraintContext ) ) {
for ( ConstraintValidatorContextImpl.ErrorMessage error : constraintContext.getErrorMessages() ) {
final String message = error.getMessage();
createConstraintViolation( value, beanClass, validationContext, leafBeanInstance, message, descriptor );
@@ -124,7 +108,7 @@
}
private <T> void createConstraintViolation(Object value, Class<T> beanClass, ValidationContext<T> validationContext, Object leafBeanInstance, String message, ConstraintDescriptor descriptor) {
- String interpolatedMessage = messageInterpolator.interpolate(
+ String interpolatedMessage = validationContext.getMessageResolver().interpolate(
message,
descriptor,
leafBeanInstance
@@ -143,15 +127,17 @@
validationContext.addConstraintFailure( failingConstraintViolation );
}
- private ConstraintValidator getConstraintValidator(ConstraintDescriptor descriptor) {
+ private ConstraintValidator getConstraintValidator(ConstraintDescriptor descriptor, ValidationContext validationContext) {
ConstraintValidator constraintValidator;
try {
//FIXME do choose the right validator depending on the object validated
- constraintValidator = constraintValidatorFactory.getInstance( descriptor.getConstraintValidatorClasses()[0] );
+ constraintValidator = validationContext.getConstraintValidatorFactory().getInstance( descriptor.getConstraintValidatorClasses()[0] );
}
catch ( RuntimeException e ) {
//FIXME do choose the right validator depending on the object validated
- throw new ValidationException( "Unable to instantiate " + descriptor.getConstraintValidatorClasses()[0], e );
+ throw new ValidationException(
+ "Unable to instantiate " + descriptor.getConstraintValidatorClasses()[0], e
+ );
}
try {
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-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintValidatorContextImpl.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -20,8 +20,8 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import javax.validation.ConstraintDescriptor;
import javax.validation.ConstraintValidatorContext;
-import javax.validation.ConstraintDescriptor;
/**
* @author Emmanuel Bernard
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintValidatorFactoryImpl.java (from rev 15834, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ConstraintValidatorFactoryImpl.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintValidatorFactoryImpl.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintValidatorFactoryImpl.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -0,0 +1,45 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.validation.engine;
+
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorFactory;
+import javax.validation.ValidationException;
+
+/**
+ * Default <code>ConstraintValidatorFactory</code> using a no-arg constructor.
+ *
+ * @author Emmanuel Bernard
+ */
+public class ConstraintValidatorFactoryImpl implements ConstraintValidatorFactory {
+
+ /**
+ * {@inheritDoc}
+ */
+ public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
+ try {
+ return key.newInstance();
+ }
+ catch ( InstantiationException e ) {
+ throw new ValidationException( "Unable to instanciate " + key, e );
+ }
+ catch ( IllegalAccessException e ) {
+ throw new ValidationException( "Unable to instanciate " + key, e );
+ }
+ }
+}
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintValidatorFactoryImpl.java
___________________________________________________________________
Name: svn:keywords
+ Id
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintViolationImpl.java (from rev 15834, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ConstraintViolationImpl.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintViolationImpl.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintViolationImpl.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -0,0 +1,146 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.validation.engine;
+
+import java.util.HashSet;
+import java.util.Set;
+import javax.validation.ConstraintDescriptor;
+import javax.validation.ConstraintViolation;
+
+/**
+ * @author Emmanuel Bernard
+ * @author Hardy Ferentschik
+ */
+public class ConstraintViolationImpl<T> implements ConstraintViolation<T> {
+ private String interpolatedMessage;
+ private T rootBean;
+ private Class<T> beanClass;
+ private Object value;
+ private String propertyPath;
+ private Set<Class<?>> groups;
+ private Object leafBeanInstance;
+ private final ConstraintDescriptor constraintDescriptor;
+ private String rawMessage;
+
+
+ public ConstraintViolationImpl(String rawMessage, String interpolatedMessage, T rootBean, Class<T> beanClass,
+ Object leafBeanInstance, Object value,
+ String propertyPath, Class<?> group, ConstraintDescriptor constraintDescriptor) {
+ this.rawMessage = rawMessage;
+ this.interpolatedMessage = interpolatedMessage;
+ this.rootBean = rootBean;
+ this.beanClass = beanClass;
+ this.value = value;
+ this.propertyPath = propertyPath;
+ groups = new HashSet<Class<?>>();
+ groups.add( group );
+ this.leafBeanInstance = leafBeanInstance;
+ this.constraintDescriptor = constraintDescriptor;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String getInterpolatedMessage() {
+ return interpolatedMessage;
+ }
+
+ public String getRawMessage() {
+ return rawMessage;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public T getRootBean() {
+ return rootBean;
+ }
+
+ public Object getLeafBean() {
+ return leafBeanInstance;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Object getInvalidValue() {
+ return value;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String getPropertyPath() {
+ return propertyPath;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Set<Class<?>> getGroups() {
+ return groups;
+ }
+
+ public ConstraintDescriptor getConstraintDescriptor() {
+ return this.constraintDescriptor;
+ }
+
+ public void addGroups(Set<Class<?>> groupSet) {
+ groups.addAll( groupSet );
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if ( this == o ) {
+ return true;
+ }
+ if ( !( o instanceof ConstraintViolationImpl ) ) {
+ return false;
+ }
+
+ ConstraintViolationImpl that = ( ConstraintViolationImpl ) o;
+
+ if ( beanClass != null ? !beanClass.equals( that.beanClass ) : that.beanClass != null ) {
+ return false;
+ }
+ if ( interpolatedMessage != null ? !interpolatedMessage.equals( that.interpolatedMessage ) : that.interpolatedMessage != null ) {
+ return false;
+ }
+ if ( propertyPath != null ? !propertyPath.equals( that.propertyPath ) : that.propertyPath != null ) {
+ return false;
+ }
+ if ( rootBean != null ? !rootBean.equals( that.rootBean ) : that.rootBean != null ) {
+ return false;
+ }
+ if ( value != null ? !value.equals( that.value ) : that.value != null ) {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = interpolatedMessage != null ? interpolatedMessage.hashCode() : 0;
+ result = 31 * result + ( rootBean != null ? rootBean.hashCode() : 0 );
+ result = 31 * result + ( beanClass != null ? beanClass.hashCode() : 0 );
+ result = 31 * result + ( value != null ? value.hashCode() : 0 );
+ result = 31 * result + ( propertyPath != null ? propertyPath.hashCode() : 0 );
+ return result;
+ }
+}
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintViolationImpl.java
___________________________________________________________________
Name: svn:keywords
+ Id
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/DefaultTraversableResolver.java (from rev 15834, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/DefaultTraversableResolver.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/DefaultTraversableResolver.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/DefaultTraversableResolver.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -0,0 +1,13 @@
+package org.hibernate.validation.engine;
+
+import java.lang.annotation.ElementType;
+import javax.validation.TraversableResolver;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class DefaultTraversableResolver implements TraversableResolver {
+ public boolean isTraversable(Object traversableObject, String traversableProperty, Class<?> rootBeanType, String pathToTraversableObject, ElementType elementType) {
+ return true;
+ }
+}
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/DefaultTraversableResolver.java
___________________________________________________________________
Name: svn:keywords
+ Id
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ElementDescriptorImpl.java (from rev 15834, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ElementDescriptorImpl.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ElementDescriptorImpl.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ElementDescriptorImpl.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -0,0 +1,85 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.validation.engine;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import javax.validation.ConstraintDescriptor;
+import javax.validation.PropertyDescriptor;
+
+/**
+ * Describe a validated element (class, field or property).
+ *
+ * @author Emmanuel Bernard
+ * @author Hardy Ferentschik
+ * @todo Should returnType be renamed to type?
+ * @todo Handle problem in descirbing cyclic dependecies for propertyPath
+ */
+//FIXME I implement both interfaces on the same object as a quick hack, we need to fix that.
+public class ElementDescriptorImpl implements PropertyDescriptor {
+ private final Class<?> returnType;
+ private final boolean cascaded;
+ private final Set<ConstraintDescriptor> constraintDescriptors = new HashSet<ConstraintDescriptor>();
+ private final String propertyPath;
+
+
+ public ElementDescriptorImpl(Class<?> returnType, boolean cascaded, String propertyPath) {
+ this.returnType = returnType;
+ this.cascaded = cascaded;
+ this.propertyPath = propertyPath;
+ }
+
+ public void addConstraintDescriptor(ConstraintDescriptorImpl constraintDescriptor) {
+ constraintDescriptors.add( constraintDescriptor );
+ }
+
+ public boolean hasConstraints() {
+ return constraintDescriptors.size() != 0;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @todo Generic type or regular type?
+ */
+ public Class getType() {
+ return returnType;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isCascaded() {
+ return cascaded;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Set<ConstraintDescriptor> getConstraintDescriptors() {
+ return Collections.unmodifiableSet( constraintDescriptors );
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String getPropertyName() {
+ return propertyPath;
+ }
+}
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ElementDescriptorImpl.java
___________________________________________________________________
Name: svn:keywords
+ Id
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/HibernateValidationProvider.java (from rev 15834, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/HibernateValidationProvider.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/HibernateValidationProvider.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/HibernateValidationProvider.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -0,0 +1,65 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.validation.engine;
+
+import javax.validation.Configuration;
+import javax.validation.ValidationException;
+import javax.validation.ValidatorFactory;
+import javax.validation.spi.BootstrapState;
+import javax.validation.spi.ConfigurationState;
+import javax.validation.spi.ValidationProvider;
+
+/**
+ * Default implementation of <code>ValidationProvider</code> within Hibernate validator.
+ *
+ * @author Emmanuel Bernard
+ * @author Hardy Ferentschik
+ */
+public class HibernateValidationProvider implements ValidationProvider {
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isSuitable(Class<? extends Configuration<?>> builderClass) {
+ return builderClass == HibernateValidatorConfiguration.class;
+ }
+
+ public <T extends Configuration<T>> T createSpecializedConfiguration(BootstrapState state, Class<T> configurationClass) {
+ if ( !isSuitable( configurationClass ) ) {
+ throw new ValidationException(
+ "Illegal call to createSpecializedConfiguration() for a non suitable provider"
+ );
+ }
+ //cast protected by isSuitable call
+ return configurationClass.cast( new ConfigurationImpl( this ) );
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Configuration<?> createGenericConfiguration(BootstrapState state) {
+ return new ConfigurationImpl( state );
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public ValidatorFactory buildValidatorFactory(ConfigurationState configurationState) {
+ return new ValidatorFactoryImpl( configurationState );
+ }
+}
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/HibernateValidationProvider.java
___________________________________________________________________
Name: svn:executable
+ *
Name: svn:keywords
+ Id
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/HibernateValidatorConfiguration.java (from rev 15834, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/HibernateValidatorConfiguration.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/HibernateValidatorConfiguration.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/HibernateValidatorConfiguration.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -0,0 +1,12 @@
+package org.hibernate.validation.engine;
+
+import javax.validation.Configuration;
+
+/**
+ * Uniquely identify Hibernate Validator in the Bean Validation bootstrap strategy
+ * Also contains Hibernate Validator specific configurations
+ *
+ * @author Emmanuel Bernard
+ */
+public interface HibernateValidatorConfiguration extends Configuration<HibernateValidatorConfiguration> {
+}
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/HibernateValidatorConfiguration.java
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/MetaConstraint.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -23,8 +23,6 @@
import java.lang.reflect.Type;
import javax.validation.ConstraintDescriptor;
import javax.validation.ValidationException;
-import javax.validation.MessageInterpolator;
-import javax.validation.ConstraintValidatorFactory;
import org.hibernate.validation.util.ReflectionHelper;
@@ -70,36 +68,32 @@
*/
private final ElementType elementType;
- public MetaConstraint(Type t, ConstraintDescriptor constraintDescriptor, MessageInterpolator messageInterpolator, ConstraintValidatorFactory validatorFactory) {
- this( t, null, null, ElementType.FIELD, constraintDescriptor, "", messageInterpolator, validatorFactory );
+ public MetaConstraint(Type t, ConstraintDescriptor constraintDescriptor) {
+ this( t, null, null, ElementType.FIELD, constraintDescriptor, "" );
}
- public MetaConstraint(Method m, ConstraintDescriptor constraintDescriptor, MessageInterpolator messageInterpolator, ConstraintValidatorFactory validatorFactory) {
+ public MetaConstraint(Method m, ConstraintDescriptor constraintDescriptor) {
this(
null,
m,
null,
ElementType.METHOD,
constraintDescriptor,
- ReflectionHelper.getPropertyName( m ),
- messageInterpolator,
- validatorFactory
+ ReflectionHelper.getPropertyName( m )
);
}
- public MetaConstraint(Field f, ConstraintDescriptor constraintDescriptor, MessageInterpolator messageInterpolator, ConstraintValidatorFactory validatorFactory) {
- this( null, null, f, ElementType.FIELD, constraintDescriptor, f.getName(), messageInterpolator,
- validatorFactory
- );
+ public MetaConstraint(Field f, ConstraintDescriptor constraintDescriptor) {
+ this( null, null, f, ElementType.FIELD, constraintDescriptor, f.getName() );
}
- private MetaConstraint(Type t, Method m, Field f, ElementType elementType, ConstraintDescriptor constraintDescriptor, String property, MessageInterpolator messageInterpolator, ConstraintValidatorFactory validatorFactory) {
+ private MetaConstraint(Type t, Method m, Field f, ElementType elementType, ConstraintDescriptor constraintDescriptor, String property) {
this.type = t;
this.method = m;
this.field = f;
this.elementType = elementType;
this.propertyName = property;
- constraintTree = new ConstraintTree( constraintDescriptor, validatorFactory, messageInterpolator );
+ constraintTree = new ConstraintTree( constraintDescriptor );
}
/**
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolator.java (from rev 15834, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ResourceBundleMessageInterpolator.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolator.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolator.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -0,0 +1,155 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.validation.engine;
+
+import java.util.Locale;
+import java.util.Map;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import javax.validation.ConstraintDescriptor;
+import javax.validation.MessageInterpolator;
+
+import org.slf4j.Logger;
+
+import org.hibernate.validation.util.LoggerFactory;
+
+
+/**
+ * Resource bundle backed message interpolator.
+ *
+ * @author Emmanuel Bernard
+ */
+public class ResourceBundleMessageInterpolator implements MessageInterpolator {
+ private static final String DEFAULT_VALIDATION_MESSAGES = "org.hibernate.validation.ValidationMessages";
+ private static final String USER_VALIDATION_MESSAGES = "ValidationMessages";
+ private static final Logger log = LoggerFactory.make();
+
+ /**
+ * Regular expression used to do message interpolation.
+ */
+ private static final Pattern messagePattern = Pattern.compile( "\\{([\\w\\.]+)\\}" );
+ private ResourceBundle defaultResourceBundle;
+ private ResourceBundle userResourceBundle;
+
+ public ResourceBundleMessageInterpolator() {
+ userResourceBundle = getFileBasedResourceBundle();
+ defaultResourceBundle = ResourceBundle.getBundle( DEFAULT_VALIDATION_MESSAGES );
+ }
+
+ public ResourceBundleMessageInterpolator(ResourceBundle resourceBundle) {
+ if ( resourceBundle == null ) {
+ userResourceBundle = getFileBasedResourceBundle();
+ }
+ else {
+ this.userResourceBundle = resourceBundle;
+ }
+ defaultResourceBundle = ResourceBundle.getBundle( DEFAULT_VALIDATION_MESSAGES );
+ }
+
+ /**
+ * Search current thread classloader for the resource bundle. If not found, search validator (this) classloader.
+ *
+ * @return the resource bundle or <code>null</code> if none is found.
+ */
+ private ResourceBundle getFileBasedResourceBundle() {
+ ResourceBundle rb = null;
+ ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
+ if ( classLoader != null ) {
+ rb = loadBundle( classLoader, USER_VALIDATION_MESSAGES + " not found by thread local classloader" );
+ }
+ if ( rb == null ) {
+ rb = loadBundle(
+ this.getClass().getClassLoader(), USER_VALIDATION_MESSAGES + " not found by validator classloader"
+ );
+ }
+ if ( log.isDebugEnabled() ) {
+ if ( rb != null ) {
+ log.debug( USER_VALIDATION_MESSAGES + " found" );
+ }
+ else {
+ log.debug( USER_VALIDATION_MESSAGES + " not found. Delegating to " + DEFAULT_VALIDATION_MESSAGES );
+ }
+ }
+ return rb;
+ }
+
+ private ResourceBundle loadBundle(ClassLoader classLoader, String message) {
+ ResourceBundle rb = null;
+ try {
+ rb = ResourceBundle.getBundle( USER_VALIDATION_MESSAGES, Locale.getDefault(), classLoader );
+ }
+ catch ( MissingResourceException e ) {
+ log.trace( message );
+ }
+ return rb;
+ }
+
+ public String interpolate(String message, ConstraintDescriptor constraintDescriptor, Object value) {
+ //probably no need for caching, but it could be done by parameters since the map
+ //is immutable and uniquely built per Validation definition, the comparaison has to be based on == and not equals though
+ return replace( message, constraintDescriptor.getParameters() );
+ }
+
+ public String interpolate(String message, ConstraintDescriptor constraintDescriptor, Object value, Locale locale) {
+ throw new UnsupportedOperationException( "Interpolation for Locale. Has to be done." );
+ }
+
+
+ private String replace(String message, Map<String, Object> parameters) {
+ Matcher matcher = messagePattern.matcher( message );
+ StringBuffer sb = new StringBuffer();
+ while ( matcher.find() ) {
+ matcher.appendReplacement( sb, resolveParameter( matcher.group( 1 ), parameters ) );
+ }
+ matcher.appendTail( sb );
+ return sb.toString();
+ }
+
+
+ private String resolveParameter(String token, Map<String, Object> parameters) {
+ Object variable = parameters.get( token );
+ if ( variable != null ) {
+ return variable.toString();
+ }
+
+ StringBuffer buffer = new StringBuffer();
+ String string = null;
+ try {
+ string = userResourceBundle != null ? userResourceBundle.getString( token ) : null;
+ }
+ catch ( MissingResourceException e ) {
+ //give a second chance with the default resource bundle
+ }
+ if ( string == null ) {
+ try {
+ string = defaultResourceBundle.getString( token );
+ }
+ catch ( MissingResourceException e ) {
+ //return the unchanged string
+ buffer.append( "{" ).append( token ).append( '}' );
+ }
+ }
+ if ( string != null ) {
+ // call resolve recusively!
+ buffer.append( replace( string, parameters ) );
+ }
+ return buffer.toString();
+ }
+}
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolator.java
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidationContext.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidationContext.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidationContext.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -23,8 +23,9 @@
import java.util.Map;
import java.util.Set;
import java.util.Stack;
+import javax.validation.ConstraintValidatorFactory;
+import javax.validation.MessageInterpolator;
-import org.hibernate.validation.impl.ConstraintViolationImpl;
import org.hibernate.validation.util.IdentitySet;
/**
@@ -72,19 +73,39 @@
*/
private Stack<ValidatedBean> validatedObjectStack = new Stack<ValidatedBean>();
+ /**
+ * The message resolver which should be used in this context.
+ */
+ private final MessageInterpolator messageResolver;
- public ValidationContext(T object) {
- this( object, object );
+ /**
+ * The constraint factory which should be used in this context.
+ */
+ ConstraintValidatorFactory constraintValidatorFactory;
+
+
+ public ValidationContext(T object, MessageInterpolator messageResolver, ConstraintValidatorFactory constraintValidatorFactory) {
+ this( object, object, messageResolver, constraintValidatorFactory );
}
- public ValidationContext(T rootBean, Object object) {
+ public ValidationContext(T rootBean, Object object, MessageInterpolator messageResolver, ConstraintValidatorFactory constraintValidatorFactory) {
this.rootBean = rootBean;
+ this.messageResolver = messageResolver;
+ this.constraintValidatorFactory = constraintValidatorFactory;
validatedObjectStack.push( new ValidatedBean( object ) );
processedObjects = new HashMap<Class<?>, IdentitySet>();
propertyPath = "";
failingConstraintViolations = new ArrayList<ConstraintViolationImpl<T>>();
}
+ public MessageInterpolator getMessageResolver() {
+ return messageResolver;
+ }
+
+ public ConstraintValidatorFactory getConstraintValidatorFactory() {
+ return constraintValidatorFactory;
+ }
+
public Object peekValidatedObject() {
return validatedObjectStack.peek().bean;
}
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorContextImpl.java (from rev 15834, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ValidatorContextImpl.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorContextImpl.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorContextImpl.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -0,0 +1,52 @@
+package org.hibernate.validation.engine;
+
+import javax.validation.ConstraintValidatorFactory;
+import javax.validation.MessageInterpolator;
+import javax.validation.TraversableResolver;
+import javax.validation.Validator;
+import javax.validation.ValidatorContext;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class ValidatorContextImpl implements ValidatorContext {
+ private MessageInterpolator messageInterpolator;
+ private TraversableResolver traversableResolver;
+ private final MessageInterpolator factoryMessageInterpolator;
+ private final TraversableResolver factoryTraversableResolver;
+ private final ConstraintValidatorFactory constraintValidatorFactory;
+
+ public ValidatorContextImpl(ConstraintValidatorFactory constraintValidatorFactory,
+ MessageInterpolator factoryMessageInterpolator,
+ TraversableResolver factoryTraversableResolver) {
+ this.constraintValidatorFactory = constraintValidatorFactory;
+ this.factoryMessageInterpolator = factoryMessageInterpolator;
+ this.factoryTraversableResolver = factoryTraversableResolver;
+ messageInterpolator( factoryMessageInterpolator );
+ traversableResolver( factoryTraversableResolver );
+ }
+
+ public ValidatorContext messageInterpolator(MessageInterpolator messageInterpolator) {
+ if ( messageInterpolator == null ) {
+ this.messageInterpolator = factoryMessageInterpolator;
+ }
+ else {
+ this.messageInterpolator = messageInterpolator;
+ }
+ return this;
+ }
+
+ public ValidatorContext traversableResolver(TraversableResolver traversableResolver) {
+ if ( traversableResolver == null ) {
+ this.traversableResolver = factoryTraversableResolver;
+ }
+ else {
+ this.traversableResolver = traversableResolver;
+ }
+ return this;
+ }
+
+ public Validator getValidator() {
+ return new ValidatorImpl( constraintValidatorFactory, messageInterpolator );
+ }
+}
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorContextImpl.java
___________________________________________________________________
Name: svn:keywords
+ Id
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorFactoryImpl.java (from rev 15834, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ValidatorFactoryImpl.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorFactoryImpl.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorFactoryImpl.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -0,0 +1,65 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.validation.engine;
+
+import javax.validation.ConstraintValidatorFactory;
+import javax.validation.MessageInterpolator;
+import javax.validation.TraversableResolver;
+import javax.validation.Validator;
+import javax.validation.ValidatorContext;
+import javax.validation.ValidatorFactory;
+import javax.validation.spi.ConfigurationState;
+
+/**
+ * @author Emmanuel Bernard
+ * @author Hardy Ferentschik
+ */
+public class ValidatorFactoryImpl implements ValidatorFactory {
+
+ private final MessageInterpolator messageInterpolator;
+ private final TraversableResolver traversableResolver;
+ private final ConstraintValidatorFactory constraintValidatorFactory;
+
+ public ValidatorFactoryImpl(ConfigurationState configurationState) {
+ this.messageInterpolator = configurationState.getMessageInterpolator();
+ this.constraintValidatorFactory = configurationState.getConstraintValidatorFactory();
+ this.traversableResolver = configurationState.getTraversableResolver();
+ //do init metadata from XML form
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Validator getValidator() {
+ return usingContext().getValidator();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public MessageInterpolator getMessageInterpolator() {
+ return messageInterpolator;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public ValidatorContext usingContext() {
+ return new ValidatorContextImpl( constraintValidatorFactory, messageInterpolator, traversableResolver );
+ }
+}
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorFactoryImpl.java
___________________________________________________________________
Name: svn:executable
+ *
Name: svn:keywords
+ Id
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorFactoryImplementor.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorFactoryImplementor.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorFactoryImplementor.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -1,31 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.validation.engine;
-
-import javax.validation.ValidatorFactory;
-
-/**
- * @author Emmanuel Bernard
- */
-public interface ValidatorFactoryImplementor extends ValidatorFactory {
- /**
- * @param clazz The bean class for which to retrieve the meta data.
- * @return Gives access to the required parsed meta data. This never returns an <code>null</code> object.
- */
- <T> BeanMetaData<T> getBeanMetaData(Class<T> clazz);
-}
Deleted: 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-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -1,398 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.validation.engine;
-
-import java.lang.reflect.Member;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import javax.validation.BeanDescriptor;
-import javax.validation.ConstraintDescriptor;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validator;
-import javax.validation.groups.Default;
-
-import org.hibernate.validation.impl.ConstraintViolationImpl;
-import org.hibernate.validation.util.PropertyIterator;
-import org.hibernate.validation.util.ReflectionHelper;
-
-/**
- * The main Bean Validation class.
- *
- * @author Emmanuel Bernard
- * @author Hardy Ferentschik
- * @todo Make all properties transient for serializability.
- */
-public class ValidatorImpl implements Validator {
- private static final Set<Class<?>> INDEXABLE_CLASS = new HashSet<Class<?>>();
- private static final Class<?>[] DEFAULT_GROUP = new Class<?>[] { Default.class };
-
- static {
- INDEXABLE_CLASS.add( Integer.class );
- INDEXABLE_CLASS.add( Long.class );
- INDEXABLE_CLASS.add( String.class );
- }
-
- private final ValidatorFactoryImplementor factory;
-
- public ValidatorImpl(ValidatorFactoryImplementor factory) {
- this.factory = factory;
- }
-
- /**
- * {@inheritDoc}
- */
- public <T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups) {
- if ( object == null ) {
- throw new IllegalArgumentException( "Validation of a null object" );
- }
-
- ValidationContext<T> context = new ValidationContext<T>( object );
- List<ConstraintViolationImpl<T>> list = validateInContext( context, Arrays.asList( groups ) );
- return new HashSet<ConstraintViolation<T>>( list );
- }
-
- /**
- * Validates the object contained in <code>context</code>.
- *
- * @param context A context object containing the object to validate together with other state information needed
- * for validation.
- * @param groups A list of groups to validate.
- *
- * @return List of invalid constraints.
- *
- * @todo Currently we iterate the cascaded fields multiple times. Maybe we should change to an approach where we iterate the object graph only once.
- * @todo Context root bean can be a different object than the current Validator<T> hence two different generics variables
- */
- private <T> List<ConstraintViolationImpl<T>> validateInContext(ValidationContext<T> context, List<Class<?>> groups) {
- if ( context.peekValidatedObject() == null ) {
- return Collections.emptyList();
- }
-
- // if no group is specified use the default
- if ( groups.size() == 0 ) {
- groups = Arrays.asList( DEFAULT_GROUP );
- }
-
- List<Class<?>> expandedGroups;
- boolean isGroupSequence;
- for ( Class<?> group : groups ) {
- expandedGroups = new ArrayList<Class<?>>();
- isGroupSequence = expandGroup( context.peekValidatedObjectType(), group, expandedGroups );
-
- for ( Class<?> expandedGroupName : expandedGroups ) {
- context.setCurrentGroup( expandedGroupName );
-
- validateConstraints( context );
- validateCascadedConstraints( context );
-
- if ( isGroupSequence && context.getFailingConstraints().size() > 0 ) {
- break;
- }
- }
- }
- return context.getFailingConstraints();
- }
-
- /**
- * Validates the non-cascaded constraints.
- *
- * @param validationContext The current validation context.
- */
- private <T> void validateConstraints(ValidationContext<T> validationContext) {
- //casting rely on the fact that root object is at the top of the stack
- @SuppressWarnings("unchecked")
- BeanMetaData<T> beanMetaData =
- ( BeanMetaData<T> ) factory.getBeanMetaData( validationContext.peekValidatedObjectType() );
- for ( MetaConstraint metaConstraint : beanMetaData.geMetaConstraintList() ) {
- ConstraintDescriptor mainConstraintDescriptor = metaConstraint.getDescriptor();
-
- validationContext.pushProperty( metaConstraint.getPropertyName() );
-
- if ( !validationContext.needsValidation( mainConstraintDescriptor.getGroups() ) ) {
- validationContext.popProperty();
- continue;
- }
-
- metaConstraint.validateConstraint( beanMetaData.getBeanClass(), validationContext );
- validationContext.popProperty();
- }
- validationContext.markProcessedForCurrentGroup();
- }
-
- /**
- * Called when processing cascaded constraints. This methods inspects the type of the cascaded constraints and in case
- * of a list or array creates an iterator in order to validate each element.
- *
- * @param context the validation context.
- * @param type the type of the cascaded field or property.
- * @param value the actual value.
- */
- private <T> void validateCascadedConstraint(ValidationContext<T> context, Type type, Object value) {
- if ( value == null ) {
- return;
- }
-
- Iterator<?> iter;
- if ( ReflectionHelper.isCollection( type ) ) {
- boolean isIterable = value instanceof Iterable;
- Map<?, ?> map = !isIterable ? ( Map<?, ?> ) value : null;
- Iterable<?> elements = isIterable ?
- ( Iterable<?> ) value :
- map.entrySet();
- iter = elements.iterator();
- context.appendIndexToPropertyPath( "[{0}]" );
- }
- else if ( ReflectionHelper.isArray( type ) ) {
- List<?> arrayList = Arrays.asList( value );
- iter = arrayList.iterator();
- context.appendIndexToPropertyPath( "[{0}]" );
- }
- else {
- List<Object> list = new ArrayList<Object>();
- list.add( value );
- iter = list.iterator();
- }
-
- validateCascadedConstraint( context, iter );
- }
-
- private <T> void validateCascadedConstraints(ValidationContext<T> context) {
- List<Member> cascadedMembers = factory.getBeanMetaData( context.peekValidatedObjectType() )
- .getCascadedMembers();
- for ( Member member : cascadedMembers ) {
- Type type = ReflectionHelper.typeOf( member );
- context.pushProperty( ReflectionHelper.getPropertyName( member ) );
- Object value = ReflectionHelper.getValue( member, context.peekValidatedObject() );
- validateCascadedConstraint( context, type, value );
- context.popProperty();
- }
- }
-
- private <T> void validateCascadedConstraint(ValidationContext<T> context, Iterator<?> iter) {
- Object actualValue;
- String propertyIndex;
- int i = 0;
- while ( iter.hasNext() ) {
- actualValue = iter.next();
- propertyIndex = String.valueOf( i );
- if ( actualValue instanceof Map.Entry ) {
- Object key = ( ( Map.Entry ) actualValue ).getKey();
- if ( INDEXABLE_CLASS.contains( key.getClass() ) ) {
- propertyIndex = key.toString();
- }
- actualValue = ( ( Map.Entry ) actualValue ).getValue();
- }
-
- if ( context.isProcessedForCurrentGroup( actualValue ) ) {
- i++;
- continue;
- }
-
- context.replacePropertyIndex( propertyIndex );
-
- context.pushValidatedObject( actualValue );
- validateInContext( context, Arrays.asList( new Class<?>[] { context.getCurrentGroup() } ) );
- context.popValidatedObject();
- i++;
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public <T> Set<ConstraintViolation<T>> validateProperty(T object, String propertyName, Class<?>... groups) {
- List<ConstraintViolationImpl<T>> failingConstraintViolations = new ArrayList<ConstraintViolationImpl<T>>();
- validateProperty( object, new PropertyIterator( propertyName ), failingConstraintViolations, groups );
- return new HashSet<ConstraintViolation<T>>( failingConstraintViolations );
- }
-
- private <T> void validateProperty(T object, PropertyIterator propertyIter, List<ConstraintViolationImpl<T>> failingConstraintViolations, Class<?>... groups) {
- if ( object == null ) {
- throw new IllegalArgumentException( "Validated object cannot be null" );
- }
- @SuppressWarnings("unchecked")
- final Class<T> beanType = ( Class<T> ) object.getClass();
-
- Set<MetaConstraint> metaConstraints = new HashSet<MetaConstraint>();
- getMetaConstraintsForPath( beanType, propertyIter, metaConstraints );
-
- if ( metaConstraints.size() == 0 ) {
- return;
- }
-
- // if no group is specified use the default
- if ( groups.length == 0 ) {
- groups = DEFAULT_GROUP;
- }
-
- List<Class<?>> expandedGroups;
- boolean isGroupSequence;
- for ( Class<?> group : groups ) {
- expandedGroups = new ArrayList<Class<?>>();
- isGroupSequence = expandGroup( beanType, group, expandedGroups );
-
- for ( Class<?> expandedGroup : expandedGroups ) {
-
- for ( MetaConstraint metaConstraint : metaConstraints ) {
- if ( !metaConstraint.getDescriptor().getGroups().contains( expandedGroup ) ) {
- continue;
- }
-
- ValidationContext<T> context = new ValidationContext<T>( object );
- metaConstraint.validateConstraint( object.getClass(), context );
- failingConstraintViolations.addAll( context.getFailingConstraints() );
- }
-
- if ( isGroupSequence && failingConstraintViolations.size() > 0 ) {
- break;
- }
- }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public <T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups) {
- List<ConstraintViolationImpl<T>> failingConstraintViolations = new ArrayList<ConstraintViolationImpl<T>>();
- validateValue( beanType, value, new PropertyIterator( propertyName ), failingConstraintViolations, groups );
- return new HashSet<ConstraintViolation<T>>( failingConstraintViolations );
- }
-
- public BeanDescriptor getConstraintsForClass(Class<?> clazz) {
- return factory.getBeanMetaData( clazz ).getBeanDescriptor();
- }
-
- private <T> void validateValue(Class<T> beanType, Object value, PropertyIterator propertyIter, List<ConstraintViolationImpl<T>> failingConstraintViolations, Class<?>... groups) {
- Set<MetaConstraint> metaConstraints = new HashSet<MetaConstraint>();
- getMetaConstraintsForPath( beanType, propertyIter, metaConstraints );
-
- if ( metaConstraints.size() == 0 ) {
- return;
- }
-
- // if no group is specified use the default
- if ( groups.length == 0 ) {
- groups = DEFAULT_GROUP;
- }
-
- List<Class<?>> expandedGroups;
- boolean isGroupSequence;
- for ( Class<?> group : groups ) {
- expandedGroups = new ArrayList<Class<?>>();
- isGroupSequence = expandGroup( beanType, group, expandedGroups );
-
- for ( Class<?> expandedGroup : expandedGroups ) {
-
- for ( MetaConstraint metaConstraint : metaConstraints ) {
- if ( !metaConstraint.getDescriptor().getGroups().contains( expandedGroup ) ) {
- continue;
- }
-
- ValidationContext<T> context = new ValidationContext<T>( ( T ) value );
- context.pushProperty( propertyIter.getOriginalProperty() );
- metaConstraint.validateConstraint( beanType, value, context );
- failingConstraintViolations.addAll( context.getFailingConstraints() );
- }
-
- if ( isGroupSequence && failingConstraintViolations.size() > 0 ) {
- break;
- }
- }
- }
- }
-
- /**
- * Collects all <code>MetaConstraint</code>s which match the given path relative to the specified root class.
- * <p>
- * This method does not traverse an actual object, but rather tries to resolve the porperty generically.
- * </p>
- * <p>
- * This method is called recursively. Only if there is a valid 'validation path' through the object graph
- * a constraint descriptor will be returned.
- * </p>
- *
- * @param clazz the class type to check for constraints.
- * @param propertyIter an instance of <code>PropertyIterator</code>
- * @param metaConstraints Set of <code>MetaConstraint</code>s to collect all matching constraints.
- */
- private void getMetaConstraintsForPath(Class<?> clazz, PropertyIterator propertyIter, Set<MetaConstraint> metaConstraints) {
- propertyIter.split();
-
- if ( !propertyIter.hasNext() ) {
- List<MetaConstraint> metaConstraintList = factory.getBeanMetaData( clazz ).geMetaConstraintList();
- for ( MetaConstraint metaConstraint : metaConstraintList ) {
- if ( metaConstraint.getPropertyName().equals( propertyIter.getHead() ) ) {
- metaConstraints.add( metaConstraint );
- }
- }
- }
- else {
- List<Member> cascadedMembers = factory.getBeanMetaData( clazz ).getCascadedMembers();
- for ( Member m : cascadedMembers ) {
- if ( ReflectionHelper.getPropertyName( m ).equals( propertyIter.getHead() ) ) {
- Type type = ReflectionHelper.typeOf( m );
-
- if ( propertyIter.isIndexed() ) {
- type = ReflectionHelper.getIndexedType( type );
- if ( type == null ) {
- continue;
- }
- }
- getMetaConstraintsForPath( ( Class<?> ) type, propertyIter, metaConstraints );
- }
- }
- }
- }
-
- /**
- * Checks whether the provided group name is a group sequence and if so expands the group name and add the expanded
- * groups names to <code>expandedGroupName</code>.
- *
- * @param beanType The class for which to expand the group names.
- * @param group The group to expand
- * @param expandedGroups The exanded group names or just a list with the single provided group name id the name
- * was not expandable
- *
- * @return <code>true</code> if an expansion took place, <code>false</code> otherwise.
- */
- private <T> boolean expandGroup(Class<T> beanType, Class<?> group, List<Class<?>> expandedGroups) {
- if ( expandedGroups == null ) {
- throw new IllegalArgumentException( "List cannot be empty" );
- }
-
- boolean isGroupSequence;
- BeanMetaData<T> metaDataProvider = factory.getBeanMetaData( beanType );
- if ( metaDataProvider.getGroupSequences().containsKey( group ) ) {
- expandedGroups.addAll( metaDataProvider.getGroupSequences().get( group ) );
- isGroupSequence = true;
- }
- else {
- expandedGroups.add( group );
- isGroupSequence = false;
- }
- return isGroupSequence;
- }
-}
Added: 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 (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -0,0 +1,425 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.validation.engine;
+
+import java.lang.reflect.Member;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import javax.validation.BeanDescriptor;
+import javax.validation.ConstraintDescriptor;
+import javax.validation.ConstraintValidatorFactory;
+import javax.validation.ConstraintViolation;
+import javax.validation.MessageInterpolator;
+import javax.validation.Validator;
+import javax.validation.groups.Default;
+
+import org.hibernate.validation.util.PropertyIterator;
+import org.hibernate.validation.util.ReflectionHelper;
+
+/**
+ * The main Bean Validation class.
+ *
+ * @author Emmanuel Bernard
+ * @author Hardy Ferentschik
+ * @todo Make all properties transient for serializability.
+ */
+public class ValidatorImpl implements Validator {
+ private static final Set<Class<?>> INDEXABLE_CLASS = new HashSet<Class<?>>();
+ private static final Class<?>[] DEFAULT_GROUP = new Class<?>[] { Default.class };
+
+ /**
+ * A map for the meta data for each entity. The key is the class and the value the bean meta data for this
+ * entity.
+ */
+ private static Map<Class<?>, BeanMetaDataImpl<?>> metadataProviders
+ = new ConcurrentHashMap<Class<?>, BeanMetaDataImpl<?>>( 10 );
+
+ static {
+ INDEXABLE_CLASS.add( Integer.class );
+ INDEXABLE_CLASS.add( Long.class );
+ INDEXABLE_CLASS.add( String.class );
+ }
+
+ private final ConstraintValidatorFactory constraintValidatorFactory;
+ private final MessageInterpolator messageInterpolator;
+
+ public ValidatorImpl(ConstraintValidatorFactory constraintValidatorFactory, MessageInterpolator messageInterpolator) {
+ this.constraintValidatorFactory = constraintValidatorFactory;
+ this.messageInterpolator = messageInterpolator;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public <T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups) {
+ if ( object == null ) {
+ throw new IllegalArgumentException( "Validation of a null object" );
+ }
+
+ ValidationContext<T> context = new ValidationContext<T>( object, messageInterpolator, constraintValidatorFactory );
+ List<ConstraintViolationImpl<T>> list = validateInContext( context, Arrays.asList( groups ) );
+ return new HashSet<ConstraintViolation<T>>( list );
+ }
+
+ /**
+ * Validates the object contained in <code>context</code>.
+ *
+ * @param context A context object containing the object to validate together with other state information needed
+ * for validation.
+ * @param groups A list of groups to validate.
+ *
+ * @return List of invalid constraints.
+ *
+ * @todo Currently we iterate the cascaded fields multiple times. Maybe we should change to an approach where we iterate the object graph only once.
+ * @todo Context root bean can be a different object than the current Validator<T> hence two different generics variables
+ */
+ private <T> List<ConstraintViolationImpl<T>> validateInContext(ValidationContext<T> context, List<Class<?>> groups) {
+ if ( context.peekValidatedObject() == null ) {
+ return Collections.emptyList();
+ }
+
+ // if no group is specified use the default
+ if ( groups.size() == 0 ) {
+ groups = Arrays.asList( DEFAULT_GROUP );
+ }
+
+ List<Class<?>> expandedGroups;
+ boolean isGroupSequence;
+ for ( Class<?> group : groups ) {
+ expandedGroups = new ArrayList<Class<?>>();
+ isGroupSequence = expandGroup( context.peekValidatedObjectType(), group, expandedGroups );
+
+ for ( Class<?> expandedGroupName : expandedGroups ) {
+ context.setCurrentGroup( expandedGroupName );
+
+ validateConstraints( context );
+ validateCascadedConstraints( context );
+
+ if ( isGroupSequence && context.getFailingConstraints().size() > 0 ) {
+ break;
+ }
+ }
+ }
+ return context.getFailingConstraints();
+ }
+
+ /**
+ * Validates the non-cascaded constraints.
+ *
+ * @param validationContext The current validation context.
+ */
+ private <T> void validateConstraints(ValidationContext<T> validationContext) {
+ //casting rely on the fact that root object is at the top of the stack
+ @SuppressWarnings("unchecked")
+ BeanMetaData<T> beanMetaData =
+ ( BeanMetaData<T> ) getBeanMetaData( validationContext.peekValidatedObjectType() );
+ for ( MetaConstraint metaConstraint : beanMetaData.geMetaConstraintList() ) {
+ ConstraintDescriptor mainConstraintDescriptor = metaConstraint.getDescriptor();
+
+ validationContext.pushProperty( metaConstraint.getPropertyName() );
+
+ if ( !validationContext.needsValidation( mainConstraintDescriptor.getGroups() ) ) {
+ validationContext.popProperty();
+ continue;
+ }
+
+ metaConstraint.validateConstraint( beanMetaData.getBeanClass(), validationContext );
+ validationContext.popProperty();
+ }
+ validationContext.markProcessedForCurrentGroup();
+ }
+
+ /**
+ * Called when processing cascaded constraints. This methods inspects the type of the cascaded constraints and in case
+ * of a list or array creates an iterator in order to validate each element.
+ *
+ * @param context the validation context.
+ * @param type the type of the cascaded field or property.
+ * @param value the actual value.
+ */
+ private <T> void validateCascadedConstraint(ValidationContext<T> context, Type type, Object value) {
+ if ( value == null ) {
+ return;
+ }
+
+ Iterator<?> iter;
+ if ( ReflectionHelper.isCollection( type ) ) {
+ boolean isIterable = value instanceof Iterable;
+ Map<?, ?> map = !isIterable ? ( Map<?, ?> ) value : null;
+ Iterable<?> elements = isIterable ?
+ ( Iterable<?> ) value :
+ map.entrySet();
+ iter = elements.iterator();
+ context.appendIndexToPropertyPath( "[{0}]" );
+ }
+ else if ( ReflectionHelper.isArray( type ) ) {
+ List<?> arrayList = Arrays.asList( value );
+ iter = arrayList.iterator();
+ context.appendIndexToPropertyPath( "[{0}]" );
+ }
+ else {
+ List<Object> list = new ArrayList<Object>();
+ list.add( value );
+ iter = list.iterator();
+ }
+
+ validateCascadedConstraint( context, iter );
+ }
+
+ private <T> void validateCascadedConstraints(ValidationContext<T> context) {
+ List<Member> cascadedMembers = getBeanMetaData( context.peekValidatedObjectType() )
+ .getCascadedMembers();
+ for ( Member member : cascadedMembers ) {
+ Type type = ReflectionHelper.typeOf( member );
+ context.pushProperty( ReflectionHelper.getPropertyName( member ) );
+ Object value = ReflectionHelper.getValue( member, context.peekValidatedObject() );
+ validateCascadedConstraint( context, type, value );
+ context.popProperty();
+ }
+ }
+
+ private <T> void validateCascadedConstraint(ValidationContext<T> context, Iterator<?> iter) {
+ Object actualValue;
+ String propertyIndex;
+ int i = 0;
+ while ( iter.hasNext() ) {
+ actualValue = iter.next();
+ propertyIndex = String.valueOf( i );
+ if ( actualValue instanceof Map.Entry ) {
+ Object key = ( ( Map.Entry ) actualValue ).getKey();
+ if ( INDEXABLE_CLASS.contains( key.getClass() ) ) {
+ propertyIndex = key.toString();
+ }
+ actualValue = ( ( Map.Entry ) actualValue ).getValue();
+ }
+
+ if ( context.isProcessedForCurrentGroup( actualValue ) ) {
+ i++;
+ continue;
+ }
+
+ context.replacePropertyIndex( propertyIndex );
+
+ context.pushValidatedObject( actualValue );
+ validateInContext( context, Arrays.asList( new Class<?>[] { context.getCurrentGroup() } ) );
+ context.popValidatedObject();
+ i++;
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public <T> Set<ConstraintViolation<T>> validateProperty(T object, String propertyName, Class<?>... groups) {
+ List<ConstraintViolationImpl<T>> failingConstraintViolations = new ArrayList<ConstraintViolationImpl<T>>();
+ validateProperty( object, new PropertyIterator( propertyName ), failingConstraintViolations, groups );
+ return new HashSet<ConstraintViolation<T>>( failingConstraintViolations );
+ }
+
+ private <T> void validateProperty(T object, PropertyIterator propertyIter, List<ConstraintViolationImpl<T>> failingConstraintViolations, Class<?>... groups) {
+ if ( object == null ) {
+ throw new IllegalArgumentException( "Validated object cannot be null" );
+ }
+ @SuppressWarnings("unchecked")
+ final Class<T> beanType = ( Class<T> ) object.getClass();
+
+ Set<MetaConstraint> metaConstraints = new HashSet<MetaConstraint>();
+ getMetaConstraintsForPath( beanType, propertyIter, metaConstraints );
+
+ if ( metaConstraints.size() == 0 ) {
+ return;
+ }
+
+ // if no group is specified use the default
+ if ( groups.length == 0 ) {
+ groups = DEFAULT_GROUP;
+ }
+
+ List<Class<?>> expandedGroups;
+ boolean isGroupSequence;
+ for ( Class<?> group : groups ) {
+ expandedGroups = new ArrayList<Class<?>>();
+ isGroupSequence = expandGroup( beanType, group, expandedGroups );
+
+ for ( Class<?> expandedGroup : expandedGroups ) {
+
+ for ( MetaConstraint metaConstraint : metaConstraints ) {
+ if ( !metaConstraint.getDescriptor().getGroups().contains( expandedGroup ) ) {
+ continue;
+ }
+
+ ValidationContext<T> context = new ValidationContext<T>( object, messageInterpolator, constraintValidatorFactory );
+ metaConstraint.validateConstraint( object.getClass(), context );
+ failingConstraintViolations.addAll( context.getFailingConstraints() );
+ }
+
+ if ( isGroupSequence && failingConstraintViolations.size() > 0 ) {
+ break;
+ }
+ }
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public <T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups) {
+ List<ConstraintViolationImpl<T>> failingConstraintViolations = new ArrayList<ConstraintViolationImpl<T>>();
+ validateValue( beanType, value, new PropertyIterator( propertyName ), failingConstraintViolations, groups );
+ return new HashSet<ConstraintViolation<T>>( failingConstraintViolations );
+ }
+
+ public BeanDescriptor getConstraintsForClass(Class<?> clazz) {
+ return getBeanMetaData( clazz ).getBeanDescriptor();
+ }
+
+ private <T> void validateValue(Class<T> beanType, Object value, PropertyIterator propertyIter, List<ConstraintViolationImpl<T>> failingConstraintViolations, Class<?>... groups) {
+ Set<MetaConstraint> metaConstraints = new HashSet<MetaConstraint>();
+ getMetaConstraintsForPath( beanType, propertyIter, metaConstraints );
+
+ if ( metaConstraints.size() == 0 ) {
+ return;
+ }
+
+ // if no group is specified use the default
+ if ( groups.length == 0 ) {
+ groups = DEFAULT_GROUP;
+ }
+
+ List<Class<?>> expandedGroups;
+ boolean isGroupSequence;
+ for ( Class<?> group : groups ) {
+ expandedGroups = new ArrayList<Class<?>>();
+ isGroupSequence = expandGroup( beanType, group, expandedGroups );
+
+ for ( Class<?> expandedGroup : expandedGroups ) {
+
+ for ( MetaConstraint metaConstraint : metaConstraints ) {
+ if ( !metaConstraint.getDescriptor().getGroups().contains( expandedGroup ) ) {
+ continue;
+ }
+
+ ValidationContext<T> context = new ValidationContext<T>( ( T ) value, messageInterpolator, constraintValidatorFactory );
+ context.pushProperty( propertyIter.getOriginalProperty() );
+ metaConstraint.validateConstraint( beanType, value, context );
+ failingConstraintViolations.addAll( context.getFailingConstraints() );
+ }
+
+ if ( isGroupSequence && failingConstraintViolations.size() > 0 ) {
+ break;
+ }
+ }
+ }
+ }
+
+ /**
+ * Collects all <code>MetaConstraint</code>s which match the given path relative to the specified root class.
+ * <p>
+ * This method does not traverse an actual object, but rather tries to resolve the porperty generically.
+ * </p>
+ * <p>
+ * This method is called recursively. Only if there is a valid 'validation path' through the object graph
+ * a constraint descriptor will be returned.
+ * </p>
+ *
+ * @param clazz the class type to check for constraints.
+ * @param propertyIter an instance of <code>PropertyIterator</code>
+ * @param metaConstraints Set of <code>MetaConstraint</code>s to collect all matching constraints.
+ */
+ private void getMetaConstraintsForPath(Class<?> clazz, PropertyIterator propertyIter, Set<MetaConstraint> metaConstraints) {
+ propertyIter.split();
+
+ if ( !propertyIter.hasNext() ) {
+ List<MetaConstraint> metaConstraintList = getBeanMetaData( clazz ).geMetaConstraintList();
+ for ( MetaConstraint metaConstraint : metaConstraintList ) {
+ if ( metaConstraint.getPropertyName().equals( propertyIter.getHead() ) ) {
+ metaConstraints.add( metaConstraint );
+ }
+ }
+ }
+ else {
+ List<Member> cascadedMembers = getBeanMetaData( clazz ).getCascadedMembers();
+ for ( Member m : cascadedMembers ) {
+ if ( ReflectionHelper.getPropertyName( m ).equals( propertyIter.getHead() ) ) {
+ Type type = ReflectionHelper.typeOf( m );
+
+ if ( propertyIter.isIndexed() ) {
+ type = ReflectionHelper.getIndexedType( type );
+ if ( type == null ) {
+ continue;
+ }
+ }
+ getMetaConstraintsForPath( ( Class<?> ) type, propertyIter, metaConstraints );
+ }
+ }
+ }
+ }
+
+ /**
+ * Checks whether the provided group name is a group sequence and if so expands the group name and add the expanded
+ * groups names to <code>expandedGroupName</code>.
+ *
+ * @param beanType The class for which to expand the group names.
+ * @param group The group to expand
+ * @param expandedGroups The exanded group names or just a list with the single provided group name id the name
+ * was not expandable
+ *
+ * @return <code>true</code> if an expansion took place, <code>false</code> otherwise.
+ */
+ private <T> boolean expandGroup(Class<T> beanType, Class<?> group, List<Class<?>> expandedGroups) {
+ if ( expandedGroups == null ) {
+ throw new IllegalArgumentException( "List cannot be empty" );
+ }
+
+ boolean isGroupSequence;
+ BeanMetaData<T> metaDataProvider = getBeanMetaData( beanType );
+ if ( metaDataProvider.getGroupSequences().containsKey( group ) ) {
+ expandedGroups.addAll( metaDataProvider.getGroupSequences().get( group ) );
+ isGroupSequence = true;
+ }
+ else {
+ expandedGroups.add( group );
+ isGroupSequence = false;
+ }
+ return isGroupSequence;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ private <T> BeanMetaDataImpl<T> getBeanMetaData(Class<T> beanClass) {
+ if ( beanClass == null ) {
+ throw new IllegalArgumentException( "Class cannot be null" );
+ }
+ @SuppressWarnings("unchecked")
+ BeanMetaDataImpl<T> metadata = ( BeanMetaDataImpl<T> ) metadataProviders.get( beanClass );
+ if ( metadata == null ) {
+ metadata = new BeanMetaDataImpl<T>( beanClass );
+ metadataProviders.put( beanClass, metadata );
+ }
+ return metadata;
+ }
+}
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/BeanDescriptorImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/BeanDescriptorImpl.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/BeanDescriptorImpl.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -1,35 +0,0 @@
-package org.hibernate.validation.impl;
-
-import java.util.Set;
-import java.util.Collections;
-import javax.validation.BeanDescriptor;
-import javax.validation.PropertyDescriptor;
-
-import org.hibernate.validation.engine.BeanMetaData;
-
-/**
- * @author Emmanuel Bernard
- */
-public class BeanDescriptorImpl<T> extends ElementDescriptorImpl implements BeanDescriptor {
- private final BeanMetaData<T> metadataBean;
-
- public BeanDescriptorImpl(Class<T> returnType, BeanMetaData<T> metadataBean) {
- super(returnType, false, "");
- this.metadataBean = metadataBean;
- }
-
- /**
- * @todo add child validation
- */
- public boolean isBeanConstrained() {
- return metadataBean.geMetaConstraintList().size() > 0;
- }
-
- public PropertyDescriptor getConstraintsForProperty(String propertyName) {
- return metadataBean.getPropertyDescriptors().get( propertyName );
- }
-
- public Set<String> getConstrainedProperties() {
- return Collections.unmodifiableSet( metadataBean.getPropertyDescriptors().keySet() );
- }
-}
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ConfigurationImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ConfigurationImpl.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ConfigurationImpl.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -1,145 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.validation.impl;
-
-import java.io.InputStream;
-import java.util.List;
-import javax.validation.ConstraintValidatorFactory;
-import javax.validation.MessageInterpolator;
-import javax.validation.TraversableResolver;
-import javax.validation.ValidationException;
-import javax.validation.ValidationProviderResolver;
-import javax.validation.ValidatorFactory;
-import javax.validation.Configuration;
-import javax.validation.bootstrap.DefaultValidationProviderResolver;
-import javax.validation.spi.BootstrapState;
-import javax.validation.spi.ValidationProvider;
-import javax.validation.spi.ConfigurationState;
-
-import org.hibernate.validation.HibernateValidatorConfiguration;
-import org.hibernate.validation.Version;
-
-/**
- * @author Emmanuel Bernard
- */
-public class ConfigurationImpl implements HibernateValidatorConfiguration, ConfigurationState {
-
- static {
- Version.touch();
- }
-
- //FIXME not sure why it is like that. We should cache these instances somehow. Static?
- private final MessageInterpolator defaultMessageInterpolator = new ResourceBundleMessageInterpolator();
- private final TraversableResolver defaultTraversableResolver = new DefaultTraversableResolver();
-
- private MessageInterpolator messageInterpolator;
- private ConstraintValidatorFactory constraintValidatorFactory = new ConstraintValidatorFactoryImpl();
- private String configurationFile = "META-INF/validation.xml";
- private final ValidationProvider provider;
- private final ValidationProviderResolver providerResolver;
- private TraversableResolver traversableResolver;
-
- public ConfigurationImpl(BootstrapState state) {
- if ( state.getValidationProviderResolver() == null ) {
- this.providerResolver = new DefaultValidationProviderResolver();
- }
- else {
- this.providerResolver = state.getValidationProviderResolver();
- }
- this.provider = null;
- this.messageInterpolator = defaultMessageInterpolator;
- this.traversableResolver = defaultTraversableResolver;
- }
-
- public ConfigurationImpl(ValidationProvider provider) {
- if ( provider == null ) {
- throw new ValidationException( "Assertion error: inconsistent ConfigurationImpl construction" );
- }
- this.provider = provider;
- this.providerResolver = null;
- this.messageInterpolator = defaultMessageInterpolator;
- this.traversableResolver = defaultTraversableResolver;
- }
-
- public ConfigurationImpl messageInterpolator(MessageInterpolator interpolator) {
- this.messageInterpolator = interpolator;
- return this;
- }
-
- public ConfigurationImpl traversableResolver(TraversableResolver resolver) {
- this.traversableResolver = resolver;
- return this;
- }
-
- public ConfigurationImpl constraintValidatorFactory(ConstraintValidatorFactory constraintValidatorFactory) {
- this.constraintValidatorFactory = constraintValidatorFactory;
- return this;
- }
-
- public ValidatorFactory buildValidatorFactory() {
- if ( isSpecificProvider() ) {
- return provider.buildValidatorFactory( this );
- }
- else {
- //read provider name from configuration
- Class<? extends Configuration<?>> providerClass = null;
-
- if ( providerClass != null ) {
- for ( ValidationProvider provider : providerResolver.getValidationProviders() ) {
- if ( provider.isSuitable( providerClass ) ) {
- return provider.buildValidatorFactory( this );
- }
- }
- throw new ValidationException( "Unable to find provider: " + providerClass );
- }
- else {
- List<ValidationProvider> providers = providerResolver.getValidationProviders();
- assert providers.size() != 0; //I run therefore I am
- return providers.get( 0 ).buildValidatorFactory( this );
- }
- }
- }
-
- private boolean isSpecificProvider() {
- return provider != null;
- }
-
- public MessageInterpolator getMessageInterpolator() {
- return messageInterpolator;
- }
-
- public ConstraintValidatorFactory getConstraintValidatorFactory() {
- return constraintValidatorFactory;
- }
-
- public TraversableResolver getTraversableResolver() {
- return traversableResolver;
- }
-
- public ConfigurationImpl customConfiguration(InputStream stream) {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public MessageInterpolator getDefaultMessageInterpolator() {
- return defaultMessageInterpolator;
- }
-
- public InputStream getConfigurationStream() {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-}
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ConstraintDescriptorImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ConstraintDescriptorImpl.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ConstraintDescriptorImpl.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -1,298 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.validation.impl;
-
-import java.lang.annotation.Annotation;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.List;
-import javax.validation.ConstraintValidator;
-import javax.validation.ConstraintDescriptor;
-import javax.validation.Constraint;
-import javax.validation.OverridesParameter;
-import javax.validation.OverridesParameters;
-import javax.validation.ReportAsViolationFromCompositeConstraint;
-import javax.validation.ValidationException;
-import javax.validation.groups.Default;
-
-import org.slf4j.Logger;
-
-import org.hibernate.validation.util.LoggerFactory;
-import org.hibernate.validation.util.ReflectionHelper;
-import org.hibernate.validation.util.annotationfactory.AnnotationFactory;
-import org.hibernate.validation.util.annotationfactory.AnnotationDescriptor;
-
-/**
- * Describe a single constraint.
- *
- * @author Emmanuel Bernard
- * @author Hardy Ferentschik
- */
-public class ConstraintDescriptorImpl<U extends Annotation> implements ConstraintDescriptor {
- private static final Logger log = LoggerFactory.make();
- private static final Class<?>[] DEFAULT_GROUP = new Class<?>[] { Default.class };
- private static final int OVERRIDES_PARAMETER_DEFAULT_INDEX = -1;
-
- private final U annotation;
- private final Class<? extends ConstraintValidator<U,?>>[] constraintClasses;
- private final Set<Class<?>> groups;
- private final Map<String, Object> parameters;
- private final Set<ConstraintDescriptor> composingConstraints = new HashSet<ConstraintDescriptor>();
- private final Map<ClassIndexWrapper, Map<String, Object>> overrideParameters = new HashMap<ClassIndexWrapper, Map<String, Object>>();
- private final boolean isReportAsSingleInvalidConstraint;
-
- public ConstraintDescriptorImpl(U annotation, Class<?>[] groups) {
- this( annotation, new HashSet<Class<?>>() );
- if ( groups.length == 0 ) {
- groups = DEFAULT_GROUP;
- }
- this.groups.addAll( Arrays.asList( groups ) );
- }
-
- public ConstraintDescriptorImpl(U annotation, Set<Class<?>> groups) {
- this.annotation = annotation;
- this.groups = groups;
- this.parameters = getAnnotationParameters( annotation );
-
- this.isReportAsSingleInvalidConstraint = annotation.annotationType().isAnnotationPresent(
- ReportAsViolationFromCompositeConstraint.class
- );
-
-
- if ( ReflectionHelper.isBuiltInConstraintAnnotation( annotation ) ) {
- this.constraintClasses = (Class<? extends ConstraintValidator<U,?>>[])
- ReflectionHelper.getBuiltInConstraints( annotation );
- }
- else {
- Constraint constraint = annotation.annotationType()
- .getAnnotation( Constraint.class );
- this.constraintClasses = (Class<? extends ConstraintValidator<U,?>>[])
- constraint.validatedBy();
- }
-
- parseOverrideParameters();
- parseComposingConstraints();
- }
-
- /**
- * {@inheritDoc}
- */
- public U getAnnotation() {
- return annotation;
- }
-
- /**
- * {@inheritDoc}
- */
- public Set<Class<?>> getGroups() {
- return groups;
- }
-
- /**
- * {@inheritDoc}
- */
- public Class<? extends ConstraintValidator<U,?>>[]
- getConstraintValidatorClasses() {
- return constraintClasses;
- }
-
- /**
- * {@inheritDoc}
- */
- public Map<String, Object> getParameters() {
- return parameters;
- }
-
- /**
- * {@inheritDoc}
- */
- public Set<ConstraintDescriptor> getComposingConstraints() {
- return composingConstraints;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isReportAsViolationFromCompositeConstraint() {
- return isReportAsSingleInvalidConstraint;
- }
-
- @Override
- public String toString() {
- return "ConstraintDescriptorImpl{" +
- "annotation=" + annotation +
- ", constraintClasses=" + constraintClasses +
- ", groups=" + groups +
- ", parameters=" + parameters +
- ", composingConstraints=" + composingConstraints +
- ", isReportAsSingleInvalidConstraint=" + isReportAsSingleInvalidConstraint +
- '}';
- }
-
- private Map<String, Object> getAnnotationParameters(Annotation annotation) {
- Method[] declaredMethods = annotation.annotationType().getDeclaredMethods();
- Map<String, Object> parameters = new HashMap<String, Object>( declaredMethods.length );
- for ( Method m : declaredMethods ) {
- try {
- parameters.put( m.getName(), m.invoke( annotation ) );
- }
- catch ( IllegalAccessException e ) {
- throw new ValidationException( "Unable to read annotation parameters: " + annotation.getClass(), e );
- }
- catch ( InvocationTargetException e ) {
- throw new ValidationException( "Unable to read annotation parameters: " + annotation.getClass(), e );
- }
- }
- return Collections.unmodifiableMap( parameters );
- }
-
- private void addOverrideParameter(Map<ClassIndexWrapper, Map<String, Object>> overrideParameters, Object value, OverridesParameter... parameters) {
-
- for ( OverridesParameter parameter : parameters ) {
- ClassIndexWrapper wrapper = new ClassIndexWrapper( parameter.constraint(), parameter.index() );
- Map<String, Object> map = overrideParameters.get( wrapper );
- if ( map == null ) {
- map = new HashMap<String, Object>();
- overrideParameters.put( wrapper, map );
- }
- map.put( parameter.parameter(), value );
- }
- }
-
- private Object getMethodValue(Annotation annotation, Method m) {
- Object value;
- try {
- value = m.invoke( annotation );
- }
- // should never happen
- catch ( IllegalAccessException e ) {
- throw new ValidationException( "Unable to retrieve annotation parameter value." );
- }
- catch ( InvocationTargetException e ) {
- throw new ValidationException( "Unable to retrieve annotation parameter value." );
- }
- return value;
- }
-
- private void parseOverrideParameters() {
- // check for overrides
- for ( Method m : annotation.annotationType().getMethods() ) {
- if ( m.getAnnotation( OverridesParameter.class ) != null ) {
- addOverrideParameter(
- overrideParameters, getMethodValue( annotation, m ), m.getAnnotation( OverridesParameter.class )
- );
- }
- else if ( m.getAnnotation( OverridesParameters.class ) != null ) {
- addOverrideParameter(
- overrideParameters,
- getMethodValue( annotation, m ),
- m.getAnnotation( OverridesParameters.class ).value()
- );
- }
- }
- }
-
- private void parseComposingConstraints() {
- for ( Annotation declaredAnnotation : annotation.annotationType().getDeclaredAnnotations() ) {
- if ( ReflectionHelper.isConstraintAnnotation( declaredAnnotation ) || ReflectionHelper.isBuiltInConstraintAnnotation(
- declaredAnnotation
- ) ) {
- ConstraintDescriptorImpl descriptor = createComposingConstraintDescriptor(
- OVERRIDES_PARAMETER_DEFAULT_INDEX,
- declaredAnnotation
- );
- composingConstraints.add( descriptor );
- log.debug( "Adding composing constraint: " + descriptor );
- }
- else if ( ReflectionHelper.isMultiValueConstraint( declaredAnnotation ) ) {
- List<Annotation> multiValueConstraints = ReflectionHelper.getMultiValueConstraints( declaredAnnotation );
- int index = 1;
- for ( Annotation constraintAnnotation : multiValueConstraints ) {
- ConstraintDescriptorImpl descriptor = createComposingConstraintDescriptor(
- index, constraintAnnotation
- );
- composingConstraints.add( descriptor );
- log.debug( "Adding composing constraint: " + descriptor );
- index++;
- }
- }
- }
- }
-
- private ConstraintDescriptorImpl createComposingConstraintDescriptor(int index, Annotation constraintAnnotation) {
- AnnotationDescriptor annotationDescriptor = new AnnotationDescriptor(
- constraintAnnotation.annotationType(), getAnnotationParameters( constraintAnnotation )
- );
- Map<String, Object> overrides = overrideParameters.get(
- new ClassIndexWrapper(
- constraintAnnotation.annotationType(), index
- )
- );
- if ( overrides != null ) {
- for ( Map.Entry<String, Object> entry : overrides.entrySet() ) {
- annotationDescriptor.setValue( entry.getKey(), entry.getValue() );
- }
- }
- Annotation annotationProxy = AnnotationFactory.create( annotationDescriptor );
- return new ConstraintDescriptorImpl( annotationProxy, groups );
- }
-
- private class ClassIndexWrapper {
- final Class<?> clazz;
- final int index;
-
- ClassIndexWrapper(Class<?> clazz, int index) {
- this.clazz = clazz;
- this.index = index;
- }
-
- @Override
- public boolean equals(Object o) {
- if ( this == o ) {
- return true;
- }
- if ( o == null || getClass() != o.getClass() ) {
- return false;
- }
-
- ClassIndexWrapper that = ( ClassIndexWrapper ) o;
-
- if ( index != that.index ) {
- return false;
- }
- if ( clazz != null ? !clazz.equals( that.clazz ) : that.clazz != null ) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = clazz != null ? clazz.hashCode() : 0;
- result = 31 * result + index;
- return result;
- }
- }
-}
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ConstraintValidatorFactoryImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ConstraintValidatorFactoryImpl.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ConstraintValidatorFactoryImpl.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -1,46 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.validation.impl;
-
-import java.lang.annotation.Annotation;
-import javax.validation.ConstraintValidator;
-import javax.validation.ConstraintValidatorFactory;
-import javax.validation.ValidationException;
-
-/**
- * Default <code>ConstraintValidatorFactory</code> using a no-arg constructor.
- *
- * @author Emmanuel Bernard
- */
-public class ConstraintValidatorFactoryImpl implements ConstraintValidatorFactory {
-
- /**
- * {@inheritDoc}
- */
- public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
- try {
- return key.newInstance();
- }
- catch ( InstantiationException e ) {
- throw new ValidationException( "Unable to instanciate " + key, e );
- }
- catch ( IllegalAccessException e ) {
- throw new ValidationException( "Unable to instanciate " + key, e );
- }
- }
-}
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ConstraintViolationImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ConstraintViolationImpl.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ConstraintViolationImpl.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -1,146 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.validation.impl;
-
-import java.util.HashSet;
-import java.util.Set;
-import javax.validation.ConstraintViolation;
-import javax.validation.ConstraintDescriptor;
-
-/**
- * @author Emmanuel Bernard
- * @author Hardy Ferentschik
- */
-public class ConstraintViolationImpl<T> implements ConstraintViolation<T> {
- private String interpolatedMessage;
- private T rootBean;
- private Class<T> beanClass;
- private Object value;
- private String propertyPath;
- private Set<Class<?>> groups;
- private Object leafBeanInstance;
- private final ConstraintDescriptor constraintDescriptor;
- private String rawMessage;
-
-
- public ConstraintViolationImpl(String rawMessage, String interpolatedMessage, T rootBean, Class<T> beanClass,
- Object leafBeanInstance, Object value,
- String propertyPath, Class<?> group, ConstraintDescriptor constraintDescriptor) {
- this.rawMessage = rawMessage;
- this.interpolatedMessage = interpolatedMessage;
- this.rootBean = rootBean;
- this.beanClass = beanClass;
- this.value = value;
- this.propertyPath = propertyPath;
- groups = new HashSet<Class<?>>();
- groups.add( group );
- this.leafBeanInstance = leafBeanInstance;
- this.constraintDescriptor = constraintDescriptor;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getInterpolatedMessage() {
- return interpolatedMessage;
- }
-
- public String getRawMessage() {
- return rawMessage;
- }
-
- /**
- * {@inheritDoc}
- */
- public T getRootBean() {
- return rootBean;
- }
-
- public Object getLeafBean() {
- return leafBeanInstance;
- }
-
- /**
- * {@inheritDoc}
- */
- public Object getInvalidValue() {
- return value;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getPropertyPath() {
- return propertyPath;
- }
-
- /**
- * {@inheritDoc}
- */
- public Set<Class<?>> getGroups() {
- return groups;
- }
-
- public ConstraintDescriptor getConstraintDescriptor() {
- return this.constraintDescriptor;
- }
-
- public void addGroups(Set<Class<?>> groupSet) {
- groups.addAll( groupSet );
- }
-
- @Override
- public boolean equals(Object o) {
- if ( this == o ) {
- return true;
- }
- if ( !( o instanceof ConstraintViolationImpl ) ) {
- return false;
- }
-
- ConstraintViolationImpl that = ( ConstraintViolationImpl ) o;
-
- if ( beanClass != null ? !beanClass.equals( that.beanClass ) : that.beanClass != null ) {
- return false;
- }
- if ( interpolatedMessage != null ? !interpolatedMessage.equals( that.interpolatedMessage ) : that.interpolatedMessage != null ) {
- return false;
- }
- if ( propertyPath != null ? !propertyPath.equals( that.propertyPath ) : that.propertyPath != null ) {
- return false;
- }
- if ( rootBean != null ? !rootBean.equals( that.rootBean ) : that.rootBean != null ) {
- return false;
- }
- if ( value != null ? !value.equals( that.value ) : that.value != null ) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = interpolatedMessage != null ? interpolatedMessage.hashCode() : 0;
- result = 31 * result + ( rootBean != null ? rootBean.hashCode() : 0 );
- result = 31 * result + ( beanClass != null ? beanClass.hashCode() : 0 );
- result = 31 * result + ( value != null ? value.hashCode() : 0 );
- result = 31 * result + ( propertyPath != null ? propertyPath.hashCode() : 0 );
- return result;
- }
-}
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/DefaultTraversableResolver.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/DefaultTraversableResolver.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/DefaultTraversableResolver.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -1,13 +0,0 @@
-package org.hibernate.validation.impl;
-
-import java.lang.annotation.ElementType;
-import javax.validation.TraversableResolver;
-
-/**
- * @author Emmanuel Bernard
- */
-public class DefaultTraversableResolver implements TraversableResolver {
- public boolean isTraversable(Object traversableObject, String traversableProperty, Class<?> rootBeanType, String pathToTraversableObject, ElementType elementType) {
- return true;
- }
-}
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ElementDescriptorImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ElementDescriptorImpl.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ElementDescriptorImpl.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -1,90 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.validation.impl;
-
-import java.lang.annotation.ElementType;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-import java.util.HashSet;
-import javax.validation.ConstraintDescriptor;
-import javax.validation.ElementDescriptor;
-import javax.validation.BeanDescriptor;
-import javax.validation.PropertyDescriptor;
-
-/**
- * Describe a validated element (class, field or property).
- *
- * @author Emmanuel Bernard
- * @author Hardy Ferentschik
- * @todo Should returnType be renamed to type?
- * @todo Handle problem in descirbing cyclic dependecies for propertyPath
- */
-//FIXME I implement both interfaces on the same object as a quick hack, we need to fix that.
-public class ElementDescriptorImpl implements PropertyDescriptor {
- private final Class<?> returnType;
- private final boolean cascaded;
- private final Set<ConstraintDescriptor> constraintDescriptors = new HashSet<ConstraintDescriptor>();
- private final String propertyPath;
-
-
- public ElementDescriptorImpl(Class<?> returnType, boolean cascaded, String propertyPath) {
- this.returnType = returnType;
- this.cascaded = cascaded;
- this.propertyPath = propertyPath;
- }
-
- public void addConstraintDescriptor(ConstraintDescriptorImpl constraintDescriptor) {
- constraintDescriptors.add( constraintDescriptor );
- }
-
- public boolean hasConstraints() {
- return constraintDescriptors.size() != 0;
- }
-
- /**
- * {@inheritDoc}
- *
- * @todo Generic type or regular type?
- */
- public Class getType() {
- return returnType;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isCascaded() {
- return cascaded;
- }
-
- /**
- * {@inheritDoc}
- */
- public Set<ConstraintDescriptor> getConstraintDescriptors() {
- return Collections.unmodifiableSet( constraintDescriptors );
- }
-
- /**
- * {@inheritDoc}
- */
- public String getPropertyName() {
- return propertyPath;
- }
-}
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/HibernateValidationProvider.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/HibernateValidationProvider.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/HibernateValidationProvider.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -1,67 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.validation.impl;
-
-import javax.validation.ValidationException;
-import javax.validation.Configuration;
-import javax.validation.ValidatorFactory;
-import javax.validation.spi.ValidationProvider;
-import javax.validation.spi.ConfigurationState;
-import javax.validation.spi.BootstrapState;
-
-import org.hibernate.validation.HibernateValidatorConfiguration;
-
-/**
- * Default implementation of <code>ValidationProvider</code> within Hibernate validator.
- *
- * @author Emmanuel Bernard
- * @author Hardy Ferentschik
- */
-public class HibernateValidationProvider implements ValidationProvider {
-
- /**
- * {@inheritDoc}
- */
- public boolean isSuitable(Class<? extends Configuration<?>> builderClass) {
- return builderClass == HibernateValidatorConfiguration.class;
- }
-
- public <T extends Configuration<T>> T createSpecializedConfiguration(BootstrapState state, Class<T> configurationClass) {
- if ( !isSuitable( configurationClass ) ) {
- throw new ValidationException(
- "Illegal call to createSpecializedConfiguration() for a non suitable provider"
- );
- }
- //cast protected by isSuitable call
- return configurationClass.cast( new ConfigurationImpl( this ) );
- }
-
- /**
- * {@inheritDoc}
- */
- public Configuration<?> createGenericConfiguration(BootstrapState state) {
- return new ConfigurationImpl( state );
- }
-
- /**
- * {@inheritDoc}
- */
- public ValidatorFactory buildValidatorFactory(ConfigurationState configurationState) {
- return new ValidatorFactoryImpl( configurationState );
- }
-}
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ResourceBundleMessageInterpolator.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ResourceBundleMessageInterpolator.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ResourceBundleMessageInterpolator.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -1,155 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.validation.impl;
-
-import java.util.Locale;
-import java.util.Map;
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import javax.validation.ConstraintDescriptor;
-import javax.validation.MessageInterpolator;
-
-import org.slf4j.Logger;
-
-import org.hibernate.validation.util.LoggerFactory;
-
-
-/**
- * Resource bundle backed message interpolator.
- *
- * @author Emmanuel Bernard
- */
-public class ResourceBundleMessageInterpolator implements MessageInterpolator {
- private static final String DEFAULT_VALIDATION_MESSAGES = "org.hibernate.validation.ValidationMessages";
- private static final String USER_VALIDATION_MESSAGES = "ValidationMessages";
- private static final Logger log = LoggerFactory.make();
-
- /**
- * Regular expression used to do message interpolation.
- */
- private static final Pattern messagePattern = Pattern.compile( "\\{([\\w\\.]+)\\}" );
- private ResourceBundle defaultResourceBundle;
- private ResourceBundle userResourceBundle;
-
- public ResourceBundleMessageInterpolator() {
- userResourceBundle = getFileBasedResourceBundle();
- defaultResourceBundle = ResourceBundle.getBundle( DEFAULT_VALIDATION_MESSAGES );
- }
-
- public ResourceBundleMessageInterpolator(ResourceBundle resourceBundle) {
- if ( resourceBundle == null ) {
- userResourceBundle = getFileBasedResourceBundle();
- }
- else {
- this.userResourceBundle = resourceBundle;
- }
- defaultResourceBundle = ResourceBundle.getBundle( DEFAULT_VALIDATION_MESSAGES );
- }
-
- /**
- * Search current thread classloader for the resource bundle. If not found, search validator (this) classloader.
- *
- * @return the resource bundle or <code>null</code> if none is found.
- */
- private ResourceBundle getFileBasedResourceBundle() {
- ResourceBundle rb = null;
- ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
- if ( classLoader != null ) {
- rb = loadBundle( classLoader, USER_VALIDATION_MESSAGES + " not found by thread local classloader" );
- }
- if ( rb == null ) {
- rb = loadBundle(
- this.getClass().getClassLoader(), USER_VALIDATION_MESSAGES + " not found by validator classloader"
- );
- }
- if ( log.isDebugEnabled() ) {
- if ( rb != null ) {
- log.debug( USER_VALIDATION_MESSAGES + " found" );
- }
- else {
- log.debug( USER_VALIDATION_MESSAGES + " not found. Delegating to " + DEFAULT_VALIDATION_MESSAGES );
- }
- }
- return rb;
- }
-
- private ResourceBundle loadBundle(ClassLoader classLoader, String message) {
- ResourceBundle rb = null;
- try {
- rb = ResourceBundle.getBundle( USER_VALIDATION_MESSAGES, Locale.getDefault(), classLoader );
- }
- catch ( MissingResourceException e ) {
- log.trace( message );
- }
- return rb;
- }
-
- public String interpolate(String message, ConstraintDescriptor constraintDescriptor, Object value) {
- //probably no need for caching, but it could be done by parameters since the map
- //is immutable and uniquely built per Validation definition, the comparaison has to be based on == and not equals though
- return replace( message, constraintDescriptor.getParameters() );
- }
-
- public String interpolate(String message, ConstraintDescriptor constraintDescriptor, Object value, Locale locale) {
- throw new UnsupportedOperationException( "Interpolation for Locale. Has to be done." );
- }
-
-
- private String replace(String message, Map<String, Object> parameters) {
- Matcher matcher = messagePattern.matcher( message );
- StringBuffer sb = new StringBuffer();
- while ( matcher.find() ) {
- matcher.appendReplacement( sb, resolveParameter( matcher.group( 1 ), parameters ) );
- }
- matcher.appendTail( sb );
- return sb.toString();
- }
-
-
- private String resolveParameter(String token, Map<String, Object> parameters) {
- Object variable = parameters.get( token );
- if ( variable != null ) {
- return variable.toString();
- }
-
- StringBuffer buffer = new StringBuffer();
- String string = null;
- try {
- string = userResourceBundle != null ? userResourceBundle.getString( token ) : null;
- }
- catch ( MissingResourceException e ) {
- //give a second chance with the default resource bundle
- }
- if ( string == null ) {
- try {
- string = defaultResourceBundle.getString( token );
- }
- catch ( MissingResourceException e ) {
- //return the unchanged string
- buffer.append( "{" ).append( token ).append( '}' );
- }
- }
- if ( string != null ) {
- // call resolve recusively!
- buffer.append( replace( string, parameters ) );
- }
- return buffer.toString();
- }
-}
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ValidatorContextImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ValidatorContextImpl.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ValidatorContextImpl.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -1,53 +0,0 @@
-package org.hibernate.validation.impl;
-
-import javax.validation.MessageInterpolator;
-import javax.validation.TraversableResolver;
-import javax.validation.Validator;
-import javax.validation.ValidatorContext;
-
-import org.hibernate.validation.engine.ValidatorImpl;
-
-/**
- * @author Emmanuel Bernard
- */
-public class ValidatorContextImpl implements ValidatorContext {
- private MessageInterpolator messageInterpolator;
- private TraversableResolver traversableResolver;
- private final MessageInterpolator factoryMessageInterpolator;
- private final TraversableResolver factoryTraversableResolver;
- private final ValidatorFactoryImpl validatorFactory;
-
- public ValidatorContextImpl(ValidatorFactoryImpl validatorFactory,
- MessageInterpolator factoryMessageInterpolator,
- TraversableResolver factoryTraversableResolver) {
- this.validatorFactory = validatorFactory;
- this.factoryMessageInterpolator = factoryMessageInterpolator;
- this.factoryTraversableResolver = factoryTraversableResolver;
- messageInterpolator( factoryMessageInterpolator );
- traversableResolver(factoryTraversableResolver);
- }
-
- public ValidatorContext messageInterpolator(MessageInterpolator messageInterpolator) {
- if ( messageInterpolator == null) {
- this.messageInterpolator = factoryMessageInterpolator;
- }
- else {
- this.messageInterpolator = messageInterpolator;
- }
- return this;
- }
-
- public ValidatorContext traversableResolver(TraversableResolver traversableResolver) {
- if (traversableResolver == null) {
- this.traversableResolver = factoryTraversableResolver;
- }
- else {
- this.traversableResolver = traversableResolver;
- }
- return this;
- }
-
- public Validator getValidator() {
- return new ValidatorImpl( validatorFactory );
- }
-}
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ValidatorFactoryImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ValidatorFactoryImpl.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ValidatorFactoryImpl.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -1,80 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.validation.impl;
-
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import javax.validation.ConstraintValidatorFactory;
-import javax.validation.MessageInterpolator;
-import javax.validation.TraversableResolver;
-import javax.validation.Validator;
-import javax.validation.ValidatorContext;
-import javax.validation.spi.ConfigurationState;
-
-import org.hibernate.validation.engine.BeanMetaDataImpl;
-import org.hibernate.validation.engine.ValidatorFactoryImplementor;
-
-/**
- * @author Emmanuel Bernard
- * @author Hardy Ferentschik
- */
-public class ValidatorFactoryImpl implements ValidatorFactoryImplementor {
-
- private final MessageInterpolator messageInterpolator;
- private final TraversableResolver traversableResolver;
- private final ConstraintValidatorFactory constraintValidatorFactory;
-
- //TODO is there a way to replace ? by so kind of <T> to express the correlation?
- private Map<Class<?>, BeanMetaDataImpl<?>> metadataProviders
- = new ConcurrentHashMap<Class<?>, BeanMetaDataImpl<?>>(10);
-
-
- public ValidatorFactoryImpl(ConfigurationState configurationState) {
- this.messageInterpolator = configurationState.getMessageInterpolator();
- this.constraintValidatorFactory = configurationState.getConstraintValidatorFactory();
- this.traversableResolver = configurationState.getTraversableResolver();
- //do init metadata from XML form
- }
-
- /**
- * {@inheritDoc}
- */
- public Validator getValidator() {
- return usingContext().getValidator();
- }
-
- public MessageInterpolator getMessageInterpolator() {
- return messageInterpolator;
- }
-
- public ValidatorContext usingContext() {
- return new ValidatorContextImpl(this, messageInterpolator, traversableResolver);
- }
-
- public <T> BeanMetaDataImpl<T> getBeanMetaData(Class<T> beanClass) {
- //FIXME make sure a optimized mock is provided when no constraints are present.
- if (beanClass == null) throw new IllegalArgumentException( "Class cannot be null" );
- @SuppressWarnings( "unchecked")
- BeanMetaDataImpl<T> metadata = ( BeanMetaDataImpl<T> ) metadataProviders.get(beanClass);
- if (metadata == null) {
- metadata = new BeanMetaDataImpl<T>(beanClass, messageInterpolator, constraintValidatorFactory );
- metadataProviders.put( beanClass, metadata );
- }
- return metadata;
- }
-}
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ValidatorTypeHelper.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ValidatorTypeHelper.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ValidatorTypeHelper.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -1,112 +0,0 @@
-package org.hibernate.validation.impl;
-
-import java.lang.annotation.Annotation;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-import java.util.HashMap;
-import java.util.Map;
-import javax.validation.ConstraintValidator;
-import javax.validation.ValidationException;
-
-
-/**
- * Helper methods around ConstraintValidator types
- */
-public class ValidatorTypeHelper {
- private static final int VALIDATOR_TYPE_INDEX = 1;
-
- /**
- * for a lsit of validators, return a Map<Class, Class<? extends ConstraintValidator>>
- * The key is the type the validator accepts, the value is the validator class itself
-
- */
- public static Map<Class<?>, Class<? extends ConstraintValidator<? extends Annotation, ?>>>
- getValidatorsTypes(Class<? extends ConstraintValidator<? extends Annotation,?>>[] validators) {
- if (validators == null || validators.length == 0) {
- //TODObe more contextually specific
- throw new ValidationException("No ConstraintValidators associated to @Constraint");
- }
- else {
- Map<Class<?>, Class<? extends ConstraintValidator<? extends Annotation, ?>>> validatorsTypes =
- new HashMap<Class<?>, Class<? extends ConstraintValidator<? extends Annotation, ?>>>();
- for (Class<? extends ConstraintValidator<? extends Annotation,?>> validator : validators) {
- validatorsTypes.put( extractType(validator), validator );
- }
- return validatorsTypes;
- }
- }
-
- private static Class<?> extractType(Class<? extends ConstraintValidator<?,?>> validator) {
-
- Map<Type, Type> resolvedTypes = new HashMap<Type, Type>();
- Type constraintValidatorType = resolveTypes(resolvedTypes, validator);
-
- //we now have all bind from a type to its resolution at one level
-
- //FIXME throw assertion exception if constraintValidatorType == null
- Type validatorType = ( (ParameterizedType) constraintValidatorType ).getActualTypeArguments()[VALIDATOR_TYPE_INDEX];
- while ( resolvedTypes.containsKey( validatorType ) ) {
- validatorType = resolvedTypes.get( validatorType );
- }
- //FIXME raise an exception if validatorType is not a class
- return (Class<?>) validatorType;
- }
-
- //TEst method, remove
- public static Type extractTypeLoose(Class<? extends ConstraintValidator<?,?>> validator) {
-
- Map<Type, Type> resolvedTypes = new HashMap<Type, Type>();
- Type constraintValidatorType = resolveTypes(resolvedTypes, validator);
-
- //we now have all bind from a type to its resolution at one level
-
- //FIXME throw assertion exception if constraintValidatorType == null
- Type validatorType = ( (ParameterizedType) constraintValidatorType ).getActualTypeArguments()[VALIDATOR_TYPE_INDEX];
- while ( resolvedTypes.containsKey( validatorType ) ) {
- validatorType = resolvedTypes.get( validatorType );
- }
- //FIXME raise an exception if validatorType is not a class
- return validatorType;
- }
-
- private static Type resolveTypes(Map<Type, Type> resolvedTypes, Type type) {
- if (type == null) {
- return null;
- }
- else if ( type instanceof Class ) {
- Class<?> clazz = ( Class<?> ) type;
- Type returnedType = resolveTypes(resolvedTypes, clazz.getGenericSuperclass() );
- if (returnedType != null) return returnedType;
- for (Type genericInterface : clazz.getGenericInterfaces() ) {
- returnedType = resolveTypes(resolvedTypes, genericInterface );
- if (returnedType != null) return returnedType;
- }
- }
- else if ( type instanceof ParameterizedType ) {
- ParameterizedType paramType = (ParameterizedType) type;
- if ( ! ( paramType.getRawType() instanceof Class ) ) return null; //don't know what to do here
- Class<?> rawType = (Class<?>) paramType.getRawType();
-
- TypeVariable<?>[] originalTypes = rawType.getTypeParameters();
- Type[] partiallyResolvedTypes = paramType.getActualTypeArguments();
- int nbrOfParams = originalTypes.length;
- for (int i = 0 ; i < nbrOfParams; i++) {
- resolvedTypes.put( originalTypes[i], partiallyResolvedTypes[i] );
- }
-
- if ( rawType.equals( ConstraintValidator.class ) ) {
- //we found our baby
- return type;
- }
- else {
- resolveTypes(resolvedTypes, rawType.getGenericSuperclass() );
- for (Type genericInterface : rawType.getGenericInterfaces() ) {
- resolveTypes(resolvedTypes, genericInterface );
- }
- }
- }
- //else we don't care I think
- return null;
- }
-}
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/ValidatorTypeHelper.java (from rev 15834, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/impl/ValidatorTypeHelper.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/ValidatorTypeHelper.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/ValidatorTypeHelper.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -0,0 +1,112 @@
+package org.hibernate.validation.util;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.lang.reflect.TypeVariable;
+import java.util.HashMap;
+import java.util.Map;
+import javax.validation.ConstraintValidator;
+import javax.validation.ValidationException;
+
+
+/**
+ * Helper methods around ConstraintValidator types
+ */
+public class ValidatorTypeHelper {
+ private static final int VALIDATOR_TYPE_INDEX = 1;
+
+ /**
+ * for a lsit of validators, return a Map<Class, Class<? extends ConstraintValidator>>
+ * The key is the type the validator accepts, the value is the validator class itself
+
+ */
+ public static Map<Class<?>, Class<? extends ConstraintValidator<? extends Annotation, ?>>>
+ getValidatorsTypes(Class<? extends ConstraintValidator<? extends Annotation,?>>[] validators) {
+ if (validators == null || validators.length == 0) {
+ //TODObe more contextually specific
+ throw new ValidationException("No ConstraintValidators associated to @Constraint");
+ }
+ else {
+ Map<Class<?>, Class<? extends ConstraintValidator<? extends Annotation, ?>>> validatorsTypes =
+ new HashMap<Class<?>, Class<? extends ConstraintValidator<? extends Annotation, ?>>>();
+ for (Class<? extends ConstraintValidator<? extends Annotation,?>> validator : validators) {
+ validatorsTypes.put( extractType(validator), validator );
+ }
+ return validatorsTypes;
+ }
+ }
+
+ private static Class<?> extractType(Class<? extends ConstraintValidator<?,?>> validator) {
+
+ Map<Type, Type> resolvedTypes = new HashMap<Type, Type>();
+ Type constraintValidatorType = resolveTypes(resolvedTypes, validator);
+
+ //we now have all bind from a type to its resolution at one level
+
+ //FIXME throw assertion exception if constraintValidatorType == null
+ Type validatorType = ( (ParameterizedType) constraintValidatorType ).getActualTypeArguments()[VALIDATOR_TYPE_INDEX];
+ while ( resolvedTypes.containsKey( validatorType ) ) {
+ validatorType = resolvedTypes.get( validatorType );
+ }
+ //FIXME raise an exception if validatorType is not a class
+ return (Class<?>) validatorType;
+ }
+
+ //TEst method, remove
+ public static Type extractTypeLoose(Class<? extends ConstraintValidator<?,?>> validator) {
+
+ Map<Type, Type> resolvedTypes = new HashMap<Type, Type>();
+ Type constraintValidatorType = resolveTypes(resolvedTypes, validator);
+
+ //we now have all bind from a type to its resolution at one level
+
+ //FIXME throw assertion exception if constraintValidatorType == null
+ Type validatorType = ( (ParameterizedType) constraintValidatorType ).getActualTypeArguments()[VALIDATOR_TYPE_INDEX];
+ while ( resolvedTypes.containsKey( validatorType ) ) {
+ validatorType = resolvedTypes.get( validatorType );
+ }
+ //FIXME raise an exception if validatorType is not a class
+ return validatorType;
+ }
+
+ private static Type resolveTypes(Map<Type, Type> resolvedTypes, Type type) {
+ if (type == null) {
+ return null;
+ }
+ else if ( type instanceof Class ) {
+ Class<?> clazz = ( Class<?> ) type;
+ Type returnedType = resolveTypes(resolvedTypes, clazz.getGenericSuperclass() );
+ if (returnedType != null) return returnedType;
+ for (Type genericInterface : clazz.getGenericInterfaces() ) {
+ returnedType = resolveTypes(resolvedTypes, genericInterface );
+ if (returnedType != null) return returnedType;
+ }
+ }
+ else if ( type instanceof ParameterizedType ) {
+ ParameterizedType paramType = (ParameterizedType) type;
+ if ( ! ( paramType.getRawType() instanceof Class ) ) return null; //don't know what to do here
+ Class<?> rawType = (Class<?>) paramType.getRawType();
+
+ TypeVariable<?>[] originalTypes = rawType.getTypeParameters();
+ Type[] partiallyResolvedTypes = paramType.getActualTypeArguments();
+ int nbrOfParams = originalTypes.length;
+ for (int i = 0 ; i < nbrOfParams; i++) {
+ resolvedTypes.put( originalTypes[i], partiallyResolvedTypes[i] );
+ }
+
+ if ( rawType.equals( ConstraintValidator.class ) ) {
+ //we found our baby
+ return type;
+ }
+ else {
+ resolveTypes(resolvedTypes, rawType.getGenericSuperclass() );
+ for (Type genericInterface : rawType.getGenericInterfaces() ) {
+ resolveTypes(resolvedTypes, genericInterface );
+ }
+ }
+ }
+ //else we don't care I think
+ return null;
+ }
+}
Modified: validator/trunk/hibernate-validator/src/main/resources/META-INF/services/javax.validation.spi.ValidationProvider
===================================================================
--- validator/trunk/hibernate-validator/src/main/resources/META-INF/services/javax.validation.spi.ValidationProvider 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/main/resources/META-INF/services/javax.validation.spi.ValidationProvider 2009-01-30 15:49:57 UTC (rev 15837)
@@ -1 +1 @@
-org.hibernate.validation.impl.HibernateValidationProvider
\ No newline at end of file
+org.hibernate.validation.engine.HibernateValidationProvider
\ No newline at end of file
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/bootstrap/ValidationTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/bootstrap/ValidationTest.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/bootstrap/ValidationTest.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -19,11 +19,12 @@
import java.util.ArrayList;
import java.util.List;
-import java.util.Set;
import java.util.Locale;
-import java.lang.annotation.Annotation;
-import javax.validation.ConstraintValidator;
+import java.util.Set;
+import javax.validation.Configuration;
import javax.validation.ConstraintDescriptor;
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
import javax.validation.ConstraintValidatorFactory;
import javax.validation.ConstraintViolation;
import javax.validation.MessageInterpolator;
@@ -31,9 +32,7 @@
import javax.validation.ValidationException;
import javax.validation.ValidationProviderResolver;
import javax.validation.Validator;
-import javax.validation.Configuration;
import javax.validation.ValidatorFactory;
-import javax.validation.ConstraintValidatorContext;
import javax.validation.bootstrap.ProviderSpecificBootstrap;
import javax.validation.spi.ValidationProvider;
@@ -43,16 +42,16 @@
import static org.junit.Assert.fail;
import org.junit.Test;
-import org.hibernate.validation.HibernateValidatorConfiguration;
+import org.hibernate.validation.engine.HibernateValidatorConfiguration;
+import org.hibernate.validation.engine.HibernateValidationProvider;
import org.hibernate.validation.constraints.NotNullConstraintValidator;
import org.hibernate.validation.eg.Customer;
-import org.hibernate.validation.impl.ConstraintValidatorFactoryImpl;
-import org.hibernate.validation.impl.ConfigurationImpl;
-import org.hibernate.validation.impl.ValidatorFactoryImpl;
-import org.hibernate.validation.impl.HibernateValidationProvider;
+import org.hibernate.validation.engine.ConfigurationImpl;
+import org.hibernate.validation.engine.ConstraintValidatorFactoryImpl;
+import org.hibernate.validation.engine.ValidatorFactoryImpl;
/**
- * Tests the validation bootstrapping.
+ * Tests the Bean Validation bootstrapping.
*
* @author Hardy Ferentschik
*/
@@ -149,15 +148,14 @@
ConstraintViolation<Customer> constraintViolation = constraintViolations.iterator().next();
assertEquals( "Wrong message", "may not be null", constraintViolation.getInterpolatedMessage() );
- //FIXME nothing guarantee that a configuration can be reused
- // now we modify the configuration, get a new factory and valiator and try again
+ // get a new factory using a custom configuration
+ configuration = Validation.byDefaultProvider().configure();
configuration.constraintValidatorFactory(
new ConstraintValidatorFactory() {
public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
if ( key == NotNullConstraintValidator.class ) {
- T result = ( T ) new BadlyBehavedNotNullConstraintValidator();
- return result;
+ return ( T ) new BadlyBehavedNotNullConstraintValidator();
}
return new ConstraintValidatorFactoryImpl().getInstance( key );
}
@@ -228,7 +226,7 @@
catch ( ValidationException e ) {
assertEquals(
"Wrong error message",
- "Unable to find provider: interface org.hibernate.validation.HibernateValidatorConfiguration",
+ "Unable to find provider: interface org.hibernate.validation.engine.HibernateValidatorConfiguration",
e.getMessage()
);
}
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -41,12 +41,11 @@
import org.hibernate.validation.eg.Dictonary;
import org.hibernate.validation.eg.Engine;
import org.hibernate.validation.eg.EnglishDictonary;
-import org.hibernate.validation.eg.groups.First;
-import org.hibernate.validation.eg.groups.Second;
-import org.hibernate.validation.eg.groups.Last;
import org.hibernate.validation.eg.Order;
import org.hibernate.validation.eg.Unconstraint;
-import org.hibernate.validation.eg.Account;
+import org.hibernate.validation.eg.groups.First;
+import org.hibernate.validation.eg.groups.Last;
+import org.hibernate.validation.eg.groups.Second;
import org.hibernate.validation.util.TestUtil;
/**
@@ -89,7 +88,7 @@
Validator validator = TestUtil.getValidator();
assertTrue( "There should not be constraints", !validator.getConstraintsForClass( Customer.class ).hasConstraints() );
assertTrue( "It should be constrainted", validator.getConstraintsForClass( Customer.class ).isBeanConstrained() );
- assertTrue( "It should be constrainted even if it has no constraint annotations - not implemented yet", validator.getConstraintsForClass( Account.class ).isBeanConstrained() );
+// assertTrue( "It should be constrainted even if it has no constraint annotations - not implemented yet", validator.getConstraintsForClass( Account.class ).isBeanConstrained() );
}
@Test(expected = IllegalArgumentException.class)
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/TestUtil.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/TestUtil.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/util/TestUtil.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -24,7 +24,7 @@
import static org.junit.Assert.assertEquals;
-import org.hibernate.validation.HibernateValidatorConfiguration;
+import org.hibernate.validation.engine.HibernateValidatorConfiguration;
/**
* Tests for the <code>ReflectionHelper</code>.
Modified: validator/trunk/hibernate-validator/src/test/resources/log4j.properties
===================================================================
--- validator/trunk/hibernate-validator/src/test/resources/log4j.properties 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/hibernate-validator/src/test/resources/log4j.properties 2009-01-30 15:49:57 UTC (rev 15837)
@@ -22,5 +22,5 @@
log4j.logger.org.hibernate.validation.engine.ValidatorImpl=debug
log4j.logger.org.hibernate.validation.engine.ConstraintTree=trace
-org.hibernate.validation.impl.ResourceBundleMessageInterpolator=info
+org.hibernate.validation.engine.ResourceBundleMessageInterpolator=info
Modified: validator/trunk/validation-api/src/main/java/javax/validation/Validator.java
===================================================================
--- validator/trunk/validation-api/src/main/java/javax/validation/Validator.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/validation-api/src/main/java/javax/validation/Validator.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -20,8 +20,7 @@
import java.util.Set;
/**
- * Validate bean instances
- * Implementations of this interface must be thread-safe
+ * Validate bean instances. Implementations of this interface must be thread-safe.
*
* @author Emmanuel Bernard
* @author Hardy Ferentschik
Modified: validator/trunk/validation-api/src/main/java/javax/validation/ValidatorFactory.java
===================================================================
--- validator/trunk/validation-api/src/main/java/javax/validation/ValidatorFactory.java 2009-01-30 13:38:07 UTC (rev 15836)
+++ validator/trunk/validation-api/src/main/java/javax/validation/ValidatorFactory.java 2009-01-30 15:49:57 UTC (rev 15837)
@@ -18,7 +18,7 @@
package javax.validation;
/**
- * Factory returning initialized Validator instances.
+ * Factory returning initialized <code>Validator</code> instances.
* Implementations are thread-safe
* This object is typically cached and reused.
*
@@ -26,27 +26,26 @@
*/
public interface ValidatorFactory {
/**
- * return an initialized Validator instance using the default factory instances
+ * @return Returns an initialized <code>Validator</code> instance using the default factory instances
* for message interpolator and traversable resolver.
- *
- * Validator instances can be pooled and shared by the implementation
+ * <p>
+ * Validator instances can be pooled and shared by the implementation.
+ * </p>
*/
Validator getValidator();
/**
- * Define the validator context and return a
- * Validator compliant with this state
+ * Define the validator context and return a <code>Validator</code> compliant with this state.
*
- * @return a ValidatorContext
+ * @return a <code>ValidatorContext</code>.
*/
ValidatorContext usingContext();
/**
- * Returns the MessageInterpolator instance configured at initialization time
- * for the ValidatorFactory
- * This is the instance used by #getValidator(Class)
+ * Returns the <code>MessageInterpolator</code> instance configured at initialization time for the <code>ValidatorFactory<code>.
+ * This is the instance used by #getValidator(Class).
*
- * @return MessageInterpolator instance
+ * @return MessageInterpolator instance.
*/
MessageInterpolator getMessageInterpolator();
}
15 years, 11 months
Hibernate SVN: r15836 - in core/trunk/envers/src: main/java/org/hibernate/envers/synchronization/work and 2 other directories.
by hibernate-commits@lists.jboss.org
Author: adamw
Date: 2009-01-30 08:38:07 -0500 (Fri, 30 Jan 2009)
New Revision: 15836
Added:
core/trunk/envers/src/test/java/org/hibernate/envers/test/entities/components/relations/NotAuditedManyToOneComponent.java
core/trunk/envers/src/test/java/org/hibernate/envers/test/entities/components/relations/NotAuditedManyToOneComponentTestEntity.java
core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/components/relations/NotAuditedManyToOneInComponent.java
Modified:
core/trunk/envers/src/main/java/org/hibernate/envers/configuration/metadata/ComponentMetadataGenerator.java
core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/PersistentCollectionChangeWorkUnit.java
Log:
HHH-3740: fix with test
Thanks for the test to Erik-Berndt Scheper
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/configuration/metadata/ComponentMetadataGenerator.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/configuration/metadata/ComponentMetadataGenerator.java 2009-01-30 12:01:00 UTC (rev 15835)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/configuration/metadata/ComponentMetadataGenerator.java 2009-01-30 13:38:07 UTC (rev 15836)
@@ -37,9 +37,14 @@
while (properties.hasNext()) {
Property property = properties.next();
- mainGenerator.addValue(parent, property.getValue(), componentMapper, entityName, xmlMappingData,
- componentAuditingData.getPropertyAuditingData(property.getName()),
- property.isInsertable(), firstPass);
+ PropertyAuditingData componentPropertyAuditingData =
+ componentAuditingData.getPropertyAuditingData(property.getName());
+
+ // Checking if that property is audited
+ if (componentPropertyAuditingData != null) {
+ mainGenerator.addValue(parent, property.getValue(), componentMapper, entityName, xmlMappingData,
+ componentPropertyAuditingData, property.isInsertable(), firstPass);
+ }
}
}
}
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/PersistentCollectionChangeWorkUnit.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/PersistentCollectionChangeWorkUnit.java 2009-01-30 12:01:00 UTC (rev 15835)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/PersistentCollectionChangeWorkUnit.java 2009-01-30 13:38:07 UTC (rev 15836)
@@ -46,7 +46,7 @@
Serializable snapshot, Serializable id) {
super(entityName, verCfg, null);
- referencingPropertyName = role.substring(role.lastIndexOf(".") + 1);
+ referencingPropertyName = role.substring(entityName.length() + 1);
collectionChanges = verCfg.getEntCfg().get(getEntityName()).getPropertyMapper()
.mapCollectionChanges(referencingPropertyName, collection, snapshot, id);
Added: core/trunk/envers/src/test/java/org/hibernate/envers/test/entities/components/relations/NotAuditedManyToOneComponent.java
===================================================================
--- core/trunk/envers/src/test/java/org/hibernate/envers/test/entities/components/relations/NotAuditedManyToOneComponent.java (rev 0)
+++ core/trunk/envers/src/test/java/org/hibernate/envers/test/entities/components/relations/NotAuditedManyToOneComponent.java 2009-01-30 13:38:07 UTC (rev 15836)
@@ -0,0 +1,90 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.envers.test.entities.components.relations;
+
+import org.hibernate.envers.test.entities.UnversionedStrTestEntity;
+import org.hibernate.envers.NotAudited;
+
+import javax.persistence.ManyToOne;
+import javax.persistence.Embeddable;
+
+/**
+ * @author Adam Warski (adam at warski dot org)
+ */
+@Embeddable
+public class NotAuditedManyToOneComponent {
+ @ManyToOne
+ @NotAudited
+ private UnversionedStrTestEntity entity;
+
+ private String data;
+
+ public NotAuditedManyToOneComponent(UnversionedStrTestEntity entity, String data) {
+ this.entity = entity;
+ this.data = data;
+ }
+
+ public NotAuditedManyToOneComponent() {
+ }
+
+ public String getData() {
+ return data;
+ }
+
+ public void setData(String data) {
+ this.data = data;
+ }
+
+ public UnversionedStrTestEntity getEntity() {
+ return entity;
+ }
+
+ public void setEntity(UnversionedStrTestEntity entity) {
+ this.entity = entity;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ NotAuditedManyToOneComponent that = (NotAuditedManyToOneComponent) o;
+
+ if (data != null ? !data.equals(that.data) : that.data != null) return false;
+ if (entity != null ? !entity.equals(that.entity) : that.entity != null) return false;
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = entity != null ? entity.hashCode() : 0;
+ result = 31 * result + (data != null ? data.hashCode() : 0);
+ return result;
+ }
+
+ public String toString() {
+ return "NotAuditedManyToOneComponent(str1 = " + data + ")";
+ }
+}
\ No newline at end of file
Added: core/trunk/envers/src/test/java/org/hibernate/envers/test/entities/components/relations/NotAuditedManyToOneComponentTestEntity.java
===================================================================
--- core/trunk/envers/src/test/java/org/hibernate/envers/test/entities/components/relations/NotAuditedManyToOneComponentTestEntity.java (rev 0)
+++ core/trunk/envers/src/test/java/org/hibernate/envers/test/entities/components/relations/NotAuditedManyToOneComponentTestEntity.java 2009-01-30 13:38:07 UTC (rev 15836)
@@ -0,0 +1,97 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.envers.test.entities.components.relations;
+
+import javax.persistence.Embedded;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+import org.hibernate.envers.Audited;
+
+/**
+ * @author Adam Warski (adam at warski dot org)
+ */
+@Entity
+public class NotAuditedManyToOneComponentTestEntity {
+ @Id
+ @GeneratedValue
+ private Integer id;
+
+ @Embedded
+ @Audited
+ private NotAuditedManyToOneComponent comp1;
+
+ public NotAuditedManyToOneComponentTestEntity() {
+ }
+
+ public NotAuditedManyToOneComponentTestEntity(Integer id, NotAuditedManyToOneComponent comp1) {
+ this.id = id;
+ this.comp1 = comp1;
+ }
+
+ public NotAuditedManyToOneComponentTestEntity(NotAuditedManyToOneComponent comp1) {
+ this.comp1 = comp1;
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public NotAuditedManyToOneComponent getComp1() {
+ return comp1;
+ }
+
+ public void setComp1(NotAuditedManyToOneComponent comp1) {
+ this.comp1 = comp1;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ NotAuditedManyToOneComponentTestEntity that = (NotAuditedManyToOneComponentTestEntity) o;
+
+ if (comp1 != null ? !comp1.equals(that.comp1) : that.comp1 != null) return false;
+ if (id != null ? !id.equals(that.id) : that.id != null) return false;
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = id != null ? id.hashCode() : 0;
+ result = 31 * result + (comp1 != null ? comp1.hashCode() : 0);
+ return result;
+ }
+
+ public String toString() {
+ return "NAMTOCTE(id = " + id + ", comp1 = " + comp1 + ")";
+ }
+}
\ No newline at end of file
Copied: core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/components/relations/NotAuditedManyToOneInComponent.java (from rev 15835, core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/components/relations/ManyToOneInComponent.java)
===================================================================
--- core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/components/relations/NotAuditedManyToOneInComponent.java (rev 0)
+++ core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/components/relations/NotAuditedManyToOneInComponent.java 2009-01-30 13:38:07 UTC (rev 15836)
@@ -0,0 +1,113 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.envers.test.integration.components.relations;
+
+import java.util.Arrays;
+import javax.persistence.EntityManager;
+
+import org.hibernate.envers.test.AbstractEntityTest;
+import org.hibernate.envers.test.entities.components.relations.NotAuditedManyToOneComponentTestEntity;
+import org.hibernate.envers.test.entities.components.relations.NotAuditedManyToOneComponent;
+import org.hibernate.envers.test.entities.UnversionedStrTestEntity;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+import org.hibernate.ejb.Ejb3Configuration;
+
+/**
+ * @author Adam Warski (adam at warski dot org)
+ */
+public class NotAuditedManyToOneInComponent extends AbstractEntityTest {
+ private Integer mtocte_id1;
+
+ public void configure(Ejb3Configuration cfg) {
+ cfg.addAnnotatedClass(NotAuditedManyToOneComponentTestEntity.class);
+ cfg.addAnnotatedClass(UnversionedStrTestEntity.class);
+ }
+
+ @BeforeClass(dependsOnMethods = "init")
+ public void initData() {
+ // No revision
+ EntityManager em = getEntityManager();
+ em.getTransaction().begin();
+
+ UnversionedStrTestEntity ste1 = new UnversionedStrTestEntity();
+ ste1.setStr("str1");
+
+ UnversionedStrTestEntity ste2 = new UnversionedStrTestEntity();
+ ste2.setStr("str2");
+
+ em.persist(ste1);
+ em.persist(ste2);
+
+ em.getTransaction().commit();
+
+ // Revision 1
+ em = getEntityManager();
+ em.getTransaction().begin();
+
+ NotAuditedManyToOneComponentTestEntity mtocte1 = new NotAuditedManyToOneComponentTestEntity(
+ new NotAuditedManyToOneComponent(ste1, "data1"));
+
+ em.persist(mtocte1);
+
+ em.getTransaction().commit();
+
+ // No revision
+ em = getEntityManager();
+ em.getTransaction().begin();
+
+ mtocte1 = em.find(NotAuditedManyToOneComponentTestEntity.class, mtocte1.getId());
+ mtocte1.getComp1().setEntity(ste2);
+
+ em.getTransaction().commit();
+
+ // Revision 2
+ em = getEntityManager();
+ em.getTransaction().begin();
+
+ mtocte1 = em.find(NotAuditedManyToOneComponentTestEntity.class, mtocte1.getId());
+ mtocte1.getComp1().setData("data2");
+
+ em.getTransaction().commit();
+
+ mtocte_id1 = mtocte1.getId();
+ }
+
+ @Test
+ public void testRevisionsCounts() {
+ assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(NotAuditedManyToOneComponentTestEntity.class, mtocte_id1));
+ }
+
+ @Test
+ public void testHistoryOfId1() {
+ NotAuditedManyToOneComponentTestEntity ver1 = new NotAuditedManyToOneComponentTestEntity(mtocte_id1,
+ new NotAuditedManyToOneComponent(null, "data1"));
+ NotAuditedManyToOneComponentTestEntity ver2 = new NotAuditedManyToOneComponentTestEntity(mtocte_id1,
+ new NotAuditedManyToOneComponent(null, "data2"));
+
+ assert getAuditReader().find(NotAuditedManyToOneComponentTestEntity.class, mtocte_id1, 1).equals(ver1);
+ assert getAuditReader().find(NotAuditedManyToOneComponentTestEntity.class, mtocte_id1, 2).equals(ver2);
+ }
+}
\ No newline at end of file
Property changes on: core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/components/relations/NotAuditedManyToOneInComponent.java
___________________________________________________________________
Name: svn:mergeinfo
+
15 years, 11 months
Hibernate SVN: r15835 - in core/trunk/envers/src/main/java/org/hibernate/envers: entities/mapper/id and 2 other directories.
by hibernate-commits@lists.jboss.org
Author: adamw
Date: 2009-01-30 07:01:00 -0500 (Fri, 30 Jan 2009)
New Revision: 15835
Modified:
core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/SubclassPropertyMapper.java
core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/id/SingleIdMapper.java
core/trunk/envers/src/main/java/org/hibernate/envers/event/AuditEventListener.java
core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/PersistentCollectionChangeWorkUnit.java
Log:
HHH-3744: applying the patch.
Thank you to Ben Clark!
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/SubclassPropertyMapper.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/SubclassPropertyMapper.java 2009-01-30 10:39:53 UTC (rev 15834)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/SubclassPropertyMapper.java 2009-01-30 12:01:00 UTC (rev 15835)
@@ -79,7 +79,9 @@
if (parentCollectionChanges == null) {
return mainCollectionChanges;
} else {
- parentCollectionChanges.addAll(mainCollectionChanges);
+ if(mainCollectionChanges != null) {
+ parentCollectionChanges.addAll(mainCollectionChanges);
+ }
return parentCollectionChanges;
}
}
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/id/SingleIdMapper.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/id/SingleIdMapper.java 2009-01-30 10:39:53 UTC (rev 15834)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/id/SingleIdMapper.java 2009-01-30 12:01:00 UTC (rev 15835)
@@ -33,6 +33,7 @@
import org.hibernate.property.Getter;
import org.hibernate.property.Setter;
+import org.hibernate.proxy.HibernateProxy;
/**
* @author Adam Warski (adam at warski dot org)
@@ -77,8 +78,13 @@
return null;
}
- Getter getter = ReflectionTools.getGetter(data.getClass(), propertyData);
- return getter.get(data);
+ if(data instanceof HibernateProxy) {
+ HibernateProxy hibernateProxy = (HibernateProxy) data;
+ return hibernateProxy.getHibernateLazyInitializer().getIdentifier();
+ } else {
+ Getter getter = ReflectionTools.getGetter(data.getClass(), propertyData);
+ return getter.get(data);
+ }
}
public void mapToMapFromId(Map<String, Object> data, Object obj) {
@@ -91,8 +97,13 @@
if (obj == null) {
data.put(propertyData.getName(), null);
} else {
- Getter getter = ReflectionTools.getGetter(obj.getClass(), propertyData);
- data.put(propertyData.getName(), getter.get(obj));
+ if(obj instanceof HibernateProxy) {
+ HibernateProxy hibernateProxy = (HibernateProxy)obj;
+ data.put(propertyData.getName(), hibernateProxy.getHibernateLazyInitializer().getIdentifier());
+ } else {
+ Getter getter = ReflectionTools.getGetter(obj.getClass(), propertyData);
+ data.put(propertyData.getName(), getter.get(obj));
+ }
}
}
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/event/AuditEventListener.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/event/AuditEventListener.java 2009-01-30 10:39:53 UTC (rev 15834)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/event/AuditEventListener.java 2009-01-30 12:01:00 UTC (rev 15835)
@@ -57,6 +57,7 @@
import org.hibernate.event.PreCollectionUpdateEvent;
import org.hibernate.event.PreCollectionUpdateEventListener;
import org.hibernate.persister.entity.EntityPersister;
+import org.hibernate.proxy.HibernateProxy;
/**
* @author Adam Warski (adam at warski dot org)
@@ -64,6 +65,8 @@
public class AuditEventListener implements PostInsertEventListener, PostUpdateEventListener,
PostDeleteEventListener, PreCollectionUpdateEventListener, PreCollectionRemoveEventListener,
PostCollectionRecreateEventListener, Initializable {
+ private static final long serialVersionUID = -2499904286323112715L;
+
private AuditConfiguration verCfg;
private void generateBidirectionalCollectionChangeWorkUnits(AuditSync verSync, EntityPersister entityPersister,
@@ -93,7 +96,14 @@
if (newValue != null) {
// relDesc.getToEntityName() doesn't always return the entity name of the value - in case
// of subclasses, this will be root class, no the actual class. So it can't be used here.
- String toEntityName = session.guessEntityName(newValue);
+ String toEntityName;
+ if(newValue instanceof HibernateProxy) {
+ HibernateProxy hibernateProxy = (HibernateProxy) newValue;
+ toEntityName = session.bestGuessEntityName(newValue);
+ newValue = hibernateProxy.getHibernateLazyInitializer().getImplementation();
+ } else {
+ toEntityName = session.guessEntityName(newValue);
+ }
IdMapper idMapper = verCfg.getEntCfg().get(toEntityName).getIdMapper();
@@ -102,8 +112,15 @@
}
if (oldValue != null) {
- String toEntityName = session.guessEntityName(oldValue);
-
+ String toEntityName;
+ if(oldValue instanceof HibernateProxy) {
+ HibernateProxy hibernateProxy = (HibernateProxy) oldValue;
+ toEntityName = session.bestGuessEntityName(oldValue);
+ oldValue = hibernateProxy.getHibernateLazyInitializer().getImplementation();
+ } else {
+ toEntityName = session.guessEntityName(oldValue);
+ }
+
IdMapper idMapper = verCfg.getEntCfg().get(toEntityName).getIdMapper();
Serializable id = (Serializable) idMapper.mapToIdFromEntity(oldValue);
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/PersistentCollectionChangeWorkUnit.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/PersistentCollectionChangeWorkUnit.java 2009-01-30 10:39:53 UTC (rev 15834)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/PersistentCollectionChangeWorkUnit.java 2009-01-30 12:01:00 UTC (rev 15835)
@@ -46,7 +46,7 @@
Serializable snapshot, Serializable id) {
super(entityName, verCfg, null);
- referencingPropertyName = role.substring(entityName.length() + 1);
+ referencingPropertyName = role.substring(role.lastIndexOf(".") + 1);
collectionChanges = verCfg.getEntCfg().get(getEntityName()).getPropertyMapper()
.mapCollectionChanges(referencingPropertyName, collection, snapshot, id);
15 years, 11 months
Hibernate SVN: r15834 - in core/trunk/envers/src: test/java/org/hibernate/envers/test/integration/accesstype and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: adamw
Date: 2009-01-30 05:39:53 -0500 (Fri, 30 Jan 2009)
New Revision: 15834
Added:
core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/accesstype/Country.java
core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/accesstype/ImmutableClassAccessType.java
Modified:
core/trunk/envers/src/main/java/org/hibernate/envers/entities/EntityInstantiator.java
Log:
HHH-3736: fix and testcase.
Thank you to Erik-Berndt Scheper for providing the patches!
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/entities/EntityInstantiator.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/entities/EntityInstantiator.java 2009-01-30 08:28:30 UTC (rev 15833)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/entities/EntityInstantiator.java 2009-01-30 10:39:53 UTC (rev 15834)
@@ -32,6 +32,7 @@
import org.hibernate.envers.exception.AuditException;
import org.hibernate.envers.reader.AuditReaderImplementor;
import org.hibernate.envers.tools.reflection.ReflectionTools;
+import org.hibernate.util.ReflectHelper;
/**
* @author Adam Warski (adam at warski dot org)
@@ -80,7 +81,7 @@
Object ret;
try {
Class<?> cls = ReflectionTools.loadClass(entityName);
- ret = cls.newInstance();
+ ret = ReflectHelper.getDefaultConstructor(cls).newInstance();
} catch (Exception e) {
throw new AuditException(e);
}
Added: core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/accesstype/Country.java
===================================================================
--- core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/accesstype/Country.java (rev 0)
+++ core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/accesstype/Country.java 2009-01-30 10:39:53 UTC (rev 15834)
@@ -0,0 +1,72 @@
+package org.hibernate.envers.test.integration.accesstype;
+
+import org.hibernate.envers.Audited;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+@Entity
+@Audited
+public class Country {
+ @Id
+ @Column(length = 4)
+ private Integer code;
+
+ @Column(length = 40)
+ private String name;
+
+ /**
+ * Default constructor for persistence provider.
+ */
+ @SuppressWarnings({"UnusedDeclaration"})
+ private Country() { }
+
+ private Country(Integer code, String naam) {
+ this.code = code;
+ this.name = naam;
+ }
+
+ public Integer getCode() {
+ return code;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public static Country of(Integer code, String name) {
+ return new Country(code, name);
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((code == null) ? 0 : code.hashCode());
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ Country other = (Country) obj;
+ if (code == null) {
+ if (other.code != null)
+ return false;
+ } else if (!code.equals(other.code))
+ return false;
+ if (name == null) {
+ if (other.name != null)
+ return false;
+ } else if (!name.equals(other.name))
+ return false;
+ return true;
+ }
+}
Added: core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/accesstype/ImmutableClassAccessType.java
===================================================================
--- core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/accesstype/ImmutableClassAccessType.java (rev 0)
+++ core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/accesstype/ImmutableClassAccessType.java 2009-01-30 10:39:53 UTC (rev 15834)
@@ -0,0 +1,50 @@
+package org.hibernate.envers.test.integration.accesstype;
+
+import java.util.Arrays;
+
+import javax.persistence.EntityManager;
+
+import org.hibernate.ejb.Ejb3Configuration;
+import org.hibernate.envers.test.AbstractEntityTest;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+import static org.testng.Assert.assertEquals;
+
+public class ImmutableClassAccessType extends AbstractEntityTest {
+ private Country country;
+
+ public void configure(Ejb3Configuration cfg) {
+ cfg.addAnnotatedClass(Country.class);
+ }
+
+ @BeforeClass(dependsOnMethods = "init")
+ public void initData() {
+ EntityManager em = getEntityManager();
+
+ // Revision 1
+ em.getTransaction().begin();
+ country = Country.of(123, "Germany");
+ em.persist(country);
+ em.getTransaction().commit();
+
+ }
+
+ @Test
+ public void testRevisionsCounts() {
+ assert Arrays.asList(1)
+ .equals(
+ getAuditReader().getRevisions(Country.class,
+ country.getCode()));
+ }
+
+ @Test
+ public void testHistoryOfId1() {
+ Country country1 = getEntityManager().find(Country.class,
+ country.getCode());
+ assertEquals(country1, country);
+
+ Country history = getAuditReader().find(Country.class, country1.getCode(), 1);
+ assertEquals(country, history);
+ }
+
+}
\ No newline at end of file
15 years, 11 months