コード例 #1
1
  @Override
  public boolean isValid(Object bean, ConstraintValidatorContext context) {
    try {
      if (bean == null) {
        return true;
      }

      if (violationOnProperty) {
        context.disableDefaultConstraintViolation();
      }

      boolean valid = true;
      Object original = PropertyUtils.getSimpleProperty(bean, properties[0]);

      for (String property : properties) {
        Object copy = PropertyUtils.getSimpleProperty(bean, property);
        if (copy == null) {
          continue;
        }
        if (!copy.equals(original)) {
          valid = false;
          if (violationOnProperty) {
            context
                .buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
                .addPropertyNode(property)
                .addConstraintViolation();
          }
        }
      }
      return valid;

    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
      throw new ValidationException(e);
    }
  }
 private void buildSubCountryViolation(
     final ConstraintValidatorContext context, final String message) {
   context.disableDefaultConstraintViolation();
   context
       .buildConstraintViolationWithTemplate(message)
       .addNode("subCountry")
       .addConstraintViolation();
 }
コード例 #3
0
  @Override
  public boolean isValid(Object value, ConstraintValidatorContext context) {
    try {
      String fieldVal = BeanUtils.getProperty(value, field);
      String verifyFieldVal = BeanUtils.getProperty(value, verifyField);
      if (fieldVal == null && verifyFieldVal == null) {
        return true;
      }

      if (fieldVal != null && !fieldVal.equals(verifyFieldVal)) {
        String messageTemplate = context.getDefaultConstraintMessageTemplate();
        context.disableDefaultConstraintViolation();
        context
            .buildConstraintViolationWithTemplate(messageTemplate)
            .addNode(verifyField)
            .addConstraintViolation();

        return false;
      }

    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    }

    return true;
  }
  @Override
  public boolean isValid(List<RouteArc> value, ConstraintValidatorContext context) {
    List<RouteArc> source =
        value
            .stream()
            .sorted((o1, o2) -> Integer.compare(o1.getNumber(), o2.getNumber()))
            .collect(Collectors.toList());

    PeekingIterator<RouteArc> iterator = Iterators.peekingIterator(source.iterator());
    List<RouteArc> result = new ArrayList<>();
    RouteArc arc;
    while (iterator.hasNext()) {
      arc = iterator.next();
      result.add(arc);
      if (iterator.hasNext()) {
        if (!arc.getEnd().equals(iterator.peek().getStart())) {
          result.add(iterator.next());
          context.disableDefaultConstraintViolation();
          context
              .buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
              .addPropertyNode("\n" + Joiner.on(",\n").join(result))
              .addConstraintViolation();
          return false;
        }
      }
    }
    return true;
  }
コード例 #5
0
 /**
  * Put constraint violation into context.
  *
  * @param context validator context
  */
 private void constraintViolated(ConstraintValidatorContext context) {
   context.disableDefaultConstraintViolation();
   context
       .buildConstraintViolationWithTemplate(failMessage)
       .addNode(secondPropertyName)
       .addConstraintViolation();
 }
 private void buildCountryViolation(final ConstraintValidatorContext context) {
   context.disableDefaultConstraintViolation();
   context
       .buildConstraintViolationWithTemplate(
           "{com.elasticpath.validation.constraints.validCountry}")
       .addNode("country")
       .addConstraintViolation();
 }
コード例 #7
0
  @Override
  public boolean isValid(String value, ConstraintValidatorContext context) {
    if (!InetAddressValidator.getInstance().isValidInet4Address(value)) {
      context.disableDefaultConstraintViolation();
      context
          .buildConstraintViolationWithTemplate(String.format("%s is invalid IPv4 Address", value))
          .addConstraintViolation();
      return false;
    }

    return true;
  }
コード例 #8
0
ファイル: ValidatorHelper.java プロジェクト: wernerb/Platform
  /**
   * Add the stored messages to the context.
   *
   * @param context
   * @return true when no messages are stored (ie failed validations) or false when validation
   *     failures are stored in context.
   */
  protected boolean isValid(final ConstraintValidatorContext context) {
    if (this.messages.isEmpty()) {
      return true;
    }

    context.disableDefaultConstraintViolation();

    for (final String message : this.messages) {
      context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
    }

    return false;
  }
