Пример #1
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;
  }
  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);
      }
    }
  }
Пример #3
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;
  }
Пример #4
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);
  }
  @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);
    }
  }
Пример #6
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;
  }
Пример #7
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;
  }
Пример #8
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;
  }
  @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();
  }
 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;
 }
    /**
     * 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;
    }
  @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 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 isValid() throws Exception {
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    MeterReading meterReading = newMeterReading();

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

    assertThat(violations, is(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())));
  }
 @Before
 public void removeOldKeys() {
   ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
   validator = factory.getValidator();
   keyStore
       .getUsers()
       .stream()
       .map(keyStore::getKeys)
       .flatMap(Collection::stream)
       .forEach(unsafe(PersistedKey::delete));
 }
Пример #17
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();
 }
Пример #18
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;
    }
Пример #19
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;
    }
Пример #20
0
  @Test
  public void ifNameIsNull_nameValidationFails() {
    User user = new User();
    user.setWorking(true);
    user.setAboutMe("Its all about me!!");
    user.setAge(50);

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<User>> violations = validator.validate(user);
    assertEquals(violations.isEmpty(), false);
  }
Пример #21
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);
  }
  /** @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;
  }
Пример #23
0
 static Validator getBeanValidator() {
   if (beanValidator == null) {
     try {
       ValidatorFactory f = Validation.buildDefaultValidatorFactory();
       return f.getValidator();
     } catch (ValidationException e) {
       LOG.info("No JSR-303 bean validation configuration found: " + e.getMessage());
       return null;
     }
   }
   return beanValidator;
 }
Пример #24
0
 public static boolean hasErrors(Object obj, String message) {
   if (message != null) {
     ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
     Validator validator = factory.getValidator();
     Set<ConstraintViolation<Object>> errors = validator.validate(obj);
     for (ConstraintViolation<Object> constraintViolation : errors) {
       if (message.equals(constraintViolation.getMessage())) {
         return true;
       }
     }
   }
   return false;
 }
Пример #25
0
// enum implementation of singleton pattern
// see http://stackoverflow.com/questions/70689/efficient-way-to-implement-singleton-pattern-in-java
public enum Validator {
  instance(Validation.buildDefaultValidatorFactory().getValidator());

  private final javax.validation.Validator validator;

  public javax.validation.Validator get() {
    return validator;
  }

  Validator(javax.validation.Validator validator) {
    this.validator = validator;
  }
}
Пример #26
0
  @Test
  public void ifFnameNullAgeNotRangeAndWorkingIsFalse_validationFailsWithThreeErrors() {
    User user = new User();
    user.setAboutMe("Its all about me!!");
    user.setAge(300);

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<User>> violations = validator.validate(user);
    logViolations(violations);
    assertEquals(violations.isEmpty(), false);
    assertEquals(violations.size(), 3);
  }
Пример #27
0
  @Test
  public void validateFromJson() throws IOException {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    XenonConfiguration actual =
        fromJson(jsonFixture("fixtures/xenon.json"), XenonConfiguration.class);

    Set<ConstraintViolation<XenonConfiguration>> constraintViolations =
        validator.validateProperty(actual, "scheduler");

    assertThat(constraintViolations.size()).isEqualTo(0);
  }
  @Override
  protected void secondPassCompile() throws MappingException {
    super.secondPassCompile();

    try {
      TypeSafeActivatorAccessor.applyRelationalConstraints(
          Validation.buildDefaultValidatorFactory(),
          classes.values(),
          getProperties(),
          ((Class<Dialect>) Class.forName(getProperty(Hbm2DdlMojo.DIALECT))).newInstance());
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Пример #29
0
  @Test
  public void testValidationOfBeanDirectly() {
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    MyBean b = new MyBean("hi", 1, 2);

    Set<ConstraintViolation<MyBean>> violations = validator.validate(b);
    Assert.assertEquals(0, violations.size());

    b = new MyBean("hi", 2, 1);
    violations = validator.validate(b);
    Assert.assertEquals(1, violations.size());
    Assert.assertEquals(
        "script expression \"_this.i < _this.j\" didn't evaluate to true",
        violations.iterator().next().getMessage());
  }
 @Test
 public void doesNotDefaultExceptionMappers() throws Exception {
   http.setRegisterDefaultExceptionMappers(false);
   assertThat(http.getRegisterDefaultExceptionMappers()).isFalse();
   Environment environment =
       new Environment(
           "test",
           Jackson.newObjectMapper(),
           Validation.buildDefaultValidatorFactory().getValidator(),
           new MetricRegistry(),
           ClassLoader.getSystemClassLoader());
   http.build(environment);
   for (Object singleton : environment.jersey().getResourceConfig().getSingletons()) {
     assertThat(singleton).isNotInstanceOf(ExceptionMapper.class);
   }
 }