Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
  * JBoss, Home of Professional Open Source
  * Copyright 2009, 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 javax.validation;
 
 import java.util.List;
This class is the entry point for Bean Validation. There are three ways to bootstrap it:
  • The easiest approach is to build the default ValidatorFactory.
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    In this case, the default validation provider resolver will be used to locate available providers. The chosen provider is defined as followed:
    • if the XML configuration defines a provider, this provider is used
    • if the XML configuration does not define a provider or if no XML configuration is present the first provider returned by the ValidationProviderResolver instance is used.
  • The second bootstrap approach allows to choose a custom ValidationProviderResolver. The chosen ValidationProvider is then determined in the same way as in the default bootstrapping case (see above).
    Configuration<?> configuration = Validation
        .byDefaultProvider()
        .providerResolver( new MyResolverStrategy() )
        .configure();
     ValidatorFactory factory = configuration.buildValidatorFactory();
     
  • The third approach allows you to specify explicitly and in a type safe fashion the expected provider.

    Optionally you can choose a custom ValidationProviderResolver.

    ACMEConfiguration configuration = Validation
        .byProvider(ACMEProvider.class)
        .providerResolver( new MyResolverStrategy() )  // optionally set the provider resolver
        .configure();
     ValidatorFactory factory = configuration.buildValidatorFactory();
     
Note:
  • The ValidatorFactory object built by the bootstrap process should be cached and shared amongst Validator consumers.
  • This class is thread-safe.

Author(s):
Emmanuel Bernard
Hardy Ferentschik
 
 public class Validation {

Build and return a ValidatorFactory instance based on the default Bean Validation provider and following the XML configuration.

The provider list is resolved using the default validation provider resolver logic.

The code is semantically equivalent to Validation.byDefaultProvider().configure().buildValidatorFactory()

Returns:
ValidatorFactory instance.
Throws:
ValidationException if the ValidatorFactory cannot be built
	}

Build a Configuration. The provider list is resolved using the strategy provided to the bootstrap state.
 Configuration&lt?> configuration = Validation
    .byDefaultProvider()
    .providerResolver( new MyResolverStrategy() )
    .configure();
 ValidatorFactory factory = configuration.buildValidatorFactory();
 
The provider can be specified in the XML configuration. If the XML configuration does not exist or if no provider is specified, the first available provider will be returned.

Returns:
instance building a generic Configuration compliant with the bootstrap state provided.
	public static GenericBootstrap byDefaultProvider() {
		return new GenericBootstrapImpl();
	}

Build a Configuration for a particular provider implementation. Optionally overrides the provider resolution strategy used to determine the provider.

Used by applications targeting a specific provider programmatically.

 ACMEConfiguration configuration =
     Validation.byProvider(ACMEProvider.class)
             .providerResolver( new MyResolverStrategy() )
             .configure();
 
, where ACMEConfiguration is the Configuration sub interface uniquely identifying the ACME Bean Validation provider. and ACMEProvider is the ValidationProvider implementation of the ACME provider.

Parameters:
providerType the ValidationProvider implementation type
Returns:
instance building a provider specific Configuration sub interface implementation.
	public static <T extends Configuration<T>, U extends ValidationProvider<T>>
		return new ProviderSpecificBootstrapImpl<T, U>( providerType );
	}
	//private class, not exposed
	private static class ProviderSpecificBootstrapImpl<T extends Configuration<T>, U extends ValidationProvider<T>>
			implements ProviderSpecificBootstrap<T> {
		private final Class<U> validationProviderClass;
		public ProviderSpecificBootstrapImpl(Class<U> validationProviderClass) {
			this. = validationProviderClass;
		}

Optionally define the provider resolver implementation used. If not defined, use the default ValidationProviderResolver

Parameters:
resolver ValidationProviderResolver implementation used
Returns:
self
			this. = resolver;
			return this;
		}

Determine the provider implementation suitable for byProvider(Class) and delegate the creation of this specific Configuration subclass to the provider.

