javax.validation.Configuration类的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(14.4k)|赞(0)|评价(0)|浏览(337)

本文整理了Java中javax.validation.Configuration类的一些代码示例,展示了Configuration类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Configuration类的具体详情如下:
包路径:javax.validation.Configuration
类名称:Configuration

Configuration介绍

[英]Receives configuration information, selects the appropriate Bean Validation provider and builds the appropriate ValidatorFactory.

Usage:

//provided by one of the Validation bootstrap methods 
Configuration<?> configuration = 
ValidatorFactory = configuration 
.messageInterpolator( new CustomMessageInterpolator() ) 
.buildValidatorFactory();

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 ValidationProvider). If none is explicitly requested, the default ValidationProviderResolver is used.

The provider is selected in the following way:

  • if a specific provider is requested programmatically using Validation#byProvider(Class), find the first provider implementing the provider class requested and use it
  • if a specific provider is requested in META-INF/validation.xml, find the first provider implementing the provider class requested and use it
  • otherwise, use the first provider returned by the ValidationProviderResolver

Implementations are not meant to be thread-safe.
[中]接收配置信息,选择适当的Bean验证提供程序并构建适当的验证器工厂。
用法:

//provided by one of the Validation bootstrap methods 
Configuration<?> configuration = 
ValidatorFactory = configuration 
.messageInterpolator( new CustomMessageInterpolator() ) 
.buildValidatorFactory();

默认情况下,从META-INF/validation检索配置信息。xml。可以使用一个或多个配置方法覆盖从XML文件检索的配置。
ValidationProviderResolver在配置时指定(请参阅ValidationProvider)。如果没有明确请求,则使用默认的ValidationProviderResolver。
通过以下方式选择提供程序:
*如果使用Validation#byProvider(Class)以编程方式请求特定的提供程序,请找到实现请求的提供程序类的第一个提供程序并使用它
*如果在META-INF/验证中请求了特定的提供程序。xml,找到实现所请求的提供程序类的第一个提供程序并使用它
*否则,请使用ValidationProviderResolver返回的第一个提供程序
实现并不意味着线程安全。

代码示例

代码示例来源:origin: com.atlassian.plugins.rest/atlassian-rest-common

public ValidationInterceptor(MessageInterpolator messageInterpolator) {
  // Yes, this cast is unnecessary in Java 6, but seems to be required in Java 5
  this.factory = ((Configuration) Validation.byDefaultProvider().configure().messageInterpolator(messageInterpolator)).buildValidatorFactory();
}

代码示例来源:origin: spring-projects/spring-framework

