javax.validation.ConstraintValidatorContext Java Examples

The following examples show how to use javax.validation.ConstraintValidatorContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UrlValidator.java    From nexus-public with Eclipse Public License 1.0 7 votes vote down vote up
@Override
public boolean isValid(final URI uri, final ConstraintValidatorContext constraintValidatorContext) {
  if (uri == null) {
    return true;
  }

  try {
    @SuppressWarnings("unused")
    URL ignored = uri.toURL(); // NOSONAR

    return isValidScheme(uri.getScheme())
        && isValidUserInfo(uri.getUserInfo())
        && isValidHost(uri.getHost())
        && isValidPort(uri.getPort())
        && isValidPath(uri.getPath())
        && isValidFragment(uri.getFragment());
  }
  catch (MalformedURLException | IllegalArgumentException e) {// NOSONAR
    log.debug("Failed to parse URL from {} with message {}", uri, e.getMessage());
  }

  return false;
}
 
Example #2
Source File: HostKeyAndAlgoBothExistValidator.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isValid(MultipleJGitEnvironmentProperties sshUriProperties,
		ConstraintValidatorContext context) {
	Set<Boolean> validationResults = new HashSet<>();
	List<JGitEnvironmentProperties> extractedProperties = this.sshPropertyValidator
			.extractRepoProperties(sshUriProperties);

	for (JGitEnvironmentProperties extractedProperty : extractedProperties) {
		if (sshUriProperties.isIgnoreLocalSshSettings()
				&& isSshUri(extractedProperty.getUri())) {
			validationResults.add(
					isAlgorithmSpecifiedWhenHostKeySet(extractedProperty, context)
							&& isHostKeySpecifiedWhenAlgorithmSet(extractedProperty,
									context));
		}
	}
	return !validationResults.contains(false);
}
 
Example #3
Source File: ValidReservationValidator.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public boolean isValid(Reservation reservation, ConstraintValidatorContext context) {

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

    if (!(reservation instanceof Reservation)) {
        throw new IllegalArgumentException("Illegal method signature, expected parameter of type Reservation.");
    }

    if (reservation.getBegin() == null || reservation.getEnd() == null || reservation.getCustomer() == null) {
        return false;
    }

    return (reservation.getBegin()
        .isAfter(LocalDate.now())
        && reservation.getBegin()
            .isBefore(reservation.getEnd())
        && reservation.getRoom() > 0);
}
 
Example #4
Source File: ServerConfigsValidatorTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Before
public void onSetUp() {
    cvc = mock(ConstraintValidatorContext.class);

    for (AppType appType : AppType.values()) {

        ServerConfig serverConfig = new ServerConfig();
        serverConfig.setApp(appType);
        serverConfig.setServerAddress("localhost:123");
        serverConfig.setCommunicationType(CommunicationType.REST);
        serverConfig.setSslConfig(null);
        serverConfig.setInfluxConfig(null);
        serverConfig.setBindingAddress(null);

        serverConfigsMap.put(appType, serverConfig);
    }

    validator = new ServerConfigsValidator();

    when(cvc.buildConstraintViolationWithTemplate(anyString()))
            .thenReturn(mock(ConstraintValidatorContext.ConstraintViolationBuilder.class));
}
 
Example #5
Source File: SpringValidatorAdapterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
public boolean isValid(Object value, ConstraintValidatorContext context) {
	BeanWrapper beanWrapper = new BeanWrapperImpl(value);
	Object fieldValue = beanWrapper.getPropertyValue(field);
	Object comparingFieldValue = beanWrapper.getPropertyValue(comparingField);
	boolean matched = ObjectUtils.nullSafeEquals(fieldValue, comparingFieldValue);
	if (matched) {
		return true;
	}
	else {
		context.disableDefaultConstraintViolation();
		context.buildConstraintViolationWithTemplate(message)
				.addPropertyNode(field)
				.addConstraintViolation();
		return false;
	}
}
 
Example #6
Source File: ImageCatalogV4BaseTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws NoSuchFieldException, IllegalAccessException {
    Configuration<?> cfg = Validation.byDefaultProvider().configure();
    cfg.messageInterpolator(new ParameterMessageInterpolator());
    validator = cfg.buildValidatorFactory().getValidator();

    for (Entry<String, Object> entry : Map.of("HTTP_CONTENT_SIZE_VALIDATOR", httpContentSizeValidator, "HTTP_HELPER", httpHelper).entrySet()) {
        Field field = ReflectionUtils.findField(ImageCatalogValidator.class, entry.getKey());
        field.setAccessible(true);
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        field.set(null, entry.getValue());
    }

    when(httpContentSizeValidator.isValid(anyString(), any(ConstraintValidatorContext.class))).thenReturn(true);
    when(statusType.getFamily()).thenReturn(Family.SUCCESSFUL);
}
 
