Java 类javax.validation.ConstraintValidatorContext 实例源码

项目:cmc-claim-store    文件:InterDependentFieldsConstraintValidator.java   
private boolean validateInterestDate(Object validateThis,
                                     ConstraintValidatorContext ctx,
                                     Field fieldObj,
                                     Field dependentFieldObj) throws IllegalAccessException {
    InterestDate interestDate = (InterestDate) fieldObj.get(validateThis);
    Interest interest = (Interest) dependentFieldObj.get(validateThis);
    if (interest != null && !interestTypeIsNoInterest(interest.getType())) {
        Set<ConstraintViolation<Object>> violations = validator.validate(interestDate);
        if (!violations.isEmpty()) {
            ctx.disableDefaultConstraintViolation();
            ctx.buildConstraintViolationWithTemplate(getViolationMessages(violations, ctx))
                .addPropertyNode(field)
                .addConstraintViolation();

            return false;
        }
    }
    return true;
}
项目:cmc-claim-store    文件:InterDependentFieldsConstraintValidator.java   
private boolean validateRate(Object validateThis,
                             ConstraintValidatorContext ctx,
                             Field fieldObj,
                             Field dependentFieldObj) throws IllegalAccessException {
    BigDecimal rate = (BigDecimal) fieldObj.get(validateThis);
    Interest.InterestType type = (Interest.InterestType) dependentFieldObj.get(validateThis);
    if ((type == null || !interestTypeIsNoInterest(type)) && rate == null) {
        ctx.disableDefaultConstraintViolation();
        ctx.buildConstraintViolationWithTemplate("may not be null")
            .addPropertyNode(field)
            .addConstraintViolation();

        return false;

    }
    return true;
}
项目:users-service    文件:PasswordConstraintValidator.java   
@Override
public boolean isValid(final String password, final ConstraintValidatorContext context) {
    final PasswordValidator validator = new PasswordValidator(singletonList(
        new LengthRule(8, 30)
        // More rules can be added to increase security
    ));

    final RuleResult result = validator.validate(new PasswordData(password));
    if (result.isValid()) {
        return true;
    }

    context.disableDefaultConstraintViolation();
    context.buildConstraintViolationWithTemplate(
        validator.getMessages(result).stream().collect(joining("\n"))
    ).addConstraintViolation();

    return false;
}
项目:c4sg-services    文件:ListEntryValidator.java   
@Override
public boolean isValid(List<String> values, ConstraintValidatorContext context) {

    if(values == null || values.isEmpty()) {
        return true;
    }

    for (String val : values) {
        boolean valid = false;
        for(String cat: categories) {
            if(cat.equals(val)) {
                valid = true;
            }
        }

        if(!valid) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
            return false;
        }
    }
    return true;
}
项目:cmc-claim-store    文件:ValidCountyCourtJudgmentValidator.java   
@Override
public boolean isValid(CountyCourtJudgment ccj, ConstraintValidatorContext context) {
    if (ccj == null) {
        return true;
    }

    PaymentOption type = ccj.getPaymentOption();
    boolean payByDateIsPopulated = ccj.getPayBySetDate().isPresent();
    boolean repaymentPlanIsPopulated = ccj.getRepaymentPlan().isPresent();

    boolean isValidImmediately = type.equals(IMMEDIATELY) && !payByDateIsPopulated && !repaymentPlanIsPopulated;
    boolean isValidFull = type.equals(FULL_BY_SPECIFIED_DATE) && payByDateIsPopulated && !repaymentPlanIsPopulated;
    boolean isValidByInstalments = type.equals(INSTALMENTS) && !payByDateIsPopulated && repaymentPlanIsPopulated;

    return isValidImmediately || isValidFull || isValidByInstalments;
}
项目:java-validator-safeguard    文件:VerifyValidator.java   
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    if(value == null) {
        return false;
    }

    check = new SafeguardCheck();
    parametros.forEach((parametro) -> check.elementOf(value, parametro).validate());

    if(check.hasError()) {
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate("(" + value + ") contém caracteres inválidos ")
        .addConstraintViolation(); 
    }

    return !check.hasError();
}
项目:Re-Collector    文件:IsOneOfValidator.java   
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    if (value == null) {
        return true;
    }
    final boolean valid = Arrays.asList(strings).contains(value);

    if (!valid) {
        HibernateConstraintValidatorContext hibernateContext = context.unwrap(HibernateConstraintValidatorContext.class);
        hibernateContext.disableDefaultConstraintViolation();

        hibernateContext.addExpressionVariable("validValues", Joiner.on(" ").join(strings))
                .buildConstraintViolationWithTemplate(hibernateContext.getDefaultConstraintMessageTemplate())
                .addConstraintViolation();
    }

    return valid;
}
项目:os    文件:PasswordValidator.java   
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    // 不能9位以下纯数字
    if (value.matches("^\\d{1,9}")) {
        return false;
    }
    // 不能相同字符组成
    if (value.matches("^(.)\\1+$")) {
        return false;
    }
    // 不能由连续字符组成
    if (consectiveStr(value)) {
        return false;
    }
    return true;
}
项目:java-bean-validation-extension    文件:InstanceOfValidator.java   
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {

    if (null == value) {
        return false;
    }

    Class<?>[] classes = annotation.value();

    for(Class<?> cls : classes) {
        if (cls.isInstance(value)) {
            return true;
        }
    }

    return false;
}
项目:java-bean-validation-extension    文件:CCValidator.java   
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {

    if (null == value) {
        return false;
    }

    CreditCardType[] types = annotation.value();

    for(CreditCardType creditCardType : types) {
        CreditCardValidator ccv =
                new CreditCardValidator(creditCardType.getInternalValue());
        if (ccv.isValid(value)) {
            return true;
        }
    }

    return false;
}
项目:java-bean-validation-extension    文件:ParseableValidator.java   
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {

    if (null == value) {
        return false;
    }

    ParseableType type = annotation.value();

    switch (type) {
        case TO_INT:
            return catcher(value, Integer::parseInt);
        case TO_DOUBLE:
            return catcher(value, Double::parseDouble);
        case TO_LONG:
            return catcher(value, Long::parseLong);
        case TO_SHORT:
            return catcher(value, Short::parseShort);
        case TO_FLOAT:
            return catcher(value, Float::parseFloat);
    }

    return false;
}
项目:jwala    文件:PathValidator.java   
@Override
public boolean isValid(final String value, final ConstraintValidatorContext context) {
    try {
        if (StringUtils.isEmpty(value)) {
            return true; // do not validate empty value there are other constraints for that e.g. @NotNull, @Size etc...
        }

        final Path path = Paths.get(value);

        if (checkIfExists && !path.toFile().exists()) {
            return false;
        }

        final String fileExt = FilenameUtils.getExtension(value);
        return allowableFileExtensions.isEmpty() ||
               !allowableFileExtensions.stream().filter(fileExt::equalsIgnoreCase).findFirst().orElse(StringUtils.EMPTY).isEmpty();

    } catch (final InvalidPathException e) {
        LOGGER.error(e.getMessage(), e);
        return false;
    }
}
项目:Smart-Shopping    文件:FieldsVerificationValidator.java   
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
    Object fieldValue = new BeanWrapperImpl(value).getPropertyValue(field);
    Object fieldMatchValue = new BeanWrapperImpl(value).getPropertyValue(fieldMatch);
    boolean result = false;

    if(fieldValue != null)
    {
        //Passwords are kept as char arrays, other values mostly as Strings
        if(fieldValue instanceof char[])
            result =  Arrays.equals((char[])fieldValue, (char[])fieldMatchValue);
        else result = fieldValue.equals(fieldMatchValue);
    } else
        result = fieldMatchValue == null;
    return result;
}
项目:spring-jdbc-orm    文件:MultipartFilesUploadValidate.java   
@Override
public boolean isValid(MultipartFile[] multipartFiles, ConstraintValidatorContext constraintValidatorContext) {
    long _totalSize = 0L;
    if (multipartFiles == null || multipartFiles.length <= 0) {
        return allowEmpty;
    }
    boolean result = false;
    for (MultipartFile multipartFile : multipartFiles) {
        result = (allowSize(multipartFile) && allowContentType(multipartFile));
        if (!result) {
            return false;
        }
        _totalSize += multipartFile.getSize();
    }
    /*
      totalSize = 0 ,则不限制
      如果超出大小,则限制
     */
    return totalSize == 0 || _totalSize < totalSize;
}
项目:beanvalidation    文件:CompareToValidator.java   
public boolean isValid(Object value, ConstraintValidatorContext context) {
    boolean returnValue = false;
    try {
        Comparable first = (Comparable) getNestedProperty(value, property);
        Object second = getNestedProperty(value, otherProperty);
        if (first == null) {
            returnValue = true;
        } else if (second != null) {
            returnValue = doComparison(first, second, comparison);
        }
        // Wenn first != null und second == null: Prüfung würde NPE bewirken, einfach false zurückgeben.
    } catch (Exception e) {
        throw new ValidationException("Cannot read property " + property + " and comparison property " + otherProperty);
    }
    if (!returnValue) {
        createViolationMessageForNestedProperty(property, messageTemplate, context);
    }
    return returnValue;
}
项目:beanvalidation    文件:ValidatorUtil.java   
static void createViolationMessageForNestedProperty(final String nestedProperty, final String messageTemplate, final
ConstraintValidatorContext context) {
    context.disableDefaultConstraintViolation();

    String[] splitted = nestedProperty.split("\\.");
    ConstraintValidatorContext.ConstraintViolationBuilder builder = context.buildConstraintViolationWithTemplate(messageTemplate);
    ConstraintValidatorContext.ConstraintViolationBuilder.NodeBuilderDefinedContext nodeDefinedContext = null;
    ConstraintValidatorContext.ConstraintViolationBuilder.NodeBuilderCustomizableContext nodeCustomizableContext = null;
    for (String s : splitted) {
        if (nodeDefinedContext == null) {
            nodeDefinedContext = builder.addNode(s);
        } else if (nodeCustomizableContext == null) {
            nodeCustomizableContext = nodeDefinedContext.addNode(s);
        } else {
            nodeCustomizableContext = nodeCustomizableContext.addNode(s);
        }
    }
    if (nodeDefinedContext == null) {
        builder.addConstraintViolation();
    } else if (nodeCustomizableContext == null) {
        nodeDefinedContext.addConstraintViolation();
    } else {
        nodeCustomizableContext.addConstraintViolation();
    }
}
项目:abhot    文件:ValidMapValidator.java   
@Override
public boolean isValid(Map<String, String> map, ConstraintValidatorContext context)
{
    for (String key : map.keySet())
    {
        if (key == null || key.isEmpty())
        {
            context.disableDefaultConstraintViolation(); // disable violation message
            context.buildConstraintViolationWithTemplate("key value cannot be null or empty").addConstraintViolation();  // add message
            return false;
        }
        if (map.get(key) == null || map.get(key).isEmpty())
        {
            context.disableDefaultConstraintViolation(); // disable violation message
            context.buildConstraintViolationWithTemplate("value cannot be null or empty for key: " + key).addConstraintViolation();  // add message
            return false;
        }
    }

    return true;
}
项目:validators    文件:DateTimeValidator.java   
@Override
public boolean isValid(CharSequence sequence, ConstraintValidatorContext context) {
    if (sequence == null || sequence.length() == 0) {
        return true;
    }

    final String value = sequence.toString();

    for (String pattern : annotation.patterns()) {
        final DateFormat format = new SimpleDateFormat(pattern);
        format.setLenient(annotation.lenient());

        try {
            format.parse(value);
            return true;
        } catch (@SuppressWarnings("unused") ParseException e) {
            continue;
        }

    }
    return false;
}
项目:Java-9-Programming-Blueprints    文件:ValidRuleValidator.java   
private boolean validateRule(Object value, ConstraintValidatorContext ctx) {
    if (!(value instanceof Rule)) {
        addViolation(ctx, "Constraint valid only on instances of Rule.");
        return false;
    }
    boolean valid = true;
    Rule rule = (Rule) value;

    if (rule.getType() == RuleType.MOVE) {
        valid &= validateNotBlank(ctx, rule.getDestFolder(), "A destination folder must be specified.");
    }
    if (!isBlank(rule.getMatchingText())) {
        valid &= validateFields(ctx, rule);
    } else if (rule.getOlderThan() != null) {
        if (rule.getOlderThan() <= 0) {
            addViolation(ctx, "The age must be greater than 0.");
            valid = false;
        }
    } else if (rule.getOlderThan() == null) {
        addViolation(ctx, "Either matchingText or olderThan must be specified.");
        valid = false;
    }

    return valid;
}
项目:xm-ms-entity    文件:TypeKeyValidator.java   
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
    try {
        String typeKey = (String) FieldUtils.readField(value, typeKeyField, true);
        if (value instanceof XmEntity) {
            return xmEntitySpecService.getAllKeys().containsKey(typeKey);
        } else {
            XmEntity entity = (XmEntity) FieldUtils.readField(value, entityField, true);
            if (entity == null) {
                return true;
            }
            String entityTypeKey = entity.getTypeKey();
            Map<String, Set<String>> keysByEntityType = xmEntitySpecService.getAllKeys().get(entityTypeKey);
            return !(keysByEntityType == null || keysByEntityType.get(getClassName(value)) == null)
                            && keysByEntityType.get(getClassName(value)).contains(typeKey);
        }
    } catch (IllegalAccessException e) {
        log.debug("Could not get keys for validation", e);
        return false;
    }
}
项目:Java-9-Programming-Blueprints    文件:ValidRuleValidator.java   
@Override
public boolean isValid(Object value, ConstraintValidatorContext ctx) {
    if (value == null) {
        addViolation(ctx, "Null values are not considered valid Rules");
        return false;
    }
    boolean valid = true;
    if (value instanceof Collection) {
        for (Object o : ((Collection) value)) {
            valid &= validateRule(o, ctx);
        }
    } else {
        valid = validateRule(value, ctx);
    }
    return valid;
}
项目:gamesboard    文件:PasswordsNotEqualValidator.java   
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
    context.disableDefaultConstraintViolation();
    try {
        String password = (String) ValidatorUtil.getFieldValue(value, passwordFieldName);
        String passwordVerification = (String) ValidatorUtil.getFieldValue(value, passwordVerificationFieldName);

        if (passwordsAreNotEqual(password, passwordVerification)) {
            ValidatorUtil.addValidationError(passwordFieldName, context);
            ValidatorUtil.addValidationError(passwordVerificationFieldName, context);

            return false;
        }
    }
    catch (Exception ex) {
        throw new RuntimeException("Exception occurred during validation", ex);
    }

    return true;
}
项目:users-service    文件:ConfirmationValidator.java   
@Override
public boolean isValid(final String confirmCode,
                       final ConstraintValidatorContext context) {

    return confirmCode != null
        && confirmCode.length() == 40;
}
项目:mafia    文件:EnumValidatorImpl.java   
@Override
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
    if(StringUtils.isEmpty(s))
    {
        return true;
    }
    else if(!valueList.contains(s))
    {
        return false;
    }
    return true;
}
项目:spring-jdbc-orm    文件:StringEnumValidate.java   
@Override
public boolean isValid(String string, ConstraintValidatorContext constraintValidatorContext) {
    if (type == null || type.length == 0 || (string == null && allowNull)) {
        return true;
    }

    return  Arrays.binarySearch(type, string) >= 0;
}
项目:EventSoft    文件:TelefonoValidator.java   
@Override
public boolean isValid(String phoneNo, ConstraintValidatorContext ctx) {
    if(phoneNo == null){
        return false;
    }
    //validate phone numbers of format "123456789"
       if (phoneNo.matches("\\d{9}")) return true;
       //return false if nothing matches the input
       else return false;
}
项目:cmc-claim-store    文件:InterDependentFieldsConstraintValidator.java   
private String getViolationMessages(Set<ConstraintViolation<Object>> violations,
                                    ConstraintValidatorContext ctx) {
    return violations.stream()
        .map(v -> v.getPropertyPath() + " : " + v.getMessage())
        .sorted(String::compareTo)
        .reduce((v1, v2) -> v1 + ", " + v2)
        .orElse(ctx.getDefaultConstraintMessageTemplate());
}
项目:cmc-claim-store    文件:DateNotInTheFutureConstraintValidator.java   
@Override
public boolean isValid(LocalDate localDate, ConstraintValidatorContext cxt) {
    // Another validator should check for this if required
    if (localDate == null) {
        return true;
    }

    return !localDate.isAfter(LocalDate.now());
}
项目:gitplex-mit    文件:GitConfig.java   
@Override
public boolean isValid(ConstraintValidatorContext context) {
    if (getExecutable() != null) {
        String error = GitCommand.checkError(getExecutable());
        if (error != null) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(error).addConstraintViolation();
            return false;
        } else {
            return true;
        }
    } else {
        return true;
    }
}
项目:cmc-claim-store    文件:AgeRangeConstraintValidator.java   
@Override
public boolean isValid(LocalDate localDate, ConstraintValidatorContext cxt) {
    // Another validator should check for this if required
    if (localDate == null) {
        return true;
    }

    long years = getAge(localDate);

    return years >= minYears && years <= maxYears;
}
项目:cmc-claim-store    文件:DateNotInThePastConstraintValidator.java   
@Override
public boolean isValid(LocalDate localDate, ConstraintValidatorContext cxt) {
    // Another validator should check for this if required
    if (localDate == null) {
        return true;
    }

    return !localDate.isBefore(LocalDate.now());
}
项目:infobip-bean-validation    文件:SimpleConstraintValidator.java   
@Override
default boolean isValid(T value, ConstraintValidatorContext context) {

    if (value == null) {
        return true;
    }

    return isValid(value);
}
项目:redirector    文件:ApplicationNameValidator.java   
@Override
public boolean isValid(String pathParam, ConstraintValidatorContext constraintValidatorContext) {
    if (StringUtils.isNotBlank(pathParam)) {
        if (appsService.isApplicationExists(pathParam)) {
            return true;
        }
    }
    log.warn("Couldn't find application: [" + pathParam + "]");
    return false;
}
项目:java-bean-validation-extension    文件:OneOfValidator.java   
public boolean isValid(VType value, VType[] possibleValues, BiFunction<VType, VType, Boolean> equalsMethod, ConstraintValidatorContext context) {
    for (VType possibleVal : possibleValues) {
        if (equalsMethod.apply(value, possibleVal)) {
            return true;
        }
    }
    return false;
}
项目:java-bean-validation-extension    文件:IPv4Validator.java   
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    if (value == null) {
        return false;
    }
    return InetAddressValidator
            .getInstance()
            .isValidInet4Address(value);
}
项目:springbootWeb    文件:ValidateRegexpValidator.java   
@Override
public boolean isValid(final Object value, ConstraintValidatorContext context) {
    if (value == null || "".equals(value)) {
        return true;
    } else if (!StringUtil.isEmpty(validateRegexp.regexp())) {
        Pattern pattern = Pattern.compile(validateRegexp.regexp());
        Matcher matcher = pattern.matcher(value.toString().replaceAll("/", ""));
        return matcher.matches();
    }
    return false;
}
项目:java-bean-validation-extension    文件:IPv6Validator.java   
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    if (value == null) {
        return false;
    }
    return InetAddressValidator
            .getInstance()
            .isValidInet6Address(value);
}
项目:java-bean-validation-extension    文件:IsDateValidator.java   
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {

    if (isEmpty(value)) {
        return false;
    }

    SimpleDateFormat sdf = new SimpleDateFormat(annotation.value());
    try {
        sdf.parse(value);
        return true;
    } catch (ParseException e) {
        return false;
    }
}
项目:d2g-api    文件:EnumValueValidate.java   
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    Object[] enumValues = this.annotation.enumClass().getEnumConstants();

    if (enumValues != null){
        for (Object enumValue:enumValues){
            if (value.equals(enumValue.toString())){
                return true;
            }
        }
    }

    return false;
}
项目:Smart-Shopping    文件:EmailVerificationValidator.java   
@Override
public boolean isValid(String email, ConstraintValidatorContext context) {
    EmailValidator emailValidator = EmailValidator.getInstance();
    if((email == null) || (!emailValidator.isValid(email)))
        return false;
    return true;
}