@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");
  }
Exemplo n.º 2
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;
  }
Exemplo n.º 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;
  }
  private Validator configure(String mappingsUrl) {
    Configuration<?> configuration = ValidatorUtil.getConfiguration();
    configuration.traversableResolver(new DummyTraversableResolver());
    configuration.addMapping(InheritanceMappingsTest.class.getResourceAsStream(mappingsUrl));

    ValidatorFactory validatorFactory = configuration.buildValidatorFactory();
    return validatorFactory.getValidator();
  }
Exemplo n.º 5
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();
 }
 private Object getInstanceSafely() {
   final ClassLoader cl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
   try {
     WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(
         factory.getClass().getClassLoader());
     return factory.getValidator();
   } finally {
     WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(cl);
   }
 }
  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());
  }
 @Before
 public void removeOldKeys() {
   ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
   validator = factory.getValidator();
   keyStore
       .getUsers()
       .stream()
       .map(keyStore::getKeys)
       .flatMap(Collection::stream)
       .forEach(unsafe(PersistedKey::delete));
 }
Exemplo n.º 9
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);
  }
Exemplo n.º 10
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);
  }
Exemplo n.º 11
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;
 }
Exemplo n.º 12
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);
  }
Exemplo n.º 13
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);
  }
Exemplo n.º 14
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;
 }
Exemplo n.º 15
0
  protected final int add() {
    Validator validator = FACTORY.getValidator();
    Set<ConstraintViolation<Model>> violations = validator.validate(this);

    if (violations.size() > 0) {
      ValidationUtils.throwException(violations);
    }

    BasicDBObject dbObjectToAdd = toBasicDBObject();

    WriteResult result = MongoDB.getInstance().create(getCollectionName(getClass()), dbObjectToAdd);
    if (!Tools.isBlankOrNull(result.getError())) {
      throw new JCertifException(this.getClass(), result.getError());
    }
    return 1;
  }
Exemplo n.º 16
0
  @RequestMapping(method = RequestMethod.POST)
  public String processSubmit(@ModelAttribute("bean") @Valid Bean bean, BindingResult result) {

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

    logger.info(validator.getClass());

    logger.info(bean.toString());

    logger.info(result.getAllErrors().toString());

    if (result.hasErrors()) {
      return "bean/form";
    }

    return "bean/done";
  }
 public String addQuestionThroughForm() throws IOException {
   if (idTaskAddQuestion < 1) {
     addFieldError("warning", "Select task and then add questions");
     return INPUT;
   }
   SessionFactory sessionFactory = (SessionFactory) servletContext.getAttribute("SessionFactory");
   try {
     task = new TaskDaoImpl(sessionFactory).getTask(idTaskAddQuestion);
   } catch (Exception e) {
     e.printStackTrace();
     return INPUT;
   }
   if (hasFieldErrors()) {
     return ERROR;
   }
   if (fileImage != null) {
     Path imagePath = Paths.get(fileImage.getAbsolutePath());
     InputStream io = Files.newInputStream(imagePath);
     question.setImage(IOUtils.toByteArray(io));
   }
   question.setTask(task);
   ValidatorFactory validatorFactory =
       (ValidatorFactory) servletContext.getAttribute("ValidatorFactory");
   Validator validator = validatorFactory.getValidator();
   Set<ConstraintViolation<Question>> constraintViolations = validator.validate(question);
   if (!constraintViolations.isEmpty()) {
     for (ConstraintViolation item : constraintViolations) {
       addFieldError("warning", "Question validate error. " + item.getMessage());
     }
     return ERROR;
   }
   if (!parseVariants(question)) {
     return ERROR;
   }
   try {
     task = new TaskDaoImpl(sessionFactory).addQuestion(idTaskAddQuestion, question);
     addFieldError("success", "Question was added!");
     question = null;
     return SUCCESS;
   } catch (Exception e) {
     addFieldError("warning", e.getMessage());
     return ERROR;
   }
 }
    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) {
        e.printStackTrace();
      }

      validator = factory.getValidator();

      entitiesUnderTest =
          IntStream.rangeClosed(0, NUMBER_OF_TEST_ENTITIES)
              .mapToObj(index -> new TestEntity(index % 10))
              .collect(Collectors.toList());
    }
