コード例 #1
1
  @Test
  public void testCustomConstraintValidatorFactory() {

    Configuration<?> configuration = Validation.byDefaultProvider().configure();
    assertDefaultBuilderAndFactory(configuration);

    ValidatorFactory factory = configuration.buildValidatorFactory();
    Validator validator = factory.getValidator();

    Customer customer = new Customer();
    customer.setFirstName("John");

    Set<ConstraintViolation<Customer>> constraintViolations = validator.validate(customer);
    assertEquals(constraintViolations.size(), 1, "Wrong number of constraints");
    ConstraintViolation<Customer> constraintViolation = constraintViolations.iterator().next();
    assertEquals("may not be empty", constraintViolation.getMessage(), "Wrong message");

    // 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 == NotNullValidator.class) {
              return (T) new BadlyBehavedNotNullConstraintValidator();
            }
            return new ConstraintValidatorFactoryImpl().getInstance(key);
          }
        });
    factory = configuration.buildValidatorFactory();
    validator = factory.getValidator();
    constraintViolations = validator.validate(customer);
    assertEquals(constraintViolations.size(), 0, "Wrong number of constraints");
  }
コード例 #2
0
  public static ValidatorFactory buildFactory(
      final ValidationInfo config, final ClassLoader classLoader) {
    ValidatorFactory factory = null;
    final Thread thread = Thread.currentThread();
    final ClassLoader oldContextLoader = thread.getContextClassLoader();
    try {
      thread.setContextClassLoader(classLoader);
      if (config == null) {
        factory = Validation.buildDefaultValidatorFactory();
      } else {
        final Configuration<?> configuration = getConfig(config);
        try {
          factory = configuration.buildValidatorFactory();
        } catch (final ValidationException ve) {
          thread.setContextClassLoader(ValidatorBuilder.class.getClassLoader());
          factory = Validation.buildDefaultValidatorFactory();
          thread.setContextClassLoader(classLoader);

          logger.warning(
              "Unable create validator factory with config "
                  + config
                  + " ("
                  + ve.getMessage()
                  + ")."
                  + " Default factory will be used.");
        }
      }
    } finally {
      thread.setContextClassLoader(oldContextLoader);
    }
    return factory;
  }
コード例 #3
0
  @Override
  @SuppressWarnings("unchecked")
  public void afterPropertiesSet() {
    @SuppressWarnings("rawtypes")
    Configuration configuration =
        (this.providerClass != null
            ? Validation.byProvider(this.providerClass).configure()
            : Validation.byDefaultProvider().configure());

    MessageInterpolator targetInterpolator = this.messageInterpolator;
    if (targetInterpolator == null) {
      targetInterpolator = configuration.getDefaultMessageInterpolator();
    }
    configuration.messageInterpolator(new LocaleContextMessageInterpolator(targetInterpolator));

    if (this.traversableResolver != null) {
      configuration.traversableResolver(this.traversableResolver);
    }

    ConstraintValidatorFactory targetConstraintValidatorFactory = this.constraintValidatorFactory;
    if (targetConstraintValidatorFactory == null && this.applicationContext != null) {
      targetConstraintValidatorFactory =
          new SpringConstraintValidatorFactory(
              this.applicationContext.getAutowireCapableBeanFactory());
    }
    if (targetConstraintValidatorFactory != null) {
      configuration.constraintValidatorFactory(targetConstraintValidatorFactory);
    }

    configureParameterNameProviderIfPossible(configuration);

    if (this.mappingLocations != null) {
      for (Resource location : this.mappingLocations) {
        try {
          configuration.addMapping(location.getInputStream());
        } catch (IOException ex) {
          throw new IllegalStateException("Cannot read mapping resource: " + location);
        }
      }
    }

    for (Map.Entry<String, String> entry : this.validationPropertyMap.entrySet()) {
      configuration.addProperty(entry.getKey(), entry.getValue());
    }

    // Allow for custom post-processing before we actually build the ValidatorFactory.
    postProcessConfiguration(configuration);

    this.validatorFactory = configuration.buildValidatorFactory();
    setTargetValidator(this.validatorFactory.getValidator());
  }
コード例 #4
0
  private ValidatorFactory createValidationFactory() {
    try {
      return Validation.buildDefaultValidatorFactory();
    } catch (final ValidationException e) {
      final ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();

      Thread.currentThread().setContextClassLoader(this.classloader);
      try {
        return Validation.buildDefaultValidatorFactory();
      } finally {
        Thread.currentThread().setContextClassLoader(oldClassLoader);
      }
    }
  }