Example #7
Source File: EnsureFloatValidator.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
    if (value == null) {
        return false;
    } else if (value instanceof String) {
        try {
            Float.parseFloat(String.valueOf(value));
            return true;
        } catch (Throwable t) {
            return false;
        }
    } else if (value instanceof Float) {
        return true;
    } else {
        return false;
    }

}
 
Example #8
Source File: AbstractNumberValidator.java    From dolphin-platform with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean checkValid(final Number value, final ConstraintValidatorContext context) {
    if (value instanceof BigDecimal) {
        return checkValidBigDecimal((BigDecimal) value);
    } else if (value instanceof BigInteger) {
        return checkValidBigInteger((BigInteger) value);
    } else if (value instanceof CharSequence) {
        return checkValidCharSequence((CharSequence) value);
    } else if (value instanceof Byte ||
            value instanceof Short ||
            value instanceof Integer ||
            value instanceof Long) {
        return checkValidLong(value.longValue() );
    } else {
        throw new ValidationException("Property contains value of type " +
                value.getClass() +
                " whereas only BigDecimal, BigInteger, CharSequence, long, integer, " +
                "short, byte and their wrappers are supported."
        );
    }
}
 
Example #9
Source File: CertificateLengthValidator.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isValid(final Object value, final ConstraintValidatorContext context) {
  for (final String fieldName : fields) {
    try {
      final Field field = value.getClass().getDeclaredField(fieldName);
      field.setAccessible(true);

      if (StringUtils.isEmpty((String) field.get(value))) {
        return true;
      }

      final String certificate = (String) field.get(value);
      if (certificate.getBytes(UTF_8).length > 7000) {
        return false;
      }

    } catch (final NoSuchFieldException | IllegalAccessException e) {
      throw new RuntimeException(e);
    }
  }
  return true;
}
 
Example #10
Source File: RegExValidator.java    From onedev with MIT License 6 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintContext) {
	if (value == null) 
		return true;
	
	if (interpolative && !Interpolated.get()) try {
		value = StringUtils.unescape(Interpolative.parse(value).interpolateWith(new Function<String, String>() {

			@Override
			public String apply(String t) {
				return "a";
			}
			
		}));
	} catch (Exception e) {
		return true; // will be handled by interpolative validator
	}
	if (pattern.matcher(value).matches()) {
		return true;
	} else {
		constraintContext.disableDefaultConstraintViolation();
		constraintContext.buildConstraintViolationWithTemplate(message).addConstraintViolation();
		return false;
	}
}
 
Example #11
Source File: PasswordValidator.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    if (value.length() < length) {
        return false;
    }
    int nonAlphaNr = 0;
    for (int i = 0; i < value.length(); i++) {
        if (!Character.isLetterOrDigit(value.charAt(i))) {
            nonAlphaNr++;
        }
    }
    if (nonAlphaNr < nonAlpha) {
        return false;
    }
    return true;
}
 
Example #12
Source File: ParameterValidator.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isValid(final Map<String, String> value, final ConstraintValidatorContext context) {
    if (value == null || value.isEmpty()) {
        return true;
    }
    String message = null;
    for (String key : value.keySet()) {
        if (key == null || key.isEmpty()) {
            message = "key can not be empty";
        } else if (RequestContext.INTERNAL_KEY.test(key)) {
            message = "key \'" + key + "\' can not start with \'" + INTERNAL_KEY_PREFIX + "\'";
            break;
        }
    }
    if (message == null) {
        return true;
    }
    context.disableDefaultConstraintViolation();
    context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
    return false;
}
 
Example #13
Source File: ReviewRequirementValidator.java    From onedev with MIT License 6 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintContext) {
	if (value == null) {
		return true;
	} else {
		try {
			io.onedev.server.util.reviewrequirement.ReviewRequirement.parse(value, true);
			return true;
		} catch (Exception e) {
			constraintContext.disableDefaultConstraintViolation();
			String message = this.message;
			if (message.length() == 0) {
				if (StringUtils.isNotBlank(e.getMessage()))
					message = e.getMessage();
				else
					message = "Malformed review requirement";
			}
			constraintContext.buildConstraintViolationWithTemplate(message).addConstraintViolation();
			return false;
		}
	}
}
 
Example #14
Source File: CronValidator.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    if (value == null) {
        return true;
    }

    CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(type);
    CronParser cronParser = new CronParser(cronDefinition);
    try {
        cronParser.parse(value).validate();
        return true;
    } catch (IllegalArgumentException e) {
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(e.getMessage()).addConstraintViolation();
        return false;
    }
}
 
Example #15
Source File: NotNullPropertyValidator.java    From dolphin-platform with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValid(Property value,
                       ConstraintValidatorContext context) {
    if (value == null || value.get() == null) {
        return false;
    }
    return true;
}
 
Example #16
Source File: NumericValidator.java    From plumemo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    if (value == null || StringUtils.isBlank(value)) {
        return false;
    }
    if (!StringUtils.isNumeric(value)) {
        return false;
    }
    return true;
}
 