Returns:
a Configuration sub interface implementation
		public T configure() {
			if (  == null ) {
						"builder is mandatory. Use Validation.byDefaultProvider() to use the generic provider discovery mechanism"
				);
			}
			//used mostly as a BootstrapState
			if (  == null ) {
			}
			else {
				//stay null if no resolver is defined
			}
			List<ValidationProvider<?>> resolvers;
			try {
			}
			catch ( RuntimeException re ) {
				throw new ValidationException"Unable to get available provider resolvers."re );
			}
			for ( ValidationProvider provider : resolvers ) {
					ValidationProvider<T> specificProvider = .castprovider );
					return specificProvider.createSpecializedConfigurationstate );
				}
			}
			throw new ValidationException"Unable to find provider: " +  );
		}
	}
	//private class, not exposed
	private static class GenericBootstrapImpl implements GenericBootstrapBootstrapState {
			this. = resolver;
			return this;
		}
			return ;
		}
			if (  == null ) {
			}
		}
		public Configuration<?> configure() {
			ValidationProviderResolver resolver = this. == null ?
			List<ValidationProvider<?>> validationProviders;
			try {
				validationProviders = resolver.getValidationProviders();
			}
			// don't wrap existing ValidationExceptions in another ValidationException
			catch ( ValidationException e ) {
				throw e;
			}
			// if any other exception occurs wrap it in a ValidationException
			catch ( RuntimeException re ) {
				throw new ValidationException"Unable to get available provider resolvers."re );
			}
			if ( validationProviders.size() == 0 ) {
				String msg = "Unable to create a Configuration, because no Bean Validation provider could be found." +
						" Add a provider like Hibernate Validator (RI) to your classpath.";
				throw new ValidationExceptionmsg );
			}
			Configuration<?> config;
			try {
				config = resolver.getValidationProviders().get( 0 ).createGenericConfigurationthis );
			}
			catch ( RuntimeException re ) {
				throw new ValidationException"Unable to instantiate Configuration."re );
			}
			return config;
		}
	}

Find ValidationProvider according to the default ValidationProviderResolver defined in the Bean Validation specification. This implementation first uses thread's context classloader to locate providers. If no suitable provider is found using the aforementioned class loader, it uses current class loader. If it still does not find any suitable provider, it tries to locate the built-in provider using the current class loader.

Author(s):
Emmanuel Bernard
Hardy Ferentschik
	private static class DefaultValidationProviderResolver implements ValidationProviderResolver {
			// class loading and ServiceLoader methods should happen in a PrivilegedAction
			return GetValidationProviderListAction.getValidationProviderList();
		}
	}
	private static class GetValidationProviderListAction implements PrivilegedAction<List<ValidationProvider<?>>> {
		//cache per classloader for an appropriate discovery
		//keep them in a weak hash map to avoid memory leaks and allow proper hot redeployment
			if ( System.getSecurityManager() != null ) {
				return AccessController.doPrivilegedaction );
			}
			else {
				return action.run();
			}
		}
		public List<ValidationProvider<?>> run() {
			// Option #1: try first context class loader
			ClassLoader classloader = Thread.currentThread().getContextClassLoader();
			List<ValidationProvider<?>> cachedContextClassLoaderProviderList = getCachedValidationProvidersclassloader );
			if ( cachedContextClassLoaderProviderList != null ) {
				// if already processed return the cached provider list
				return cachedContextClassLoaderProviderList;
			}
			List<ValidationProvider<?>> validationProviderList = loadProvidersclassloader );
			// Option #2: if we cannot find any service files with the context class loader use the current class loader
			if ( validationProviderList.isEmpty() ) {
				List<ValidationProvider<?>> cachedCurrentClassLoaderProviderList = getCachedValidationProviders(
						classloader
				);
				if ( cachedCurrentClassLoaderProviderList != null ) {
					// if already processed return the cached provider list
					return cachedCurrentClassLoaderProviderList;
				}
				validationProviderList = loadProvidersclassloader );
			}
			// cache the detected providers against the classloader in which they were found
			cacheValidationProvidersclassloadervalidationProviderList );
			return validationProviderList;
		}
		private List<ValidationProvider<?>> loadProviders(ClassLoader classloader) {
			ServiceLoader<ValidationProviderloader = ServiceLoader.loadValidationProvider.classclassloader );
			Iterator<ValidationProviderproviderIterator = loader.iterator();
			List<ValidationProvider<?>> validationProviderList = new ArrayList<ValidationProvider<?>>();
			while ( providerIterator.hasNext() ) {
				try {
					validationProviderList.addproviderIterator.next() );
				}
				catch ( ServiceConfigurationError e ) {
					// ignore, because it can happen when multiple
					// providers are present and some of them are not class loader
					// compatible with our API.
				}
			}
			return validationProviderList;
		}
		private synchronized List<ValidationProvider<?>> getCachedValidationProviders(ClassLoader classLoader) {
			return ref != null ? ref.get() : null;
		}
		private synchronized void cacheValidationProviders(ClassLoader classLoaderList<ValidationProvider<?>> providers) {
			.putclassLoadernew SoftReference<List<ValidationProvider<?>>>( providers ) );
		}
	}
New to GrepCode? Check out our FAQ X