コード例 #5
0
ファイル: KeywhizTestRunner.java プロジェクト: stripe/keywhiz
  static Injector createInjector() {
    KeywhizService service = new KeywhizService();
    Bootstrap<KeywhizConfig> bootstrap = new Bootstrap<>(service);
    service.initialize(bootstrap);

    File yamlFile = new File(Resources.getResource("keywhiz-test.yaml").getFile());
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    ObjectMapper objectMapper = bootstrap.getObjectMapper().copy();
    KeywhizConfig config;
    try {
      config =
          new ConfigurationFactory<>(KeywhizConfig.class, validator, objectMapper, "dw")
              .build(yamlFile);
    } catch (IOException | ConfigurationException e) {
      throw Throwables.propagate(e);
    }

    Environment environment =
        new Environment(
            service.getName(),
            objectMapper,
            validator,
            bootstrap.getMetricRegistry(),
            bootstrap.getClassLoader());

    Injector injector = Guice.createInjector(new ServiceModule(config, environment));

    service.setInjector(injector);
    return injector;
  }
コード例 #6
0
  @Before
  public void setUp() throws Exception {
    preferredValidatorFactory = Validation.buildDefaultValidatorFactory();

    JAXBContext ctx = JAXBContextFactory.createContext(EMPLOYEE, null);
    marshallerValidOn = (JAXBMarshaller) ctx.createMarshaller();
    marshallerValidOn.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshallerValidOff = (JAXBMarshaller) ctx.createMarshaller();
    /* tests setting the property through marshaller */
    marshallerValidOff.setProperty(
        MarshallerProperties.BEAN_VALIDATION_MODE, BeanValidationMode.NONE);
    marshallerValidOff.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    JAXBContext ctxValidationOff =
        JAXBContextFactory.createContext(
            EMPLOYEE,
            new HashMap<String, Object>() {
              {
                put(JAXBContextProperties.BEAN_VALIDATION_MODE, BeanValidationMode.NONE);
                put(JAXBContextProperties.BEAN_VALIDATION_FACTORY, preferredValidatorFactory);
              }
            });
    unmarshallerValidOn = (JAXBUnmarshaller) ctxValidationOff.createUnmarshaller();
    /* tests setting the property through unmarshaller */
    unmarshallerValidOn.setProperty(
        UnmarshallerProperties.BEAN_VALIDATION_MODE, BeanValidationMode.CALLBACK);
    unmarshallerValidOff = (JAXBUnmarshaller) ctxValidationOff.createUnmarshaller();
  }
コード例 #7
0
  @Override
  public String getTaxNumber(String firmokpo, String docnum, String docdate) {
    TaxNumberParameter params = new TaxNumberParameter(firmokpo, docnum, docdate);

    StringBuilder outputBuffer = new StringBuilder();

    // here we should validate parameters, that have been passed with query
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<TaxNumberParameter>> constraintViolations = validator.validate(params);

    StringBuilder validationBuffer = new StringBuilder();

    validationBuffer.append(
        constraintViolations
            .stream()
            .map(ConstraintViolation::getMessage)
            .collect(Collectors.joining("\n")));

    String validationMessage = validationBuffer.toString();
    if (!validationMessage.isEmpty()) {

      // outputBuffer.append(validationMessage);
      // Throwing Exception with contents.
      throw new IllegalArgumentException("Invalid input parameters: " + validationMessage);
    }

    String taxNumber = taxNumberDAO.getTaxNumber(params);

    return taxNumber;
  }
コード例 #8
0
  @SuppressWarnings("unchecked")
  public void afterPropertiesSet() throws Exception {

    Assert.state(yaml != null, "Yaml document should not be null");

    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    try {
      logger.trace("Yaml document is\n" + yaml);
      configuration = (T) (new Yaml(constructor)).load(yaml);
      Set<ConstraintViolation<T>> errors = validator.validate(configuration);

      if (!errors.isEmpty()) {
        logger.error("YAML configuration failed validation");
        for (ConstraintViolation<?> error : errors) {
          logger.error(error.getPropertyPath() + ": " + error.getMessage());
        }
        if (exceptionIfInvalid) {
          @SuppressWarnings("rawtypes")
          ConstraintViolationException summary = new ConstraintViolationException((Set) errors);
          throw summary;
        }
      }
    } catch (YAMLException e) {
      if (exceptionIfInvalid) {
        throw e;
      }
      logger.error("Failed to load YAML validation bean. Your YAML file may be invalid.", e);
    }
  }
コード例 #9
0
  @POST
  @Path("pay")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public ResponseBean payment(ExamBean2 bean) {

    ResponseBean<ExamBean2> res = new ResponseBean();

    // We can't @Inject Validator on Glassfish 4.0, 4.0.1 may be fix it.
    final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Set<ConstraintViolation<ExamBean2>> violations =
        validator.validate(bean, bean.validateGroups());
    System.out.println(violations.toString());
    if (!violations.isEmpty()) {
      // There are some validation errors
      res.setSuccess(false);
      res.setValidationError(violations);
      return res;
    }

    res.setSuccess(true);
    return res;
  }
コード例 #10
0
  /**
   * Returns the underlying JSR-303 bean validator factory used. A factory is created using {@link
   * Validation} if necessary.
   *
   * @return {@link ValidatorFactory} to use
   */
  protected static ValidatorFactory getJavaxBeanValidatorFactory() {
    if (factory == null) {
      factory = Validation.buildDefaultValidatorFactory();
    }

    return factory;
  }
コード例 #11
0
  @RequestMapping(value = "/add", method = RequestMethod.POST)
  public ResponseEntity<?> addBook(
      Principal principal,
      @RequestParam("title") String title,
      @RequestParam("intro") String intro,
      @RequestParam("categories") String[] categories,
      @RequestParam("file") MultipartFile file) {

    BookDTO bookDTO = new BookDTO(title, intro, file, categories);

    Set<ConstraintViolation<BookDTO>> violations =
        Validation.buildDefaultValidatorFactory().getValidator().validate(bookDTO);

    if (violations.size() > 0 || !file.getContentType().equals("application/pdf"))
      return new ResponseEntity<>(HttpStatus.BAD_REQUEST);

    Book book = new Book();
    book.setTitle(title);
    book.setIntroduction(intro);
    book.setCategories(categories);
    try {
      book.setContent(file.getBytes());
    } catch (IOException e) {
      return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    book.setPublished_date(new Date());
    book.setTotal_pages(100);

    book.setUser(userRepo.findOneByEmail(principal.getName()));

    if (bookRepo.addBook(book) && bookRepo.addBookHasCategory(book))
      return new ResponseEntity<>(HttpStatus.ACCEPTED);
    else return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
  }
コード例 #12
0
 private <T> Map<String, ConstraintViolation<T>> validate(T user) {
   Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
   Map<String, ConstraintViolation<T>> violations = new HashMap<String, ConstraintViolation<T>>();
   for (ConstraintViolation<T> violation : validator.validate(user)) {
     violations.put(violation.getPropertyPath().toString(), violation);
   }
   return violations;
 }
 /** Creates and reuses injecting JSR 303 Validator factory. */
 @Provides
 @Singleton
 public ValidatorFactory getValidatorFactory(Injector injector) {
   return Validation.byDefaultProvider()
       .configure()
       .constraintValidatorFactory(new InjectingConstraintValidationFactory(injector))
       .buildValidatorFactory();
 }
コード例 #14
0
 public static void main(String[] args) {
   Configuration configuration = Validation.byProvider(HibernateValidator.class).configure();
   ValidatorFactory factory = configuration.buildValidatorFactory();
   Validator validator = factory.getValidator();
   validator.validate(Object.class);
   // programmation constraint mappings
   ConstraintMapping mapping = new ConstraintMapping();
 }
コード例 #15
0
  @Provides
  protected ValidatorFactory getValidationFactory(
      Provider<MessageInterpolator> interpolatorProvider) {
    HibernateValidatorConfiguration configure =
        Validation.byProvider(HibernateValidator.class).configure();

    configure.messageInterpolator(interpolatorProvider.get());
    return configure.buildValidatorFactory();
  }
コード例 #16
0
    /**
     * INTERNAL:
     *
     * @param puProperties merged properties for this persitence unit
     * @return ValidatorFactory instance to be used for this persistence unit.
     */
    private ValidatorFactory getValidatorFactory(Map puProperties) {
      ValidatorFactory validatorFactory =
          (ValidatorFactory) puProperties.get(PersistenceUnitProperties.VALIDATOR_FACTORY);

      if (validatorFactory == null) {
        validatorFactory = Validation.buildDefaultValidatorFactory();
      }
      return validatorFactory;
    }
コード例 #17
0
 static {
   HibernateValidatorConfiguration configuration =
       Validation.byProvider(HibernateValidator.class).configure().failFast(true);
   FACTORY =
       configuration
           .messageInterpolator(
               new ContextualMessageInterpolator(configuration.getDefaultMessageInterpolator()))
           .buildValidatorFactory();
 }
  public static ValidatorFactory createValidatorFactory(ValidatorProvider provider) {
    Configuration<?> config = Validation.byDefaultProvider().configure();

    config.constraintValidatorFactory(
        new CustomConstraintValidatorFactory(
            config.getDefaultConstraintValidatorFactory(), provider));

    return config.buildValidatorFactory();
  }
コード例 #19
0
  public ValidationExtension() {
    Configuration<?> config = Validation.byDefaultProvider().configure();
    BootstrapConfiguration bootstrap = config.getBootstrapConfiguration();
    globalExecutableTypes = bootstrap.getDefaultValidatedExecutableTypes();
    isExecutableValidationEnabled = bootstrap.isExecutableValidationEnabled();
    validatorFactory = config.buildValidatorFactory();
    validator = validatorFactory.getValidator();

    executableHelper = new ExecutableHelper(new TypeResolutionHelper());
  }
  @Test
  public void isInvalid() throws Exception {
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    ServiceCategory serviceCategory = new ServiceCategory();

    Set<ConstraintViolation<ServiceCategory>> violations = validator.validate(serviceCategory);

    assertThat(violations, is(not(empty())));
  }
コード例 #21
0
  @Test
  public void isInvalid() throws Exception {
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    Authorization authorization = new Authorization();

    Set<ConstraintViolation<Authorization>> violations = validator.validate(authorization);

    assertThat(violations, is(not(empty())));
  }
コード例 #22
0
  @Test
  public void isInvalid() throws Exception {
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    Subscription subscription = new Subscription();

    Set<ConstraintViolation<Subscription>> violations = validator.validate(subscription);

    assertFalse(violations.isEmpty());
  }
コード例 #23
0
  @Test
  public void isValid() throws Exception {
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    MeterReading meterReading = newMeterReading();

    Set<ConstraintViolation<MeterReading>> violations = validator.validate(meterReading);

    assertThat(violations, is(empty()));
  }
コード例 #24
0
 /** @param theMessageInterpolator */
 public GPI18NValidator(IGPI18NMessageInterpolator theMessageInterpolator) {
   Preconditions.checkArgument(
       theMessageInterpolator != null, "The Parameter MessageInterpoletor must " + "not be null.");
   this.messageInterpolator = theMessageInterpolator;
   Configuration<?> configuration = Validation.byDefaultProvider().configure();
   this.validator =
       configuration
           .messageInterpolator(this.messageInterpolator)
           .buildValidatorFactory()
           .getValidator();
 }
コード例 #25
0
 private T parseConfiguration(
     ConfigurationSourceProvider provider, String path, Class<T> klass, ObjectMapper objectMapper)
     throws IOException, ConfigurationException {
   final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
   final ConfigurationFactory<T> configurationFactory =
       new ConfigurationFactory<>(klass, validator, objectMapper, "dw");
   if (path != null) {
     return configurationFactory.build(provider, path);
   }
   return configurationFactory.build();
 }
コード例 #26
0
    public Binding<M, T> to(Property<T> targetProperty) {

      Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

      Binding<M, T> binding =
          new Binding<M, T>(
              modelProperty, targetProperty, targetUpdatePolicy, converter, validator, labelText);
      bindingContext.addBinding(binding);

      return binding;
    }
コード例 #27
0
    public <T> Binding<M, T> to(ReadOnlyProperty<T> targetProperty) {

      Converter<M, T> converter = ConverterFactory.getConverter(modelProperty, targetProperty);
      Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

      Binding<M, T> binding =
          new Binding<M, T>(modelProperty, targetProperty, modelUpdatePolicy, converter, validator);
      bindingContext.addBinding(binding);

      return binding;
    }
コード例 #28
0
 @Before
 public void removeOldKeys() {
   ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
   validator = factory.getValidator();
   keyStore
       .getUsers()
       .stream()
       .map(keyStore::getKeys)
       .flatMap(Collection::stream)
       .forEach(unsafe(PersistedKey::delete));
 }
コード例 #29
0
  /** @return the factory to use to get new JSR 303 validators. */
  public ValidatorFactory getValidatorFactory() {
    if (this.validatorFactory == null) {
      try {
        this.validatorFactory = Validation.buildDefaultValidatorFactory();
      } catch (ValidationException e) {
        this.logger.warn(
            "Unable to find default JSR 303 provider. There will be no Java bean validation.");
      }
    }

    return this.validatorFactory;
  }
コード例 #30
0
ファイル: UserTest.java プロジェクト: claudioaltamura/javaee
  @Test
  public void ifAgeNotRange_ageValidationFails() {
    User user = new User();
    user.setName("MyName");
    user.setAboutMe("Its all about me!!");
    user.setAge(8);

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<User>> violations = validator.validate(user);
    assertEquals(violations.isEmpty(), false);
  }