Exemplo n.º 19
0
  protected final int update() {
    Validator validator = FACTORY.getValidator();
    Set<ConstraintViolation<Model>> violations = validator.validate(this);

    if (violations.size() > 0) {
      ValidationUtils.throwException(violations);
    }

    BasicDBObject dbObjectToUpdate = toBasicDBObject();
    dbObjectToUpdate.append(Constantes.MONGOD_ID_ATTRIBUTE_NAME, _id);
    int newId = increment(dbObjectToUpdate);

    WriteResult result =
        MongoDB.getInstance().update(getCollectionName(getClass()), dbObjectToUpdate);
    if (!Tools.isBlankOrNull(result.getError())) {
      throw new JCertifException(this.getClass(), result.getError());
    }
    return newId;
  }
  public static void main(String[] args) {

    // Cria o objeto que deseja-se validar
    ModalidadeDisciplina ser = new ModalidadeDisciplina();

    // Faz uma frabrica de validações
    ValidatorFactory fabrica = Validation.buildDefaultValidatorFactory();

    // Cria a validação
    Validator valida = fabrica.getValidator();

    // Pega a coleção de erros elencados
    Set<ConstraintViolation<ModalidadeDisciplina>> constraintViolationsCliente =
        valida.validate(ser);

    for (ConstraintViolation<ModalidadeDisciplina> erro : constraintViolationsCliente) {
      // Imprime os erros
      System.err.println(erro.getMessage());
    }
  }
Exemplo n.º 21
0
  private Validator configureValidation(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
    PrintWriter out = resp.getWriter();

    GenericBootstrap bootstrap = Validation.byDefaultProvider();
    Configuration config = bootstrap.configure();
    InputStream mappingsXml = new ByteArrayInputStream(validationXml.getBytes());
    config.addMapping(mappingsXml);
    ValidatorFactory factory = config.buildValidatorFactory();
    ValidatorContext validatorContext = factory.usingContext();
    Validator validator = validatorContext.getValidator();

    if (null == validator) {
      factory = Validation.byDefaultProvider().configure().buildValidatorFactory();
      validator = factory.getValidator();
    }

    out.print("<p>");
    out.print("Obtained ValidatorFactory: " + factory + ".");
    out.print("</p>");

    return validator;
  }
Exemplo n.º 22
0
  @Test
  public void testBasicRequestBuild() throws Exception {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

    TatraPaySettings settings = new TatraPaySettings();
    settings.setKey("123456789");
    settings.setBaseUrl(BASEURL);
    settings.setMid("08A");
    settings.setRurl("http://hungaropage.hu/");

    TatraPayRequest request = new TatraPayRequest();
    request.setSettings(settings);
    request.setAmt(BigDecimal.valueOf(12.7d));
    request.setVs(235664L);

    PaymentSigner signer = new DESSigner();
    TatraPayRequestBuilder builder = new TatraPayRequestBuilder(factory.getValidator(), signer);
    PaymentRequest paymentRequest = builder.generate(request, null);

    assertEquals("12.70", paymentRequest.getParameters().get(TatraPayParameter.AMT.getName()));
    assertNotNull(
        "Sign not generated?",
        paymentRequest.getParameters().get(TatraPayParameter.SIGN.getName()));
  }