コード例 #9
0
  // isValid = false means need to throw error
  @Override
  public boolean isValid(
      String columnvalue, ConstraintValidatorContext constraintValidatorContext) {

    // To overwrite the custom message instead of default mesasge
    constraintValidatorContext.disableDefaultConstraintViolation();

    if (columnvalue == null) return true;

    boolean isValid = false;

    boolean isExists = false;
    Object[] fld = ac_enum.value().getEnumConstants();
    Class annotationClass = ac_enum.value();

    Method[] methods = annotationClass.getMethods();
    Method getValue = null;
    for (Method m : methods) {
      String name = m.getName();
      if ("getValue".equals(name)) {
        getValue = m;
        break;
      }
    }

    for (Object flds : fld) {
      try {
        String value = (String) getValue.invoke(flds);
        if (!isExists) {
          if (value.equals(columnvalue)) {
            isExists = true;
            break;
          } else isExists = false;
        }
      } catch (IllegalArgumentException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        e.printStackTrace();
      }
    }
    if (!isExists) {
      constraintValidatorContext
          .buildConstraintViolationWithTemplate("Invalid " + ac_enum.columnName() + " Value")
          .addConstraintViolation();
      isValid = false;
    } else isValid = true;

    return isValid;
  }
コード例 #10
0
  @Override
  public boolean isValid(LocationModel value, ConstraintValidatorContext context) {
    Long id = value.getId();
    QLocation location = QLocation.location;
    JPAQuery qquery = new JPAQuery(entityManager);
    qquery.from(location);
    if (id != null) {
      qquery.where((location.id.ne(value.getId())));
    }
    String param = null;
    BooleanExpression exp = null;
    if (value.getIata() != null) {
      exp = location.iata.eq(value.getIata());
      param = "iata";
    }
    if (value.getIcao() != null) {
      if (exp == null) exp = location.icao.eq(value.getIcao());
      else exp = exp.or(location.icao.eq(value.getIcao()));
      param = "icao";
    }
    if (value.getIso() != null) {
      if (exp == null) exp = location.iso.eq(value.getIso());
      else exp = exp.or(location.iso.eq(value.getIso()));
      param = "iso";
    }
    if (value.getITransfer() != null) {
      if (exp == null) exp = location.iTransfer.eq(value.getITransfer());
      else exp = exp.or(location.iTransfer.eq(value.getITransfer()));
      param = "itransfer";
    }
    if (value.getUfs() != null) {
      if (exp == null) exp = location.ufs.eq(value.getUfs());
      else exp = exp.or(location.ufs.eq(value.getUfs()));
      param = "ufs";
    }
    qquery.where(exp);
    List results = qquery.createQuery().getResultList();

    if (results.size() > 0) {
      context
          .buildConstraintViolationWithTemplate("Unique constraint violation")
          .addPropertyNode(param)
          .addConstraintViolation();
      context.disableDefaultConstraintViolation();

      return false;
    }
    return true;
  }
コード例 #11
0
  @Override
  public boolean isValid(User user, ConstraintValidatorContext context) {
    context
        .buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
        .addNode("username")
        .addConstraintViolation();

    if (user.getUsername() == null || user.getUsername().isEmpty()) return true;

    User anotherUser = userService.findByUsername(user.getUsername());

    return anotherUser == null
        || anotherUser.getUsername() == null
        || anotherUser.getId() == user.getId();
  }
コード例 #12
0
 @Override
 public boolean isValid(CharSequence value, ConstraintValidatorContext context) {
   if (value == null) {
     return true;
   }
   try {
     new SimpleDateFormat(value.toString());
   } catch (IllegalArgumentException e) {
     if (DEFAULT_MESSAGE.equals(this.message)) {
       context.disableDefaultConstraintViolation();
       context.buildConstraintViolationWithTemplate(e.getMessage()).addConstraintViolation();
     }
     return false;
   }
   return true;
 }
コード例 #13
0
ファイル: StringMap.java プロジェクト: david-lopez/abiquo
    @Override
    public boolean isValid(
        final Map<String, String> value, final ConstraintValidatorContext context) {
      if (!map.required() && value == null) {
        return true;
      }

      boolean valid = value != null && validKeys(value.keySet()) && validValues(value.values());

      if (!valid) {
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(map.message()).addConstraintViolation();
      }

      return valid;
    }
コード例 #14
0
  @Before
  public void inicializa() {
    initMocks(this);
    when(context.buildConstraintViolationWithTemplate(anyString())).thenReturn(constraintBuilder);

    validador = new PartesAutuacaoValidator();
  }
コード例 #15
0
  @Override
  public boolean isValid(String value, ConstraintValidatorContext context) {
    boolean validationResult = true;

    if (!content.matcher(value).matches()) {
      validationResult = false;
    } else if (!digits.matcher(value).matches()) {
      context.disableDefaultConstraintViolation();
      context
          .buildConstraintViolationWithTemplate("{password.needDigits}")
          .addConstraintViolation();

      validationResult = false;
    }

    return validationResult;
  }
コード例 #16
0
 @Override
 public boolean isValid(Double value, ConstraintValidatorContext context) {
   if (value == null) {
     return true;
   } else if (value < -90) {
     context.disableDefaultConstraintViolation();
     context
         .buildConstraintViolationWithTemplate("latitude.validation.too.low")
         .addConstraintViolation();
     return false;
   } else if (value > +90) {
     context.disableDefaultConstraintViolation();
     context
         .buildConstraintViolationWithTemplate("latitude.validation.too.high")
         .addConstraintViolation();
     return false;
   } else {
     return true;
   }
 }
コード例 #17
0
  @Test
  public void should_return_true_if_individual_fullname_is_null() {

    Tracker.insert(Tracker.VALIDATION_VERSION, VALIDATOR_VERSION);
    when(context.buildConstraintViolationWithTemplate(anyString())).thenReturn(builder);
    when(builder.addPropertyNode(anyString())).thenReturn(node);
    when(node.addConstraintViolation()).thenReturn(null);
    when(validationAdapter.check(any(Field.class))).thenReturn(null);

    Assert.assertTrue(validator.isValid(null, context));
    Mockito.verify(node, Mockito.times(0)).addConstraintViolation();
  }
コード例 #18
0
  @Test
  public void should_return_false_and_add_violation_for_invalid_individual_fullname() {

    Tracker.insert(Tracker.VALIDATION_VERSION, VALIDATOR_VERSION);
    when(context.buildConstraintViolationWithTemplate(anyString())).thenReturn(builder);
    when(builder.addPropertyNode(anyString())).thenReturn(node);
    when(node.addConstraintViolation()).thenReturn(null);
    when(validationAdapter.check(any(Field.class))).thenReturn(new Error());

    Assert.assertFalse(validator.isValid(INVALID_NAME, context));
    Mockito.verify(node, Mockito.times(1)).addConstraintViolation();
  }
  /**
   * Implements the validation logic. The state of {@code value} must not be altered.
   *
   * <p>This method can be accessed concurrently, thread-safety must be ensured by the
   * implementation.
   *
   * @param value object to validate
   * @param context context in which the constraint is evaluated
   * @return {@code false} if {@code value} does not pass the constraint
   */
  @Override
  public boolean isValid(final String value, final ConstraintValidatorContext context) {
    // 0. On ignore les cas bizarres
    if (value == null || value.isEmpty()) {
      return true;
    }

    // 1. Récupération de la DataSource associée à target
    DataSource ds = BeanLocator.lookup(this.targetedDatabase);

    // 2. Obtention d'une connexion
    boolean doesExist = false;

    try (Connection cnx = ds.getConnection();
        PreparedStatement ps =
            cnx.prepareStatement("SELECT GR_CODE FROM SYSADM.GROUPEMENTS WHERE GR_CODE = ?")) {
      // 3. Exécution de la requête
      ps.setString(1, value);
      try (ResultSet rs = ps.executeQuery()) {
        if (rs.next()) {
          doesExist = true;
        } else {
          context.disableDefaultConstraintViolation();
          context
              .buildConstraintViolationWithTemplate(
                  String.format("GR_CODE: %s must be in %s DataBase !", value, targetedDatabase))
              .addConstraintViolation();
        }
      }
    } catch (SQLException ex) {
      // Théoriquement, ce n'est pas une exception système mais l'API de Bean Validation
      // ne propose pas de SQLException dans le contrat donc on n'a pas le choix que d'intercepter
      // cette requête
      // et de la renvoyer comme sous-exception runtime puisque personne n'interceptera cette
      // requête
      throw new ValidationRuleException(ex);
    }

    return doesExist;
  }
コード例 #20
0
 /** {@inheritDoc} */
 @Override
 public boolean isValid(UserProfileDto userProfile, ConstraintValidatorContext context) {
   String changedEmail = userProfile.getEmail();
   if (changedEmail == null) {
     // null emails checks are out of scope, pls use separate annotation for that
     return true;
   }
   String currentUserEmail = getEmailOfUser(userProfile.getUserId());
   if (ObjectUtils.equals(changedEmail, currentUserEmail)) {
     return true; // no changes in an email, that's ok
   } else {
     boolean userWithTheSameChangedEmailExists = userDao.getByEmail(changedEmail) != null;
     if (userWithTheSameChangedEmailExists) {
       context.disableDefaultConstraintViolation();
       context
           .buildConstraintViolationWithTemplate(message)
           .addNode("email")
           .addConstraintViolation();
     }
     return !userWithTheSameChangedEmailExists;
   }
 }