Configuration<?> configuration;
if (this.providerClass != null) {
  ProviderSpecificBootstrap bootstrap = Validation.byProvider(this.providerClass);
  if (this.validationProviderResolver != null) {
    bootstrap = bootstrap.providerResolver(this.validationProviderResolver);
  GenericBootstrap bootstrap = Validation.byDefaultProvider();
  if (this.validationProviderResolver != null) {
    bootstrap = bootstrap.providerResolver(this.validationProviderResolver);
  configuration = bootstrap.configure();
  targetInterpolator = configuration.getDefaultMessageInterpolator();
configuration.messageInterpolator(new LocaleContextMessageInterpolator(targetInterpolator));
  configuration.traversableResolver(this.traversableResolver);
  configuration.constraintValidatorFactory(targetConstraintValidatorFactory);
  for (Resource location : this.mappingLocations) {
    try {
      configuration.addMapping(location.getInputStream());
this.validatorFactory = configuration.buildValidatorFactory();
setTargetValidator(this.validatorFactory.getValidator());

代码示例来源:origin: org.jboss.ironjacamar/ironjacamar-core-impl

/**
* Create a validator factory
* @return The factory
*/
public static ValidatorFactory createValidatorFactory()
{
 Configuration configuration = Validation.byDefaultProvider().configure();
 Configuration<?> conf = configuration.traversableResolver(new JCATraversableResolver());
 return conf.buildValidatorFactory();
}

代码示例来源:origin: org.hibernate.jsr303.tck/jsr303-tck

@Test
@SpecAssertion(section = "4.4.5", id = "a")
public void testBuildDefaultValidatorFactory() {
  ValidatorFactory defaultFactory = Validation.buildDefaultValidatorFactory();
  assertNotNull( defaultFactory, "We should be able to get a factory." );
  ValidatorFactory defaultProviderFactory = Validation.byDefaultProvider().configure().buildValidatorFactory();
  assertNotNull( defaultProviderFactory, "We should be able to get a factory." );
  assertEquals( defaultFactory.getClass(), defaultFactory.getClass(), "The factories have to be identical." );
}

代码示例来源:origin: javax.validation/validation-api

/**
 * Builds and returns a {@link ValidatorFactory} instance based on the
 * default Bean Validation provider and following the XML configuration.
 * <p>
 * The provider list is resolved using the default validation provider resolver
 * logic.
 * <p>
 * The code is semantically equivalent to
 * {@code Validation.byDefaultProvider().configure().buildValidatorFactory()}.
 *
 * @return {@code ValidatorFactory} instance
 *
 * @throws NoProviderFoundException if no Bean Validation provider was found
 * @throws ValidationException if a Bean Validation provider was found but the
 * {@code ValidatorFactory} cannot be built
 */
public static ValidatorFactory buildDefaultValidatorFactory() {
  return byDefaultProvider().configure().buildValidatorFactory();
}

代码示例来源:origin: apache/incubator-dubbo

@SuppressWarnings({"unchecked", "rawtypes"})
public JValidator(URL url) {
  this.clazz = ReflectUtils.forName(url.getServiceInterface());
  String jvalidation = url.getParameter("jvalidation");
  ValidatorFactory factory;
  if (jvalidation != null && jvalidation.length() > 0) {
    factory = Validation.byProvider((Class) ReflectUtils.forName(jvalidation)).configure().buildValidatorFactory();
  } else {
    factory = Validation.buildDefaultValidatorFactory();
  }
  this.validator = factory.getValidator();
  this.methodClassMap = new ConcurrentHashMap<String, Class>();
}

代码示例来源:origin: org.apache.openejb/openejb-core

target.ignoreXmlConfiguration();
    @SuppressWarnings("unchecked") final
    Class<MessageInterpolator> clazz = (Class<MessageInterpolator>) classLoader.loadClass(messageInterpolatorClass);
    target.messageInterpolator(clazz.newInstance());
  } catch (final Exception e) {
    logger.warning("Unable to set " + messageInterpolatorClass + " as message interpolator.", e);
    @SuppressWarnings("unchecked") final
    Class<TraversableResolver> clazz = (Class<TraversableResolver>) classLoader.loadClass(traversableResolverClass);
    target.traversableResolver(clazz.newInstance());
  } catch (final Exception e) {
    logger.warning("Unable to set " + traversableResolverClass + " as traversable resolver.", e);
    @SuppressWarnings("unchecked") final
    Class<ConstraintValidatorFactory> clazz = (Class<ConstraintValidatorFactory>) classLoader.loadClass(constraintFactoryClass);
    target.constraintValidatorFactory(clazz.newInstance());
  } catch (final Exception e) {
    logger.warning("Unable to set " + constraintFactoryClass + " as constraint factory.", e);
    logger.debug("Found property '" + property.getName() + "' with value '" + property.getValue());
  target.addProperty(property.getName(), property.getValue());
    logger.warning("Unable to open input stream for mapping file " + mappingFileName + ". It will be ignored");
  } else {
    target.addMapping(in);

代码示例来源:origin: org.springframework.boot/spring-boot

@Override
public MessageInterpolator getObject() throws BeansException {
  try {
    return Validation.byDefaultProvider().configure()
        .getDefaultMessageInterpolator();
  }
  catch (ValidationException ex) {
    MessageInterpolator fallback = getFallback();
    if (fallback != null) {
      return fallback;
    }
    throw ex;
  }
}

代码示例来源:origin: wildfly/wildfly

private ValidatorFactory initFactory() {
  final ClassLoader oldTCCL = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
  try {
    WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);
    if (configuration == null) {
      return Validation.byDefaultProvider().providerResolver(new WildFlyProviderResolver()).configure()
          .buildValidatorFactory();
    } else {
      return configuration.buildValidatorFactory();
    }
  } finally {
    WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTCCL);
  }
}

代码示例来源:origin: org.hibernate.beanvalidation.tck/beanvalidation-tck-tests

@Test(expectedExceptions = ValueExtractorDefinitionException.class)
@SpecAssertion(section = Sections.VALUEEXTRACTORDEFINITION_EXTRACTEDVALUE, id = "b")
@SpecAssertion(section = Sections.VALUEEXTRACTORDEFINITION_EXTRACTEDVALUE, id = "f")
@SpecAssertion(section = Sections.EXCEPTION_VALUEEXTRACTORDEFINITION, id = "a")
public void noExtractedValueThrowsException() {
  Validation.byDefaultProvider().configure()
      .addValueExtractor( new NoExtractedValueValueExtractor() )
      .buildValidatorFactory()
      .getValidator();
}

代码示例来源:origin: org.hibernate.beanvalidation.tck/beanvalidation-tck-tests

@Test(expectedExceptions = ValidationException.class)
@SpecAssertion(section = Sections.CONSTRAINTDECLARATIONVALIDATIONPROCESS_VALIDATIONROUTINE_TRAVERSABLE, id = "j")
public void testResolverExceptionsGetWrappedInValidationException() {
  ExceptionThrowingTraversableResolver resolver = new ExceptionThrowingTraversableResolver();
  Configuration<?> config = TestUtil.getConfigurationUnderTest().traversableResolver( resolver );
  ValidatorFactory factory = config.buildValidatorFactory();
  Validator v = factory.getValidator();
  v.validate( new Suit() );
}

代码示例来源:origin: hibernate/hibernate-validator

public ValidationExtension() {
  Configuration<?> config = Validation.byDefaultProvider().configure();
  // we use the default ParameterNameProvider here as we cannot use the injected one
  // as it hasn't been turned into a managed bean yet and might not be able to
  // return a parameter name. At this stage, we don't care about the parameter names.
  config.parameterNameProvider( config.getDefaultParameterNameProvider() );
  BootstrapConfiguration bootstrap = config.getBootstrapConfiguration();
  globalExecutableTypes = bootstrap.getDefaultValidatedExecutableTypes();
  isExecutableValidationEnabled = bootstrap.isExecutableValidationEnabled();
  validatorFactory = config.buildValidatorFactory();
  validator = validatorFactory.getValidator();
  getterPropertySelectionStrategyHelper = GetterPropertySelectionStrategyHelper.forValidationFactory( validatorFactory );
  executableHelper = new ExecutableHelper( new TypeResolutionHelper() );
}

代码示例来源:origin: hibernate/hibernate-validator

public StatisticalValidationState() {
  ValidatorFactory factory = null;
  final Configuration<?> configuration = Validation.byDefaultProvider().configure();
  try ( InputStream mappingStream = StatisticalValidation.class.getResourceAsStream( "mapping.xml" ) ) {
    configuration.addMapping( mappingStream );
    factory = configuration.buildValidatorFactory();
    assertThat( factory ).isNotNull();
  }
  catch (IOException e) {
    throw new IllegalStateException( "Mappings cannot be read. Validation factory cannot be configured correctly.", e );
  }
  validator = factory.getValidator();
  entitiesUnderTest = IntStream.rangeClosed( 0, NUMBER_OF_TEST_ENTITIES )
      .mapToObj( index -> new TestEntity( index % 10 ) )
      .collect( Collectors.toList() );
}

代码示例来源:origin: torakiki/sejda

private DefaultValidationContext() {
  Configuration<?> validationConfig = Validation.byDefaultProvider().configure();
  if (new DefaultSejdaContext().isIgnoreXmlConfiguration()) {
    validationConfig.ignoreXmlConfiguration();
  }
  ValidatorFactory factory = validationConfig.buildValidatorFactory();
  validator = factory.getValidator();
}

代码示例来源:origin: hibernate/hibernate-validator

@Override
public ValidatorFactory create(CreationalContext<ValidatorFactory> ctx) {
  Configuration<?> config = getConfiguration();
  config.constraintValidatorFactory( createConstraintValidatorFactory( config ) );
  config.messageInterpolator( createMessageInterpolator( config ) );
  config.traversableResolver( createTraversableResolver( config ) );
  config.parameterNameProvider( createParameterNameProvider( config ) );
  config.clockProvider( createClockProvider( config ) );
  addValueExtractorBeans( config );
  return config.buildValidatorFactory();
}

代码示例来源:origin: org.hibernate.jsr303.tck/jsr303-tck

@SpecAssertion(section = "2.5", id = "c")
@Test(expectedExceptions = ValidationException.class)
public void testValidationExceptionIsThrownInCaseFactoryReturnsNull() {
  Configuration<?> config = TestUtil.getConfigurationUnderTest().constraintValidatorFactory(
      new ConstraintValidatorFactory() {
        public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
          return null;
        }
      }
  );
  Validator validator = config.buildValidatorFactory().getValidator();
  validator.validate( new SecondDummy() );
}

代码示例来源:origin: com.google.gwt/gwt-servlet

/**
 * Build and return a <code>ValidatorFactory</code> instance based on the
 * default Bean Validation provider.
 * <p/>
 * The provider list is resolved using the default validation provider
 * resolver logic.
 * <p/>
 * The code is semantically equivalent to
 * <code>Validation.byDefaultProvider().configure().buildValidatorFactory()</code>
 * 
 * @return <code>ValidatorFactory</code> instance.
 * 
 * @throws ValidationException if the ValidatorFactory cannot be built
 */
public static ValidatorFactory buildDefaultValidatorFactory() {
 return byDefaultProvider().configure().buildValidatorFactory();
}

代码示例来源:origin: apache/cxf

private static void initFactoryConfig(Configuration<?> factoryCfg, ValidationConfiguration cfg) {
  if (cfg != null) {
    factoryCfg.parameterNameProvider(cfg.getParameterNameProvider());
    factoryCfg.messageInterpolator(cfg.getMessageInterpolator());
    factoryCfg.traversableResolver(cfg.getTraversableResolver());
    factoryCfg.constraintValidatorFactory(cfg.getConstraintValidatorFactory());
    for (Map.Entry<String, String> entry : cfg.getProperties().entrySet()) {
      factoryCfg.addProperty(entry.getKey(), entry.getValue());
    }
  }
}

代码示例来源:origin: jersey/jersey

@Override
  public ValidatorFactory get() {
    return config.buildValidatorFactory();
  }
}

代码示例来源:origin: org.hibernate.beanvalidation.tck/beanvalidation-tck-tests

@Test
@SpecAssertion(section = Sections.VALIDATIONAPI_MESSAGE_CUSTOMRESOLUTION, id = "a")
@SpecAssertion(section = Sections.VALIDATIONAPI_MESSAGE_CUSTOMRESOLUTION, id = "b")
@SpecAssertion(section = Sections.VALIDATIONAPI_MESSAGE_CUSTOMRESOLUTION, id = "c")
public void testCorrectValuesArePassedToInterpolateForClassLevelConstraint() {
  TestMessageInterpolator messageInterpolator = new TestMessageInterpolator();
  Validator validator = TestUtil.getConfigurationUnderTest()
      .messageInterpolator( messageInterpolator )
      .buildValidatorFactory()
      .getValidator();
  TestBeanWithClassLevelConstraint testBean = new TestBeanWithClassLevelConstraint();
  validator.validate( testBean );
  assertEquals( messageInterpolator.messageTemplate, TestBeanWithClassLevelConstraint.MESSAGE );
  ConstraintDescriptor<?> constraintDescriptor = messageInterpolator.constraintDescriptor;
  assertEquals( constraintDescriptor.getAnnotation().annotationType(), ValidTestBean.class );
  assertEquals( constraintDescriptor.getMessageTemplate(), TestBeanWithClassLevelConstraint.MESSAGE );
  assertEquals( messageInterpolator.validatedValue, testBean );
}

相关文章