use of javax.validation.ConstraintViolation in project druid by druid-io.
the class JsonConfigurator method configurate.
public <T> T configurate(Properties props, String propertyPrefix, Class<T> clazz) throws ProvisionException {
verifyClazzIsConfigurable(jsonMapper, clazz);
// Make it end with a period so we only include properties with sub-object thingies.
final String propertyBase = propertyPrefix.endsWith(".") ? propertyPrefix : propertyPrefix + ".";
Map<String, Object> jsonMap = Maps.newHashMap();
for (String prop : props.stringPropertyNames()) {
if (prop.startsWith(propertyBase)) {
final String propValue = props.getProperty(prop);
Object value;
try {
// If it's a String Jackson wants it to be quoted, so check if it's not an object or array and quote.
String modifiedPropValue = propValue;
if (!(modifiedPropValue.startsWith("[") || modifiedPropValue.startsWith("{"))) {
modifiedPropValue = jsonMapper.writeValueAsString(propValue);
}
value = jsonMapper.readValue(modifiedPropValue, Object.class);
} catch (IOException e) {
log.info(e, "Unable to parse [%s]=[%s] as a json object, using as is.", prop, propValue);
value = propValue;
}
jsonMap.put(prop.substring(propertyBase.length()), value);
}
}
final T config;
try {
config = jsonMapper.convertValue(jsonMap, clazz);
} catch (IllegalArgumentException e) {
throw new ProvisionException(String.format("Problem parsing object at prefix[%s]: %s.", propertyPrefix, e.getMessage()), e);
}
final Set<ConstraintViolation<T>> violations = validator.validate(config);
if (!violations.isEmpty()) {
List<String> messages = Lists.newArrayList();
for (ConstraintViolation<T> violation : violations) {
String path = "";
try {
Class<?> beanClazz = violation.getRootBeanClass();
final Iterator<Path.Node> iter = violation.getPropertyPath().iterator();
while (iter.hasNext()) {
Path.Node next = iter.next();
if (next.getKind() == ElementKind.PROPERTY) {
final String fieldName = next.getName();
final Field theField = beanClazz.getDeclaredField(fieldName);
if (theField.getAnnotation(JacksonInject.class) != null) {
path = String.format(" -- Injected field[%s] not bound!?", fieldName);
break;
}
JsonProperty annotation = theField.getAnnotation(JsonProperty.class);
final boolean noAnnotationValue = annotation == null || Strings.isNullOrEmpty(annotation.value());
final String pathPart = noAnnotationValue ? fieldName : annotation.value();
if (path.isEmpty()) {
path += pathPart;
} else {
path += "." + pathPart;
}
}
}
} catch (NoSuchFieldException e) {
throw Throwables.propagate(e);
}
messages.add(String.format("%s - %s", path, violation.getMessage()));
}
throw new ProvisionException(Iterables.transform(messages, new Function<String, Message>() {
@Override
public Message apply(String input) {
return new Message(String.format("%s%s", propertyBase, input));
}
}));
}
log.info("Loaded class[%s] from props[%s] as [%s]", clazz, propertyBase, config);
return config;
}
use of javax.validation.ConstraintViolation in project druid by druid-io.
the class S3DataSegmentPusherConfigTest method testSerializationValidatingMaxListingLength.
@Test
public void testSerializationValidatingMaxListingLength() throws IOException {
String jsonConfig = "{\"bucket\":\"bucket1\",\"baseKey\":\"dataSource1\"," + "\"disableAcl\":false,\"maxListingLength\":-1}";
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
S3DataSegmentPusherConfig config = jsonMapper.readValue(jsonConfig, S3DataSegmentPusherConfig.class);
Set<ConstraintViolation<S3DataSegmentPusherConfig>> violations = validator.validate(config);
Assert.assertEquals(1, violations.size());
ConstraintViolation violation = Iterators.getOnlyElement(violations.iterator());
Assert.assertEquals("must be greater than or equal to 0", violation.getMessage());
}
use of javax.validation.ConstraintViolation in project jersey by jersey.
the class DefaultConfiguredValidator method validateResult.
@Override
public void validateResult(final Object resource, final Invocable resourceMethod, final Object result) {
if (configuration.getBootstrapConfiguration().isExecutableValidationEnabled()) {
final Set<ConstraintViolation<Object>> constraintViolations = new HashSet<>();
final Method handlingMethod = resourceMethod.getHandlingMethod();
final BeanDescriptor beanDescriptor = getConstraintsForClass(resource.getClass());
final MethodDescriptor methodDescriptor = beanDescriptor.getConstraintsForMethod(handlingMethod.getName(), handlingMethod.getParameterTypes());
final Method definitionMethod = resourceMethod.getDefinitionMethod();
if (methodDescriptor != null && methodDescriptor.hasConstrainedReturnValue() && validateOnExecutionHandler.validateMethod(resource.getClass(), definitionMethod, handlingMethod)) {
constraintViolations.addAll(forExecutables().validateReturnValue(resource, handlingMethod, result));
if (result instanceof Response) {
constraintViolations.addAll(forExecutables().validateReturnValue(resource, handlingMethod, ((Response) result).getEntity()));
}
}
if (!constraintViolations.isEmpty()) {
throw new ConstraintViolationException(constraintViolations);
}
}
}
use of javax.validation.ConstraintViolation in project ORCID-Source by ORCID.
the class ManagePasswordOptionsValidationFormTest method testPasswordFormMissingData.
@Test
public void testPasswordFormMissingData() {
ManagePasswordOptionsForm form = new ManagePasswordOptionsForm();
form.setPassword("");
form.setRetypedPassword("");
Set<ConstraintViolation<ManagePasswordOptionsForm>> violations = validator.validate(form);
Map<String, String> allErrorValues = retrieveErrorKeyAndMessage(violations);
String password = allErrorValues.get("password");
String confirmedPassword = allErrorValues.get("retypedPassword");
String securityQuestion = allErrorValues.get("securityQuestionId");
String securityAnswer = allErrorValues.get("securityQuestionAnswer");
String digits = allErrorValues.get("verificationNumber");
assertEquals("Passwords must be 8 or more characters and contain at least 1 number and at least 1 alpha character or symbol", password);
assertEquals("The confirm password field is invalid.", confirmedPassword);
assertEquals("Please select a security question.", securityQuestion);
assertEquals("Please provide an answer to your security question.", securityAnswer);
assertEquals("Please enter a 4 digit verification number", digits);
}
use of javax.validation.ConstraintViolation in project ORCID-Source by ORCID.
the class ManagePasswordOptionsValidationFormTest method testPasswordFormatValidation.
@Test
public void testPasswordFormatValidation() throws Exception {
String pwErrorMessage = "Passwords must be 8 or more characters and contain at least 1 number and at least 1 alpha character or symbol";
String tooShortPassword = "pssword";
ManagePasswordOptionsForm form = new ManagePasswordOptionsForm();
form.setPassword(tooShortPassword);
Set<ConstraintViolation<ManagePasswordOptionsForm>> violations = validator.validate(form);
Map<String, String> allErrorValues = retrieveErrorKeyAndMessage(violations);
String passwordValidationError = allErrorValues.get("password");
assertEquals(pwErrorMessage, passwordValidationError);
String eightDigitsButLowerCaseAlphaOnly = "password";
form.setPassword(eightDigitsButLowerCaseAlphaOnly);
violations = validator.validate(form);
allErrorValues = retrieveErrorKeyAndMessage(violations);
passwordValidationError = allErrorValues.get("password");
assertEquals(pwErrorMessage, passwordValidationError);
String eightDigitsLowerUpperCaseButAlphaOnly = "pAssword";
form.setPassword(eightDigitsLowerUpperCaseButAlphaOnly);
violations = validator.validate(form);
allErrorValues = retrieveErrorKeyAndMessage(violations);
passwordValidationError = allErrorValues.get("password");
assertEquals(pwErrorMessage, passwordValidationError);
String eightCharactersLowerUpperCaseSymbol = "pAssw%rd";
form.setPassword(eightCharactersLowerUpperCaseSymbol);
violations = validator.validate(form);
allErrorValues = retrieveErrorKeyAndMessage(violations);
passwordValidationError = allErrorValues.get("password");
assertEquals(pwErrorMessage, passwordValidationError);
String eightMixedCharactersDigitsAndSymbol = "p4ssW&rd";
form.setPassword(eightMixedCharactersDigitsAndSymbol);
violations = validator.validate(form);
allErrorValues = retrieveErrorKeyAndMessage(violations);
passwordValidationError = allErrorValues.get("password");
assertNull(passwordValidationError);
String eightUpperCaseCharactersOnlyDigitsAndSymbol = "P4SSW&RD";
form.setPassword(eightUpperCaseCharactersOnlyDigitsAndSymbol);
violations = validator.validate(form);
allErrorValues = retrieveErrorKeyAndMessage(violations);
passwordValidationError = allErrorValues.get("password");
assertNull(passwordValidationError);
}
Aggregations