コード例 #21
0
  @Test
  public void changedEmailShouldNotBeValidIfItIsBusy() {
    when(userDao.getByEmail(anyString()))
        .thenReturn(new JCUser("*****@*****.**", "email", "password"));
    EditUserProfileDto editedUserProfile = new EditUserProfileDto();
    editedUserProfile.setEmail("*****@*****.**");
    when(validatorContext.buildConstraintViolationWithTemplate(null)).thenReturn(violationBuilder);
    when(violationBuilder.addNode(anyString())).thenReturn(nodeBuilderDefinedContext);

    boolean isValid = validator.isValid(editedUserProfile, validatorContext);

    assertFalse(isValid, "New email is taken, so it must be invalid.");
  }
コード例 #22
0
 @Override
 public boolean isValid(Map<String, Object> value, ConstraintValidatorContext context) {
   boolean valid = true;
   for (String field : this.fields) {
     if (!value.containsKey(field)) {
       context
           .buildConstraintViolationWithTemplate("Missing field ''" + field + "''")
           .addConstraintViolation();
       valid = false;
     }
   }
   return valid;
 }
コード例 #23
0
 public boolean isValid(final Object value, final ConstraintValidatorContext context) {
   boolean isValid = false;
   BeanWrapper beanWrapper = new BeanWrapperImpl(value);
   final Object field = beanWrapper.getPropertyValue(constraint.field());
   final Object match = beanWrapper.getPropertyValue(constraint.match());
   isValid = field == match || field != null && field.equals(match);
   if (!isValid) {
     context
         .buildConstraintViolationWithTemplate(constraint.message())
         .addNode(constraint.match())
         .addConstraintViolation();
   }
   return isValid;
 }
コード例 #24
0
 @Test
 public void testChangeUserPasswordIncorrect() {
   String incorrectCurrentPassword = "******";
   editUserProfileDto.setCurrentUserPassword(incorrectCurrentPassword);
   Mockito.when(encryptionService.encryptPassword(incorrectCurrentPassword))
       .thenReturn(incorrectCurrentPassword);
   Mockito.when(validatorContext.buildConstraintViolationWithTemplate(null))
       .thenReturn(violationBuilder);
   Mockito.when(violationBuilder.addNode(Mockito.anyString()))
       .thenReturn(nodeBuilderDefinedContext);
   boolean isValid = validator.isValid(editUserProfileDto, validatorContext);
   Assert.assertEquals(isValid, false, "The old password isn't correct, but the check passed.");
   Mockito.verify(validatorContext).buildConstraintViolationWithTemplate(null);
 }
コード例 #25
0
ファイル: User.java プロジェクト: LHN/s3auth
 /**
  * {@inheritDoc}
  *
  * @checkstyle MultipleStringLiterals (50 lines)
  */
 @Override
 public boolean isValid(final User user, final ConstraintValidatorContext ctx) {
   boolean isValid = true;
   final String nid = user.identity().nid();
   if (!"facebook".equals(nid)
       && !"google".equals(nid)
       && !"github".equals(nid)
       && !"test".equals(nid)) {
     ctx.buildConstraintViolationWithTemplate(
             String.format("invalid NID of URN: %s", user.identity()))
         .addPropertyNode("identity")
         .addConstraintViolation();
     isValid = false;
   }
   if (!user.identity().nss().matches("\\d+")) {
     ctx.buildConstraintViolationWithTemplate(
             String.format("invalid NSS of URN: %s", user.identity()))
         .addPropertyNode("identity")
         .addConstraintViolation();
     isValid = false;
   }
   return isValid;
 }
コード例 #26
0
  @Override
  public boolean isValid(PasswordModel passwordModel, ConstraintValidatorContext context) {
    String password = passwordModel.getPassword();
    String passwordRetype = passwordModel.getPasswordRetype();

    if (StringUtils.isBlank(password) || StringUtils.isBlank(passwordRetype)) {
      return false;
    }

    if (!password.equals(passwordRetype)) {
      context
          .buildConstraintViolationWithTemplate("passwordMatchError")
          .addPropertyNode("passwordRetype")
          .addConstraintViolation();
      return false;
    }

    return true;
  }