Skip to content
Snippets Groups Projects
Commit c0115660 authored by Emmanuel Bourg's avatar Emmanuel Bourg
Browse files

New upstream version 5.1.0

parent 3bb6b02e
No related branches found
No related tags found
No related merge requests found
Showing
with 734 additions and 170 deletions
# Repository specific GIT options
# Set default handling of line terminators for all non explicitly listed file types:
* text=auto
# Force LF as internal repository format for all following files;
# this overrides user settings to enforce the *right format* :
*.java text
*.xml text
*.txt text
*.md text
*.html text
*.properties text
*.rb text
*.pot text
*.po text
*.xsd text
*.header text
*.groovy text
*.css text
# Specify we want Java-friendly readable chunk headers for diff:
*.java diff=java
# Hibernate Validator
*Version: 5.0.3.Final, 28.01.2014*
*Version: 5.1.0.Final, 02.03.2014*
## What is it?
......@@ -35,10 +35,10 @@ Logging will delegate any log requests to that provider.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.3.Final</version>
<version>5.1.0.Final</version>
</dependency>
You also need an API and implementation of the Unified Expression Language. This dependencies must be explicitly added in an SE environment.
You also need an API and implementation of the Unified Expression Language. These dependencies must be explicitly added in an SE environment.
In an EE environment they are often already provided.
<dependency>
......@@ -59,7 +59,7 @@ extension by adding the following dependency:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-cdi</artifactId>
<version>5.0.3.Final</version>
<version>5.1.0.Final</version>
</dependency>
* _hibernate-validator-annotation-processor-&lt;version&gt;.jar_ is an optional jar which can be integrated with your build
......@@ -74,7 +74,7 @@ the Apache Software License 2.0. Refer to license.txt for more information.
## Build from Source
You can build Hibernate Validator from source by cloning the git repository git://github.com/hibernate/hibernate-validator.git.
You will also need a JDK 6 or 7 and Maven 3. With these prerequisites in place you can compile the source via
You will also need a JDK 7 and Maven 3 (>= 3.0.3). With these prerequisites in place you can compile the source via
mvn clean install -s settings-example.xml
......@@ -93,3 +93,4 @@ There are more build options available as well. For more information refer to [C
* [Mailing Lists](http://www.hibernate.org/community/mailinglists.html)
* [Source Code](git://github.com/hibernate/hibernate-validator.git)
* [Issue Tracking](http://opensource.atlassian.com/projects/hibernate/browse/HV)
* [Continuous Integration](https://hibernate-validator.ci.cloudbees.com/) [![Build Status](https://hibernate-validator.ci.cloudbees.com/buildStatus/icon?job=HV-5-MASTER)](https://hibernate-validator.ci.cloudbees.com/view/Hibernate%20Validator%205/job/HV-5-MASTER/)
......@@ -21,7 +21,7 @@
<parent>
<artifactId>hibernate-validator-parent</artifactId>
<groupId>org.hibernate</groupId>
<version>5.0.3.Final</version>
<version>5.1.0.Final</version>
<relativePath>../pom.xml</relativePath>
</parent>
......
......@@ -200,6 +200,9 @@ public ConstraintHelper(Types typeUtils, AnnotationApiHelper annotationApiHelper
registerAllowedTypesForBuiltInConstraint( HibernateValidatorTypes.EMAIL, CharSequence.class );
registerAllowedTypesForBuiltInConstraint( HibernateValidatorTypes.LENGTH, CharSequence.class );
registerAllowedTypesForBuiltInConstraint( HibernateValidatorTypes.MOD_CHECK, CharSequence.class );
registerAllowedTypesForBuiltInConstraint( HibernateValidatorTypes.LUHN_CHECK, CharSequence.class );
registerAllowedTypesForBuiltInConstraint( HibernateValidatorTypes.MOD_10_CHECK, CharSequence.class );
registerAllowedTypesForBuiltInConstraint( HibernateValidatorTypes.MOD_11_CHECK, CharSequence.class );
registerAllowedTypesForBuiltInConstraint( HibernateValidatorTypes.NOT_BLANK, CharSequence.class );
registerAllowedTypesForBuiltInConstraint( HibernateValidatorTypes.SAFE_HTML, CharSequence.class );
registerAllowedTypesForBuiltInConstraint( HibernateValidatorTypes.SCRIPT_ASSERT, Object.class );
......
......@@ -65,6 +65,9 @@ public static class HibernateValidatorTypes {
public static final String EMAIL = ORG_HIBERNATE_VALIDATOR_CONSTRAINTS + ".Email";
public static final String LENGTH = ORG_HIBERNATE_VALIDATOR_CONSTRAINTS + ".Length";
public static final String MOD_CHECK = ORG_HIBERNATE_VALIDATOR_CONSTRAINTS + ".ModCheck";
public static final String LUHN_CHECK = ORG_HIBERNATE_VALIDATOR_CONSTRAINTS + ".LuhnCheck";
public static final String MOD_10_CHECK = ORG_HIBERNATE_VALIDATOR_CONSTRAINTS + ".Mod10Check";
public static final String MOD_11_CHECK = ORG_HIBERNATE_VALIDATOR_CONSTRAINTS + ".Mod11Check";
public static final String NOT_BLANK = ORG_HIBERNATE_VALIDATOR_CONSTRAINTS + ".NotBlank";
public static final String SAFE_HTML = ORG_HIBERNATE_VALIDATOR_CONSTRAINTS + ".SafeHtml";
public static final String SCRIPT_ASSERT = ORG_HIBERNATE_VALIDATOR_CONSTRAINTS + ".ScriptAssert";
......
......@@ -113,18 +113,22 @@ public void hibernateValidatorProvidedCustomConstraints() {
assertFalse( compilationResult );
assertThatDiagnosticsMatch(
diagnostics,
new DiagnosticExpectation( Kind.ERROR, 58 ),
new DiagnosticExpectation( Kind.ERROR, 59 ),
new DiagnosticExpectation( Kind.ERROR, 60 ),
new DiagnosticExpectation( Kind.ERROR, 61 ),
new DiagnosticExpectation( Kind.ERROR, 62 ),
new DiagnosticExpectation( Kind.ERROR, 63 ),
new DiagnosticExpectation( Kind.ERROR, 64 ),
new DiagnosticExpectation( Kind.ERROR, 65 ),
new DiagnosticExpectation( Kind.ERROR, 66 ),
new DiagnosticExpectation( Kind.ERROR, 67 ),
new DiagnosticExpectation( Kind.ERROR, 68 ),
new DiagnosticExpectation( Kind.ERROR, 69 )
new DiagnosticExpectation( Kind.ERROR, 69 ),
new DiagnosticExpectation( Kind.ERROR, 70 ),
new DiagnosticExpectation( Kind.ERROR, 71 ),
new DiagnosticExpectation( Kind.ERROR, 72 ),
new DiagnosticExpectation( Kind.ERROR, 73 ),
new DiagnosticExpectation( Kind.ERROR, 74 ),
new DiagnosticExpectation( Kind.ERROR, 75 ),
new DiagnosticExpectation( Kind.ERROR, 76 ),
new DiagnosticExpectation( Kind.ERROR, 77 ),
new DiagnosticExpectation( Kind.ERROR, 78 )
);
}
......
......@@ -21,6 +21,9 @@
import org.hibernate.validator.constraints.CreditCardNumber;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.LuhnCheck;
import org.hibernate.validator.constraints.Mod10Check;
import org.hibernate.validator.constraints.Mod11Check;
import org.hibernate.validator.constraints.ModCheck;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
......@@ -41,7 +44,10 @@ public class HibernateValidatorProvidedCustomConstraints {
@CreditCardNumber
@Email
@Length
@LuhnCheck
@ModCheck(modType = ModCheck.ModType.MOD10, multiplier = 2)
@Mod10Check
@Mod11Check
@NotBlank
@NotEmpty
@Range
......@@ -58,7 +64,10 @@ public class HibernateValidatorProvidedCustomConstraints {
@CreditCardNumber
@Email
@Length
@LuhnCheck
@ModCheck(modType = ModCheck.ModType.MOD10, multiplier = 2)
@Mod10Check
@Mod11Check
@NotBlank
@NotEmpty
@Range
......
......@@ -16,11 +16,10 @@
*/
package org.hibernate.validator.ap.util;
import javax.tools.Diagnostic;
import javax.tools.Diagnostic.Kind;
/**
* Expectation value to be matched against a given {@link Diagnostic}.
* Expectation value to be matched against a given {@link javax.tools.Diagnostic}.
*
* @author Gunnar Morling
*/
......
......@@ -21,7 +21,7 @@
<parent>
<artifactId>hibernate-validator-parent</artifactId>
<groupId>org.hibernate</groupId>
<version>5.0.3.Final</version>
<version>5.1.0.Final</version>
<relativePath>../pom.xml</relativePath>
</parent>
......@@ -112,6 +112,12 @@
<artifactId>arquillian-weld-se-embedded-1.1</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<classifier>testing</classifier>
<scope>test</scope>
</dependency>
</dependencies>
<build>
......
......@@ -56,6 +56,9 @@ public InjectingConstraintValidatorFactory(BeanManager beanManager) {
@Override
public void releaseInstance(ConstraintValidator<?, ?> instance) {
DestructibleBeanInstance<?> destructibleBeanInstance = constraintValidatorMap.remove( instance );
destructibleBeanInstance.destroy();
// HV-865 (Cleanup is multi threaded and instances can be removed by multiple threads. Explicit null check is needed)
if ( destructibleBeanInstance != null ) {
destructibleBeanInstance.destroy();
}
}
}
/*
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat, Inc. and/or its affiliates, and individual contributors
* Copyright 2012-2014, Red Hat, Inc. and/or its affiliates, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
......@@ -59,6 +59,7 @@
import org.hibernate.validator.internal.util.Contracts;
import org.hibernate.validator.internal.util.ExecutableHelper;
import org.hibernate.validator.internal.util.ReflectionHelper;
import org.hibernate.validator.internal.util.TypeResolutionHelper;
import org.hibernate.validator.internal.util.classhierarchy.ClassHierarchyHelper;
import org.hibernate.validator.internal.util.logging.Log;
import org.hibernate.validator.internal.util.logging.LoggerFactory;
......@@ -66,35 +67,64 @@
import static org.hibernate.validator.internal.util.CollectionHelper.newHashSet;
/**
* A CDI portable extension which registers beans for {@link ValidatorFactory} and {@link Validator}.
* A CDI portable extension which integrates Bean Validation with CDI. It registers the following objects:
* <ul>
* <li>
* Beans for {@link ValidatorFactory} and {@link Validator} representing default validator factory and validator as
* configured via {@code META-INF/validation.xml}. These beans will have the {@code Default} qualifier and in addition
* the {@code HibernateValidator} qualifier if Hibernate Validator is the default validation provider.</li>
* <li>In case Hibernate Validator is <em>not</em> the default provider, another pair of beans will be registered in
* addition which are qualified with the {@code HibernateValidator} qualifier.</li>
* </ul>
* Neither of these beans will be registered in case there is already another bean with the same type and qualifier(s),
* e.g. registered by another portable extension or the application itself.
*
* @author Gunnar Morling
* @author Hardy Ferentschik
*/
public class ValidationExtension implements Extension {
private static final Log log = LoggerFactory.make();
private static final EnumSet<ExecutableType> ALL_EXECUTABLE_TYPES =
EnumSet.of( ExecutableType.CONSTRUCTORS, ExecutableType.NON_GETTER_METHODS, ExecutableType.GETTER_METHODS );
private static final EnumSet<ExecutableType> DEFAULT_EXECUTABLE_TYPES =
EnumSet.of( ExecutableType.CONSTRUCTORS, ExecutableType.NON_GETTER_METHODS );
@SuppressWarnings("serial")
private final Annotation defaultQualifier = new AnnotationLiteral<Default>() {
};
@SuppressWarnings("serial")
private final Annotation hibernateValidatorQualifier = new AnnotationLiteral<HibernateValidator>() {
};
private final ExecutableHelper executableHelper;
/**
* Used for identifying constrained classes
*/
private final Validator validator;
private final ValidatorFactory validatorFactory;
private final Set<ExecutableType> globalExecutableTypes;
private final boolean isExecutableValidationEnabled;
private boolean validatorRegisteredUnderDefaultQualifier;
private boolean validatorRegisteredUnderHibernateQualifier;
public ValidationExtension() {
validatorRegisteredUnderDefaultQualifier = false;
validatorRegisteredUnderHibernateQualifier = false;
private Bean<?> defaultValidatorFactoryBean;
private Bean<?> hibernateValidatorFactoryBean;
private boolean defaultValidatorAlreadyRegistered = false;
private boolean hibernateValidatorAlreadyRegistered = false;
public ValidationExtension() {
Configuration<?> config = Validation.byDefaultProvider().configure();
BootstrapConfiguration bootstrap = config.getBootstrapConfiguration();
globalExecutableTypes = bootstrap.getDefaultValidatedExecutableTypes();
isExecutableValidationEnabled = bootstrap.isExecutableValidationEnabled();
validator = config.buildValidatorFactory().getValidator();
executableHelper = new ExecutableHelper();
validatorFactory = config.buildValidatorFactory();
validator = validatorFactory.getValidator();
executableHelper = new ExecutableHelper( new TypeResolutionHelper() );
}
/**
......@@ -103,7 +133,8 @@ public ValidationExtension() {
* @param beforeBeanDiscoveryEvent event fired before the bean discovery process starts
* @param beanManager the bean manager.
*/
public void beforeBeanDiscovery(@Observes BeforeBeanDiscovery beforeBeanDiscoveryEvent, final BeanManager beanManager) {
public void beforeBeanDiscovery(@Observes BeforeBeanDiscovery beforeBeanDiscoveryEvent,
final BeanManager beanManager) {
Contracts.assertNotNull( beforeBeanDiscoveryEvent, "The BeforeBeanDiscovery event cannot be null" );
Contracts.assertNotNull( beanManager, "The BeanManager cannot be null" );
......@@ -113,8 +144,7 @@ public void beforeBeanDiscovery(@Observes BeforeBeanDiscovery beforeBeanDiscover
}
/**
* Registers the Hibernate specific {@code ValidatorFactory} and {@code Validator}. The qualifiers used for registration
* depend on which other beans have already registered these type of beans.
* Registers beans for {@code ValidatorFactory} and {@code Validator} if not yet present.
*
* @param afterBeanDiscoveryEvent event fired after the bean discovery phase.
* @param beanManager the bean manager.
......@@ -123,18 +153,44 @@ public void afterBeanDiscovery(@Observes AfterBeanDiscovery afterBeanDiscoveryEv
Contracts.assertNotNull( afterBeanDiscoveryEvent, "The AfterBeanDiscovery event cannot be null" );
Contracts.assertNotNull( beanManager, "The BeanManager cannot be null" );
Set<Annotation> missingQualifiers = determineMissingQualifiers();
if ( missingQualifiers.isEmpty() ) {
return;
ValidationProviderHelper defaultProviderHelper = ValidationProviderHelper.forDefaultProvider( validatorFactory );
ValidationProviderHelper hvProviderHelper = ValidationProviderHelper.forHibernateValidator();
// register a @Default VF; note that this will fire a ProcessBean event, so when coming to the next if-block,
// hibernateValidatorFactoryBean will already have been set to that newly registered bean, causing not
// another bean for HV to be set
if ( defaultValidatorFactoryBean == null ) {
afterBeanDiscoveryEvent.addBean( new ValidatorFactoryBean( beanManager, defaultProviderHelper ) );
}
if ( hibernateValidatorFactoryBean == null ) {
afterBeanDiscoveryEvent.addBean( new ValidatorFactoryBean( beanManager, hvProviderHelper ) );
}
if ( !defaultValidatorAlreadyRegistered ) {
afterBeanDiscoveryEvent.addBean(
new ValidatorBean(
beanManager,
defaultValidatorFactoryBean,
defaultProviderHelper
)
);
}
afterBeanDiscoveryEvent.addBean( new ValidatorFactoryBean( beanManager, missingQualifiers ) );
afterBeanDiscoveryEvent.addBean( new ValidatorBean( beanManager, missingQualifiers ) );
if ( !hibernateValidatorAlreadyRegistered ) {
afterBeanDiscoveryEvent.addBean(
new ValidatorBean(
beanManager,
hibernateValidatorFactoryBean,
hvProviderHelper
)
);
}
}
/**
* Watches the {@code ProcessBean} event in order to determine whether and under which qualifiers {@code ValidatorFactory}s
* and {@code Validator}s get registered.
* Watches the {@code ProcessBean} event in order to determine whether beans for {@code ValidatorFactory} and
* {@code Validator} already have been registered by some other component.
*
* @param processBeanEvent event fired for each enabled bean.
*/
......@@ -142,18 +198,21 @@ public void processBean(@Observes ProcessBean<?> processBeanEvent) {
Contracts.assertNotNull( processBeanEvent, "The ProcessBean event cannot be null" );
Bean<?> bean = processBeanEvent.getBean();
if ( !bean.getTypes().contains( ValidatorFactory.class ) && !bean.getTypes().contains( Validator.class ) ) {
return;
}
if ( bean instanceof ValidatorFactoryBean || bean instanceof ValidatorBean ) {
return;
if ( bean.getTypes().contains( ValidatorFactory.class ) || bean instanceof ValidatorFactoryBean ) {
if ( bean.getQualifiers().contains( defaultQualifier ) ) {
defaultValidatorFactoryBean = bean;
}
if ( bean.getQualifiers().contains( hibernateValidatorQualifier ) ) {
hibernateValidatorFactoryBean = bean;
}
}
for ( Annotation annotation : bean.getQualifiers() ) {
if ( HibernateValidator.class.equals( annotation.annotationType() ) ) {
validatorRegisteredUnderHibernateQualifier = true;
else if ( bean.getTypes().contains( Validator.class ) || bean instanceof ValidatorBean ) {
if ( bean.getQualifiers().contains( defaultQualifier ) ) {
defaultValidatorAlreadyRegistered = true;
}
if ( Default.class.equals( annotation.annotationType() ) ) {
validatorRegisteredUnderDefaultQualifier = true;
if ( bean.getQualifiers().contains( hibernateValidatorQualifier ) ) {
hibernateValidatorAlreadyRegistered = true;
}
}
}
......@@ -196,8 +255,8 @@ public <T> void processAnnotatedType(@Observes @WithAnnotations({
}
private <T> Set<AnnotatedCallable<? super T>> determineConstrainedCallables(AnnotatedType<T> type,
BeanDescriptor beanDescriptor,
EnumSet<ExecutableType> classLevelExecutableTypes) {
BeanDescriptor beanDescriptor,
EnumSet<ExecutableType> classLevelExecutableTypes) {
Set<AnnotatedCallable<? super T>> callables = newHashSet();
determineConstrainedConstructors( type, beanDescriptor, classLevelExecutableTypes, callables );
......@@ -207,8 +266,8 @@ private <T> Set<AnnotatedCallable<? super T>> determineConstrainedCallables(Anno
}
private <T> void determineConstrainedMethod(AnnotatedType<T> type,
BeanDescriptor beanDescriptor,
Set<AnnotatedCallable<? super T>> callables) {
BeanDescriptor beanDescriptor,
Set<AnnotatedCallable<? super T>> callables) {
List<Method> overriddenAndImplementedMethods = ClassHierarchyHelper.getAllMethods( type.getJavaClass() );
for ( AnnotatedMethod<? super T> annotatedMethod : type.getMethods() ) {
Method method = annotatedMethod.getJavaMember();
......@@ -242,7 +301,8 @@ private <T> void determineConstrainedMethod(AnnotatedType<T> type,
}
}
private <T> void determineConstrainedConstructors(AnnotatedType<T> type, BeanDescriptor beanDescriptor, EnumSet<ExecutableType> classLevelExecutableTypes, Set<AnnotatedCallable<? super T>> callables) {
private <T> void determineConstrainedConstructors(AnnotatedType<T> type, BeanDescriptor beanDescriptor,
EnumSet<ExecutableType> classLevelExecutableTypes, Set<AnnotatedCallable<? super T>> callables) {
// no special inheritance rules to consider for constructors
for ( AnnotatedConstructor<T> annotatedConstructor : type.getConstructors() ) {
Constructor<?> constructor = annotatedConstructor.getJavaMember();
......@@ -271,8 +331,8 @@ private boolean isGetterConstrained(Method method, BeanDescriptor beanDescriptor
}
private boolean veto(EnumSet<ExecutableType> classLevelExecutableTypes,
EnumSet<ExecutableType> memberLevelExecutableType,
ExecutableType currentExecutableType) {
EnumSet<ExecutableType> memberLevelExecutableType,
ExecutableType currentExecutableType) {
if ( !memberLevelExecutableType.isEmpty() ) {
return !memberLevelExecutableType.contains( currentExecutableType )
&& !memberLevelExecutableType.contains( ExecutableType.IMPLICIT );
......@@ -286,32 +346,6 @@ private boolean veto(EnumSet<ExecutableType> classLevelExecutableTypes,
return !globalExecutableTypes.contains( currentExecutableType );
}
/**
* The set of qualifier this extension should bind its {@code ValidatorFactory} and {@code Validator}
* under. This set is based on the observed registered beans via the {@code ProcessBean} event.
*
* @return Returns the set of qualifier this extension should bind its {@code ValidatorFactory} and {@code Validator}
* under.
*/
private Set<Annotation> determineMissingQualifiers() {
Set<Annotation> annotations = newHashSet( 2 );
if ( !validatorRegisteredUnderDefaultQualifier ) {
annotations.add(
new AnnotationLiteral<Default>() {
}
);
}
if ( !validatorRegisteredUnderHibernateQualifier ) {
annotations.add(
new AnnotationLiteral<HibernateValidator>() {
}
);
}
return annotations;
}
private EnumSet<ExecutableType> executableTypesDefinedOnType(Class<?> clazz) {
ValidateOnExecution validateOnExecutionAnnotation = clazz.getAnnotation( ValidateOnExecution.class );
EnumSet<ExecutableType> executableTypes = commonExecutableTypeChecks( validateOnExecutionAnnotation );
......@@ -376,7 +410,7 @@ private EnumSet<ExecutableType> commonExecutableTypeChecks(ValidateOnExecution v
executableTypes.remove( ExecutableType.NONE );
}
// 10.1.2 od spec - A list containing ALL and other types of executables is equivalent to a list containing only ALL
// 10.1.2 of spec - A list containing ALL and other types of executables is equivalent to a list containing only ALL
if ( executableTypes.contains( ExecutableType.ALL ) ) {
executableTypes = ALL_EXECUTABLE_TYPES;
}
......
/*
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat, Inc. and/or its affiliates, 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.validator.internal.cdi;
import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Default;
import javax.enterprise.util.AnnotationLiteral;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.hibernate.validator.HibernateValidatorFactory;
import org.hibernate.validator.cdi.HibernateValidator;
import org.hibernate.validator.internal.engine.ValidatorFactoryImpl;
import org.hibernate.validator.internal.engine.ValidatorImpl;
import static org.hibernate.validator.internal.util.CollectionHelper.newHashSet;
/**
* Provides functionality for dealing with validation provider types.
*
* @author Gunnar Morling
*/
public class ValidationProviderHelper {
private final boolean isDefaultProvider;
private final boolean isHibernateValidator;
private final Class<? extends ValidatorFactory> validatorFactoryClass;
private final Class<? extends Validator> validatorClass;
private final Set<Annotation> qualifiers;
public static ValidationProviderHelper forDefaultProvider(ValidatorFactory validatorFactory) {
boolean isHibernateValidator = validatorFactory instanceof HibernateValidatorFactory;
return new ValidationProviderHelper(
true,
isHibernateValidator,
validatorFactory.getClass(),
validatorFactory.getValidator().getClass(),
determineRequiredQualifiers( true, isHibernateValidator )
);
}
public static ValidationProviderHelper forHibernateValidator() {
return new ValidationProviderHelper(
false,
true,
ValidatorFactoryImpl.class,
ValidatorImpl.class,
determineRequiredQualifiers( false, true )
);
}
private ValidationProviderHelper(boolean isDefaultProvider,
boolean isHibernateValidator,
Class<? extends ValidatorFactory> validatorFactoryClass,
Class<? extends Validator> validatorClass,
Set<Annotation> qualifiers) {
this.isDefaultProvider = isDefaultProvider;
this.isHibernateValidator = isHibernateValidator;
this.validatorFactoryClass = validatorFactoryClass;
this.validatorClass = validatorClass;
this.qualifiers = Collections.unmodifiableSet( qualifiers );
}
/**
* Whether the given provider is the default provider or not.
*/
public boolean isDefaultProvider() {
return isDefaultProvider;
}
/**
* Whether the given provider is Hibernate Validator or not.
*/
boolean isHibernateValidator() {
return isHibernateValidator;
}
/**
* Determines the class of the {@link ValidatorFactory} corresponding to the given configuration object.
*/
Class<? extends ValidatorFactory> getValidatorFactoryBeanClass() {
return validatorFactoryClass;
}
/**
* Determines the class of the {@link Validator} corresponding to the given configuration object.
*/
Class<? extends Validator> getValidatorBeanClass() {
return validatorClass;
}
Set<Annotation> getQualifiers() {
return qualifiers;
}
/**
* Returns the qualifiers to be used for registering a validator or validator factory.
*/
@SuppressWarnings("serial")
private static Set<Annotation> determineRequiredQualifiers(boolean isDefaultProvider,
boolean isHibernateValidator) {
HashSet<Annotation> qualifiers = newHashSet( 3 );
if ( isDefaultProvider ) {
qualifiers.add(
new AnnotationLiteral<Default>() {
}
);
}
if ( isHibernateValidator ) {
qualifiers.add(
new AnnotationLiteral<HibernateValidator>() {
}
);
}
qualifiers.add(
new AnnotationLiteral<Any>() {
}
);
return qualifiers;
}
@Override
public String toString() {
return "ValidationProviderHelper [isDefaultProvider="
+ isDefaultProvider + ", isHibernateValidator="
+ isHibernateValidator + ", validatorFactoryClass="
+ validatorFactoryClass + ", validatorClass=" + validatorClass
+ ", qualifiers=" + qualifiers + "]";
}
}
/*
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat, Inc. and/or its affiliates, and individual contributors
* Copyright 2012-2014, Red Hat, Inc. and/or its affiliates, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
......@@ -19,44 +19,48 @@
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.enterprise.inject.spi.PassivationCapable;
import javax.enterprise.util.AnnotationLiteral;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.executable.ExecutableValidator;
import org.hibernate.validator.cdi.HibernateValidator;
import org.hibernate.validator.internal.engine.ValidatorImpl;
import org.hibernate.validator.internal.util.CollectionHelper;
import org.hibernate.validator.internal.util.classhierarchy.ClassHierarchyHelper;
/**
* A {@link Bean} representing a {@link Validator}. There is one instance of this type representing the default
* validator and optionally another instance representing the HV validator in case the default provider is not HV.
*
* @author Hardy Ferentschik
* @author Gunnar Morling
*/
public class ValidatorBean implements Bean<Validator>, PassivationCapable {
private final BeanManager beanManager;
private final Set<Annotation> qualifiers;
private final ValidationProviderHelper validationProviderHelper;
private final Set<Type> types;
private final Bean<?> validatorFactoryBean;
public ValidatorBean(BeanManager beanManager, Set<Annotation> qualifiers) {
public ValidatorBean(BeanManager beanManager, Bean<?> validatorFactoryBean,
ValidationProviderHelper validationProviderHelper) {
this.beanManager = beanManager;
this.qualifiers = CollectionHelper.newHashSet();
this.qualifiers.addAll( qualifiers );
this.qualifiers.add(
new AnnotationLiteral<Any>() {
}
this.validatorFactoryBean = validatorFactoryBean;
this.validationProviderHelper = validationProviderHelper;
this.types = Collections.unmodifiableSet(
CollectionHelper.<Type>newHashSet(
ClassHierarchyHelper.getHierarchy( validationProviderHelper.getValidatorBeanClass() )
)
);
}
@Override
public Class<?> getBeanClass() {
return ValidatorImpl.class;
return validationProviderHelper.getValidatorBeanClass();
}
@Override
......@@ -71,7 +75,7 @@ public String getName() {
@Override
public Set<Annotation> getQualifiers() {
return qualifiers;
return validationProviderHelper.getQualifiers();
}
@Override
......@@ -86,12 +90,6 @@ public Set<Class<? extends Annotation>> getStereotypes() {
@Override
public Set<Type> getTypes() {
Set<Type> types = new HashSet<Type>();
types.add( Validator.class );
types.add( ExecutableValidator.class );
types.add( Object.class );
return types;
}
......@@ -107,30 +105,26 @@ public boolean isNullable() {
@Override
public Validator create(CreationalContext<Validator> ctx) {
ValidatorFactory validatorFactory = getReference( beanManager, ValidatorFactory.class );
ValidatorFactory validatorFactory = createValidatorFactory();
return validatorFactory.getValidator();
}
private ValidatorFactory createValidatorFactory() {
CreationalContext<?> context = beanManager.createCreationalContext( validatorFactoryBean );
return (ValidatorFactory) beanManager.getReference( validatorFactoryBean, ValidatorFactory.class, context );
}
@Override
public void destroy(Validator instance, CreationalContext<Validator> ctx) {
}
@SuppressWarnings("unchecked")
private <T> T getReference(BeanManager beanManager, Class<T> clazz) {
Set<Bean<?>> beans = beanManager.getBeans( clazz, qualifiers.toArray( new Annotation[qualifiers.size()] ) );
for ( Bean<?> bean : beans ) {
for ( Annotation annotation : bean.getQualifiers() ) {
if ( annotation.annotationType().getName().equals( HibernateValidator.class.getName() ) ) {
CreationalContext<?> context = beanManager.createCreationalContext( bean );
return (T) beanManager.getReference( bean, clazz, context );
}
}
}
return null;
@Override
public String getId() {
return ValidatorBean.class.getName() + "_" + ( validationProviderHelper.isDefaultProvider() ? "default" : "hv" );
}
@Override
public String getId() {
return ValidatorBean.class.getName();
}
@Override
public String toString() {
return "ValidatorBean [id=" + getId() + "]";
}
}
/*
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat, Inc. and/or its affiliates, and individual contributors
* Copyright 2012-2014, Red Hat, Inc. and/or its affiliates, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
......@@ -22,12 +22,10 @@
import java.util.Set;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.enterprise.inject.spi.PassivationCapable;
import javax.enterprise.util.AnnotationLiteral;
import javax.validation.BootstrapConfiguration;
import javax.validation.Configuration;
import javax.validation.ConstraintValidatorFactory;
......@@ -37,32 +35,41 @@
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import org.hibernate.validator.internal.engine.ValidatorFactoryImpl;
import org.hibernate.validator.internal.util.CollectionHelper;
import org.hibernate.validator.internal.util.ReflectionHelper;
import org.hibernate.validator.internal.util.classhierarchy.ClassHierarchyHelper;
import static org.hibernate.validator.internal.util.CollectionHelper.newHashSet;
/**
* A {@link Bean} representing a {@link ValidatorFactory}. There is one instance of this type representing the default
* validator factory and optionally another instance representing the HV validator factory in case the default provider
* is not HV.
*
* @author Hardy Ferentschik
* @author Gunnar Morling
*/
public class ValidatorFactoryBean implements Bean<ValidatorFactory>, PassivationCapable {
private final BeanManager beanManager;
private final Set<Annotation> qualifiers;
private final Set<DestructibleBeanInstance<?>> destructibleResources;
private final ValidationProviderHelper validationProviderHelper;
private final Set<Type> types;
public ValidatorFactoryBean(BeanManager beanManager, Set<Annotation> qualifiers) {
public ValidatorFactoryBean(BeanManager beanManager, ValidationProviderHelper validationProviderHelper) {
this.beanManager = beanManager;
this.destructibleResources = CollectionHelper.newHashSet();
this.qualifiers = CollectionHelper.newHashSet();
this.qualifiers.addAll( qualifiers );
this.qualifiers.add(
new AnnotationLiteral<Any>() {
}
this.destructibleResources = newHashSet( 4 );
this.validationProviderHelper = validationProviderHelper;
this.types = Collections.unmodifiableSet(
CollectionHelper.<Type>newHashSet(
ClassHierarchyHelper.getHierarchy( validationProviderHelper.getValidatorFactoryBeanClass() )
)
);
}
@Override
public Class<?> getBeanClass() {
return ValidatorFactoryImpl.class;
return validationProviderHelper.getValidatorFactoryBeanClass();
}
@Override
......@@ -77,7 +84,7 @@ public String getName() {
@Override
public Set<Annotation> getQualifiers() {
return qualifiers;
return validationProviderHelper.getQualifiers();
}
@Override
......@@ -92,11 +99,6 @@ public Set<Class<? extends Annotation>> getStereotypes() {
@Override
public Set<Type> getTypes() {
Set<Type> types = CollectionHelper.newHashSet();
types.add( ValidatorFactory.class );
types.add( Object.class );
return types;
}
......@@ -112,8 +114,7 @@ public boolean isNullable() {
@Override
public ValidatorFactory create(CreationalContext<ValidatorFactory> ctx) {
Configuration<?> config = Validation.byProvider( org.hibernate.validator.HibernateValidator.class )
.configure();
Configuration<?> config = getConfiguration();
config.constraintValidatorFactory( createConstraintValidatorFactory( config ) );
config.messageInterpolator( createMessageInterpolator( config ) );
......@@ -207,8 +208,19 @@ private <T> T createInstance(Class<T> type) {
return destructibleInstance.getInstance();
}
@Override
public String getId() {
return ValidatorFactoryBean.class.getName();
}
private Configuration<?> getConfiguration() {
return validationProviderHelper.isDefaultProvider() ?
Validation.byDefaultProvider().configure() :
Validation.byProvider( org.hibernate.validator.HibernateValidator.class ).configure();
}
@Override
public String getId() {
return ValidatorFactoryBean.class.getName() + "_" + ( validationProviderHelper.isDefaultProvider() ? "default" : "hv" );
}
@Override
public String toString() {
return "ValidatorFactoryBean [id=" + getId() + "]";
}
}
......@@ -29,7 +29,7 @@
* @author Hardy Ferentschik
* @author Gunnar Morling
*/
@Target({ ElementType.METHOD, ElementType.TYPE, ElementType.CONSTRUCTOR })
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@InterceptorBinding
public @interface MethodValidated {
......
......@@ -43,7 +43,7 @@
*/
@MethodValidated
@Interceptor
@Priority(4800)
@Priority(Interceptor.Priority.PLATFORM_AFTER + 800)
public class ValidationInterceptor implements Serializable {
private static final long serialVersionUID = 604440259030722151L;
......@@ -86,7 +86,7 @@ public Object validateMethodInvocation(InvocationContext ctx) throws Exception {
Object result = ctx.proceed();
violations = validator.forExecutables().validateReturnValue(
violations = executableValidator.validateReturnValue(
ctx.getTarget(),
ctx.getMethod(),
result
......@@ -111,7 +111,6 @@ public Object validateMethodInvocation(InvocationContext ctx) throws Exception {
* in case at least one constraint violation occurred either during parameter or return value validation.
*/
@AroundConstruct
@SuppressWarnings("unchecked")
public void validateConstructorInvocation(InvocationContext ctx) throws Exception {
ExecutableValidator executableValidator = validator.forExecutables();
Set<ConstraintViolation<Object>> violations = executableValidator.validateConstructorParameters(
......
/*
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat, Inc. and/or its affiliates, and individual contributors
* Copyright 2012-2014, Red Hat, Inc. and/or its affiliates, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
......@@ -18,10 +18,12 @@
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.spi.AfterBeanDiscovery;
import javax.enterprise.inject.spi.Annotated;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.ProcessBean;
......@@ -29,16 +31,19 @@
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.easymock.EasyMock;
import org.easymock.IAnswer;
import org.junit.Before;
import org.junit.Test;
import org.hibernate.validator.cdi.HibernateValidator;
import org.hibernate.validator.internal.cdi.ValidationExtension;
import org.hibernate.validator.internal.cdi.ValidationProviderHelper;
import org.hibernate.validator.internal.cdi.ValidatorBean;
import org.hibernate.validator.internal.cdi.ValidatorFactoryBean;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.isA;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
......@@ -102,17 +107,26 @@ public void testNullParameters() {
@Test
public void testRegisterBeanWithDefaultQualifier() {
// setup the mocks
Set<Annotation> qualifiers = new HashSet<Annotation>();
qualifiers.add(
new AnnotationLiteral<HibernateValidator>() {
}
ValidationProviderHelper validationProviderHelper = ValidationProviderHelper.forHibernateValidator();
expect( processBeanMock.getBean() ).andReturn(
new ValidatorFactoryBean(
beanManagerMock,
validationProviderHelper
)
);
expect( processBeanMock.getBean() ).andReturn(
new ValidatorBean(
beanManagerMock,
validatorFactoryBeanMock,
validationProviderHelper
)
);
expect( processBeanMock.getBean() ).andReturn( new ValidatorFactoryBean( beanManagerMock, qualifiers ) );
expect( processBeanMock.getBean() ).andReturn( new ValidatorBean( beanManagerMock, qualifiers ) );
afterBeanDiscoveryMock.addBean( isA( ValidatorFactoryBean.class ) );
expectLastCall();
afterBeanDiscoveryMock.addBean( isA( ValidatorBean.class ) );
expectLastCall();
// get the mocks ready
replay( processBeanMock, afterBeanDiscoveryMock, beanManagerMock );
......@@ -129,7 +143,30 @@ public void testRegisterBeanWithDefaultQualifier() {
@Test
public void testRegisterBeanWithCustomQualifier() {
afterBeanDiscoveryMock.addBean( isA( ValidatorFactoryBean.class ) );
expectLastCall().andAnswer(
new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
ProcessBean<?> event = getProcessBeanEvent( (Bean<ValidatorFactory>) EasyMock.getCurrentArguments()[0] );
extension.processBean( event );
return null;
}
}
);
afterBeanDiscoveryMock.addBean( isA( ValidatorBean.class ) );
expectLastCall().andAnswer(
new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
ProcessBean<?> event = getProcessBeanEvent( (Bean<ValidatorBean>) EasyMock.getCurrentArguments()[0] );
extension.processBean( event );
return null;
}
}
);
// get the mocks ready
replay( afterBeanDiscoveryMock, beanManagerMock );
......@@ -144,30 +181,34 @@ public void testRegisterBeanWithCustomQualifier() {
@Test
public void testNoRegistrationRequired() {
// setup the mocks
Set<Annotation> qualifiers = new HashSet<Annotation>();
qualifiers.add(
new AnnotationLiteral<HibernateValidator>() {
}
);
qualifiers.add(
new AnnotationLiteral<Default>() {
}
);
Set<Type> validatorFactoryBeanTypes = new HashSet<Type>();
validatorFactoryBeanTypes.add( ValidatorFactory.class );
Set<Type> validatorBeanTypes = new HashSet<Type>();
validatorBeanTypes.add( Validator.class );
Set<Annotation> qualifiers = Collections.<Annotation>singleton(
new AnnotationLiteral<Default>() {
}
);
expect( processBeanMock.getBean() ).andReturn( validatorFactoryBeanMock );
expect( validatorFactoryBeanMock.getTypes() ).andReturn( validatorFactoryBeanTypes );
expect( validatorFactoryBeanMock.getQualifiers() ).andReturn( qualifiers );
expect( validatorFactoryBeanMock.getQualifiers() ).andReturn( qualifiers );
afterBeanDiscoveryMock.addBean( isA( ValidatorFactoryBean.class ) );
expectLastCall();
expect( processBeanMock.getBean() ).andReturn( validatorBeanMock );
expect( validatorBeanMock.getTypes() ).andReturn( validatorBeanTypes );
expect( validatorBeanMock.getTypes() ).andReturn( validatorBeanTypes );
expect( validatorBeanMock.getQualifiers() ).andReturn( qualifiers );
expect( validatorBeanMock.getQualifiers() ).andReturn( qualifiers );
afterBeanDiscoveryMock.addBean( isA( ValidatorBean.class ) );
expectLastCall();
// get the mocks ready
replay( processBeanMock, validatorFactoryBeanMock, validatorBeanMock, afterBeanDiscoveryMock, beanManagerMock );
......@@ -191,5 +232,24 @@ public void testProcessAnnotatedTypeNullParameter() {
// success
}
}
private <T> ProcessBean<T> getProcessBeanEvent(final Bean<T> bean) {
return new ProcessBean<T>() {
@Override
public Annotated getAnnotated() {
return null;
}
@Override
public Bean<T> getBean() {
return bean;
}
@Override
public void addDefinitionError(Throwable t) {
}
};
}
}
/*
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat, Inc. and/or its affiliates, 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.validator.test.internal.cdi.injection;
import javax.inject.Inject;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.NotNull;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.hibernate.validator.HibernateValidatorFactory;
import org.hibernate.validator.cdi.HibernateValidator;
import org.hibernate.validator.internal.engine.ValidatorImpl;
import org.hibernate.validator.test.internal.cdi.injection.MyValidationProvider.MyValidator;
import org.hibernate.validator.test.internal.cdi.injection.MyValidationProvider.MyValidatorFactory;
import org.hibernate.validator.testutil.TestForIssue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Tests the injection of validator and validator factory if the default provider is not Hibernate Validator.
*
* @author Gunnar Morling
*/
@RunWith(Arquillian.class)
@TestForIssue(jiraKey = "HV-858")
public class InjectionOfCustomProviderTest {
@Deployment
public static JavaArchive createDeployment() {
return ShrinkWrap.create( JavaArchive.class )
.addClass( MyValidationProvider.class )
.addAsResource(
InjectionOfCustomProviderTest.class.getResource( "validation.xml" ),
"META-INF/validation.xml"
)
.add(
new StringAsset( "org.hibernate.validator.test.internal.cdi.injection.MyValidationProvider" ),
"META-INF/services/javax.validation.spi.ValidationProvider"
);
}
@Inject
ValidatorFactory defaultValidatorFactory;
@Inject
Validator defaultValidator;
@Inject
MyValidatorFactory myValidatorFactory;
@Inject
MyValidator myValidator;
@Inject
@HibernateValidator
ValidatorFactory hibernateValidatorFactory;
@Inject
@HibernateValidator
Validator hibernateValidator;
@Inject
@HibernateValidator
HibernateValidatorFactory hibernateValidatorSpecificFactory;
@Test
public void testInjectionOfDefaultFactory() throws Exception {
assertNotNull( defaultValidatorFactory );
assertTrue( defaultValidatorFactory instanceof MyValidatorFactory );
assertTrue( defaultValidatorFactory.unwrap( MyValidatorFactory.class ) instanceof MyValidatorFactory );
assertNotNull( myValidatorFactory );
}
@Test
public void testInjectionOfDefaultValidator() throws Exception {
assertNotNull( defaultValidator );
assertTrue( defaultValidator instanceof MyValidator );
assertNotNull( defaultValidator.forExecutables() );
assertNotNull( myValidator );
assertNotNull( myValidator.forExecutables() );
assertEquals( 1, defaultValidator.validate( new TestEntity() ).size() );
assertEquals( 1, myValidator.validate( new TestEntity() ).size() );
}
@Test
public void testInjectionOfHibernateFactory() throws Exception {
assertNotNull( hibernateValidatorFactory );
assertNotNull( hibernateValidatorSpecificFactory );
assertEquals( ValidatorImpl.class, hibernateValidatorFactory.getValidator().getClass() );
assertEquals( ValidatorImpl.class, hibernateValidatorSpecificFactory.getValidator().getClass() );
}
@Test
public void testInjectionOfHibernateValidator() throws Exception {
assertNotNull( hibernateValidator );
assertNotNull( hibernateValidator.forExecutables() );
assertNotNull( hibernateValidator.unwrap( Validator.class ) );
assertEquals( 1, hibernateValidator.validate( new TestEntity() ).size() );
}
public static class TestEntity {
@NotNull
private String foo;
}
}
......@@ -29,10 +29,11 @@
import org.junit.Test;
import org.junit.runner.RunWith;
import org.hibernate.validator.HibernateValidatorFactory;
import org.hibernate.validator.cdi.HibernateValidator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author Hardy Ferentschik
......@@ -60,12 +61,15 @@ public static JavaArchive createDeployment() {
@Inject
Validator defaultValidator;
@Inject
HibernateValidatorFactory hibernateValidatorFactory;
@Test
public void testInjectionOfQualifiedBeans() throws Exception {
assertNotNull( validatorFactory );
assertNotNull( validator );
assertTrue( validator.validate( new TestEntity() ).size() == 1 );
assertEquals( 1, validator.validate( new TestEntity() ).size() );
}
@Test
......@@ -73,7 +77,13 @@ public void testInjectionOfDefaultBeans() throws Exception {
assertNotNull( defaultValidatorFactory );
assertNotNull( defaultValidator );
assertTrue( defaultValidator.validate( new TestEntity() ).size() == 1 );
assertEquals( 1, defaultValidator.validate( new TestEntity() ).size() );
}
@Test
public void testInjectionOfHibernateValidatorFactory() throws Exception {
assertNotNull( hibernateValidatorFactory );
assertEquals( 1, hibernateValidatorFactory.getValidator().validate( new TestEntity() ).size() );
}
public static class TestEntity {
......
/*
* JBoss, Home of Professional Open Source
* Copyright 2013-2014, Red Hat, Inc. and/or its affiliates, 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.validator.test.internal.cdi.injection;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.NotNull;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.hibernate.validator.HibernateValidatorFactory;
import org.hibernate.validator.cdi.HibernateValidator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Tests the case where {@code @Default}-scoped beans for validator and validator factory have already beenr registered
* by another component and only the {@code @HibernateValidator}-scoped beans must be registered.
*
* @author Hardy Ferentschik
* @author Gunnar Morling
*/
@RunWith(Arquillian.class)
public class InjectionWithExternallyProvidedDefaultBeansTest {
@Deployment
public static JavaArchive createDeployment() {
return ShrinkWrap.create( JavaArchive.class )
.addAsManifestResource( EmptyAsset.INSTANCE, "beans.xml" );
}
@HibernateValidator
@Inject
ValidatorFactory validatorFactory;
@HibernateValidator
@Inject
Validator validator;
@Inject
ValidatorFactory defaultValidatorFactory;
@Inject
Validator defaultValidator;
@Inject
@Any
HibernateValidatorFactory hibernateValidatorFactory;
@Test
public void testInjectionOfQualifiedBeans() throws Exception {
assertNotNull( validatorFactory );
assertNotNull( validator );
assertEquals( 1, validator.validate( new TestEntity() ).size() );
}
@Test
public void testInjectionOfDefaultBeans() throws Exception {
assertNotNull( defaultValidatorFactory );
assertNotNull( defaultValidator );
assertEquals( 1, defaultValidator.validate( new TestEntity() ).size() );
}
@Test
public void testInjectionOfHibernateValidatorFactory() throws Exception {
assertNotNull( hibernateValidatorFactory );
assertEquals( 1, hibernateValidatorFactory.getValidator().validate( new TestEntity() ).size() );
}
public static class TestEntity {
@NotNull
private String foo;
}
@ApplicationScoped
public static class ProducerBean {
@Produces
ValidatorFactory produceDefaultValidatorFactory() {
return Validation.buildDefaultValidatorFactory();
}
@Produces
Validator produceDefaultValidator() {
return Validation.buildDefaultValidatorFactory().getValidator();
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment