@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");
  }
  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;
  }
  @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());
  }
  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);
      }
    }
  }
Beispiel #5
0
  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;
  }
  @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();
  }
  @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;
  }
  @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);
    }
  }
  @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;
  }
  /**
   * 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;
  }
  @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);
  }
 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();
 }
 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();
 }
  @Provides
  protected ValidatorFactory getValidationFactory(
      Provider<MessageInterpolator> interpolatorProvider) {
    HibernateValidatorConfiguration configure =
        Validation.byProvider(HibernateValidator.class).configure();

    configure.messageInterpolator(interpolatorProvider.get());
    return configure.buildValidatorFactory();
  }
    /**
     * 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;
    }
 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();
  }
  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())));
  }
  @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())));
  }
  @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());
  }
  @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()));
  }
 /** @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();
 }
 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();
 }
    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;
    }
    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;
    }
 @Before
 public void removeOldKeys() {
   ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
   validator = factory.getValidator();
   keyStore
       .getUsers()
       .stream()
       .map(keyStore::getKeys)
       .flatMap(Collection::stream)
       .forEach(unsafe(PersistedKey::delete));
 }
  /** @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;
  }
Beispiel #30
0
  @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);
  }