Example #17
Source File: AbstractCollectionValidator.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValid(final C collection, final ConstraintValidatorContext context) {
  if (collection != null && !collection.isEmpty()) {
    Iterator<E> iterator = collection.iterator();
    while (iterator.hasNext()) {
      E element = iterator.next();
      if (element == null || !isElementValid(element)) {
        return false;
      }
    }
  }
  return true;
}
 
Example #18
Source File: EnumBaseValidator.java    From java-master with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValid(EnumBase value, ConstraintValidatorContext context) {
    if (value == null) {
        return true;
    }
    if (value.getCode() < min || value.getCode() > max) {
        return false;
    }
    return true;
}
 
Example #19
Source File: MinByteLengthValidator.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean isValid(CharSequence suspect, ConstraintValidatorContext context) {
    if (Validators.isEmpty(suspect)) return true;
    try {
        return Validators.minByteLength(suspect, size, encoding);
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example #20
Source File: EmailValidator.java    From g-suite-identity-sync with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValid(CharSequence value, ConstraintValidatorContext context) {
    if (value == null || value.length() == 0) {
        return true;
    }

    // split email at '@' and consider local and domain part separately;
    // note a split limit of 3 is used as it causes all characters following to an (illegal) second @ character to
    // be put into a separate array element, avoiding the regex application in this case since the resulting array
    // has more than 2 elements
    String[] emailParts = value.toString().split("@", 3);
    if (emailParts.length != 2) {
        return false;
    }

    // if we have a trailing dot in local or domain part we have an invalid email address.
    // the regular expression match would take care of this, but IDN.toASCII drops the trailing '.'
    // (imo a bug in the implementation)
    if (emailParts[0].endsWith(".") || emailParts[1].endsWith(".")) {
        return false;
    }

    if (!matchPart(emailParts[0], localPattern, MAX_LOCAL_PART_LENGTH)) {
        return false;
    }

    return matchPart(emailParts[1], domainPattern, MAX_DOMAIN_PART_LENGTH);
}
 
Example #21
Source File: DnsNameValidator.java    From onedev with MIT License 5 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintContext) {
	if (value == null)
		return true;
	
	if (interpolative && !Interpolated.get()) try {
		value = StringUtils.unescape(Interpolative.parse(value).interpolateWith(new Function<String, String>() {

			@Override
			public String apply(String t) {
				return "a";
			}
			
		}));
	} catch (Exception e) {
		return true; // will be handled by interpolative validator
	}
	
	if (!PATTERN.matcher(value).matches()) {
		String message = this.message;
		if (message.length() == 0) {
			message = "Should only contain alphanumberic characters or '-', and can only "
					+ "start and end with alphanumeric characters";
		}
		constraintContext.buildConstraintViolationWithTemplate(message).addConstraintViolation();
		return false;
	} else {
		return true;
	}
}
 
Example #22
Source File: EnumTypeValidator.java    From spring-boot-plus with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {
    if (value == null) {
        return true;
    }
    return BaseEnumUtil.exists(baseEnum, value);
}
 
Example #23
Source File: CValidator.java    From hj-t212-parser with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
    int len;
    if(value == null){
        len = 0;
    }else{
        len = value.length();
    }
    return len <= max;
}
 
Example #24
Source File: PageOrderValidator.java    From disconf with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {

    if (value.equals(ASC) || value.equals(DESC) || value.isEmpty()) {
        return true;
    } else {
        return false;
    }
}
 
Example #25
Source File: MacAddressValidator.java    From yue-library with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
	if (StringUtils.isNotBlank(value)) {
		return Validator.isMac(value);
	}
	
	if (notNull) {
		return false;
	}
	
	return true;
}
 
Example #26
Source File: UUIDValidator.java    From yue-library with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
	if (StringUtils.isNotBlank(value)) {
		return Validator.isUUID(value);
	}
	
	if (notNull) {
		return false;
	}
	
	return true;
}
 
Example #27
Source File: MyConstraintValidator.java    From Spring-Boot-Book with Apache License 2.0 5 votes vote down vote up
/**
 * @Description: 自定义校验逻辑
 */
@Override
public boolean isValid(String s, ConstraintValidatorContext validatorContext) {
    if (!(s.equals("北京") || s.equals("上海"))) {
        return false;
    }

    return true;
}
 
Example #28
Source File: OrderValidator.java    From mall with MIT License 5 votes vote down vote up
@Override
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
    if (!valueList.contains(s.toUpperCase())) {
        return false;
    }
    return true;
}
 
Example #29
Source File: FixedEqualsToValidatorForBigInteger.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean isValid(BigInteger suspect, ConstraintValidatorContext context) {
    if (suspect == null) return true;
    return suspect.equals(value);

}
 
Example #30
Source File: MaxDataSizeValidator.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValid(DataSize value, ConstraintValidatorContext context) {
	// null values are valid
	if (value == null) {
		return true;
	}
	return value.toBytes() <= maxValue;
}