Exemplo n.º 23
0
  private ValidatorFactory() {
    Configuration<?> config = Validation.byDefaultProvider().configure();
    final MessageInterpolator defaultMessageInterpolator = config.getDefaultMessageInterpolator();

    config.messageInterpolator(
        new MessageInterpolator() {
          @Override
          public String interpolate(String messageTemplate, Context context) {
            String message;
            if (context.getConstraintDescriptor().getPayload() != null
                && context.getConstraintDescriptor().getPayload().contains(Localized.class)) {
              // Retrieve message from message library
              message = MessageUtility.getLocalizedMessage(messageTemplate).getMessage();
            } else {
              message = defaultMessageInterpolator.interpolate(messageTemplate, context);
            }
            return message;
          }

          @Override
          public String interpolate(String messageTemplate, Context context, Locale locale) {
            String message;
            if (context.getConstraintDescriptor().getPayload() != null
                && context.getConstraintDescriptor().getPayload().contains(Localized.class)) {
              // Retrieve message from message library
              message = MessageUtility.getLocalizedMessage(messageTemplate, locale).getMessage();
            } else {
              message = defaultMessageInterpolator.interpolate(messageTemplate, context);
            }
            return message;
          }
        });

    // Stop validation if Entity action is DELETE
    config.traversableResolver(
        new TraversableResolver() {

          @Override
          public boolean isReachable(
              Object traversableObject,
              Node traversableProperty,
              Class<?> rootBeanType,
              Path pathToTraversableObject,
              ElementType elementType) {
            if (traversableObject != null
                && AbstractBindingBean.class.isAssignableFrom(traversableObject.getClass())) {
              AbstractBindingBean bean = (AbstractBindingBean) traversableObject;
              if (bean.getEntityAction() != null && bean.getEntityAction() == EntityAction.DELETE) {
                return false;
              }
            }
            return true;
          }

          @Override
          public boolean isCascadable(
              Object traversableObject,
              Node traversableProperty,
              Class<?> rootBeanType,
              Path pathToTraversableObject,
              ElementType elementType) {
            return true;
          }
        });

    javax.validation.ValidatorFactory factory = config.buildValidatorFactory();
    validator = factory.getValidator();
  }
Exemplo n.º 24
0
 {
   ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
   validator = factory.getValidator();
 }
Exemplo n.º 25
0
 @Override
 public Validator getValidator() {
   return delegate.getValidator();
 }
 @BeforeClass
 public static void setUp() {
   ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
   validator = factory.getValidator();
 }
Exemplo n.º 27
0
 @BeforeClass
 public static void init() {
   vf = Validation.buildDefaultValidatorFactory();
   validator = vf.getValidator();
 }
Exemplo n.º 28
0
 @Override
 public ManagedReference getReference() {
   return new ValueManagedReference(new ImmediateValue<Object>(factory.getValidator()));
 }
Exemplo n.º 29
0
/**
 * Cassandra implementation of the user repository.
 *
 * @author Julien Dubois
 */
@Repository
public class CassandraUserRepository implements UserRepository {

  private final Log log = LogFactory.getLog(CassandraUserRepository.class);

  @Inject private EntityManagerImpl em;

  @Inject private Keyspace keyspaceOperator;

  @Inject private CounterRepository counterRepository;

  private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
  private static Validator validator = factory.getValidator();

  @Override
  @CacheEvict(value = "user-cache", key = "#user.login")
  public void createUser(User user) {
    if (log.isDebugEnabled()) {
      log.debug("Creating user : "******"user-cache", key = "#user.login", beforeInvocation = true)
  public void updateUser(User user) throws ConstraintViolationException, IllegalArgumentException {
    if (log.isDebugEnabled()) {
      log.debug("Updating user : "******"user-cache", key = "#user.login")
  public void deleteUser(User user) {
    if (log.isDebugEnabled()) {
      log.debug("Deleting user : "******"user-cache")
  public User findUserByLogin(String login) {
    User user = null;
    try {
      user = em.find(User.class, login);
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.debug("Exception while looking for user " + login + " : " + e.toString());
      }
      return null;
    }
    if (user != null) {
      user.setStatusCount(counterRepository.getStatusCounter(login));
      user.setFollowersCount(counterRepository.getFollowersCounter(login));
      user.setFriendsCount(counterRepository.getFriendsCounter(login));
    }
    return user;
  }
}
 @Before
 public void setUp() throws Exception {
   ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
   validator = factory.getValidator();
 }