Search in sources :

Example 1 with ConstraintViolation

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;
}
Also used : Path(javax.validation.Path) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) Message(com.google.inject.spi.Message) IOException(java.io.IOException) AnnotatedField(com.fasterxml.jackson.databind.introspect.AnnotatedField) Field(java.lang.reflect.Field) Function(com.google.common.base.Function) ProvisionException(com.google.inject.ProvisionException) JacksonInject(com.fasterxml.jackson.annotation.JacksonInject) ConstraintViolation(javax.validation.ConstraintViolation)

Example 2 with ConstraintViolation

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());
}
Also used : ConstraintViolation(javax.validation.ConstraintViolation) Validator(javax.validation.Validator) Test(org.junit.Test)

Example 3 with ConstraintViolation

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);
        }
    }
}
Also used : Response(javax.ws.rs.core.Response) BeanDescriptor(javax.validation.metadata.BeanDescriptor) ConstraintViolation(javax.validation.ConstraintViolation) ConstraintViolationException(javax.validation.ConstraintViolationException) Method(java.lang.reflect.Method) MethodDescriptor(javax.validation.metadata.MethodDescriptor) HashSet(java.util.HashSet)

Example 4 with ConstraintViolation

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);
}
Also used : ManagePasswordOptionsForm(org.orcid.frontend.web.forms.ManagePasswordOptionsForm) ConstraintViolation(javax.validation.ConstraintViolation) Test(org.junit.Test)

Example 5 with ConstraintViolation

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);
}
Also used : ManagePasswordOptionsForm(org.orcid.frontend.web.forms.ManagePasswordOptionsForm) ConstraintViolation(javax.validation.ConstraintViolation) Test(org.junit.Test)

Aggregations

ConstraintViolation (javax.validation.ConstraintViolation)338 Test (org.junit.Test)194 Validator (javax.validation.Validator)76 ConstraintViolationException (javax.validation.ConstraintViolationException)53 ArrayList (java.util.ArrayList)29 ValidatorFactory (javax.validation.ValidatorFactory)27 HashSet (java.util.HashSet)22 Set (java.util.Set)22 Test (org.junit.jupiter.api.Test)20 Method (java.lang.reflect.Method)18 Name (org.kie.workbench.common.stunner.bpmn.definition.property.general.Name)16 Date (java.util.Date)14 EJBException (javax.ejb.EJBException)12 ExecutableValidator (javax.validation.executable.ExecutableValidator)12 PhoneNumberType (gov.ca.cwds.cals.persistence.model.calsns.dictionaries.PhoneNumberType)11 Path (javax.validation.Path)11 Customer (org.baeldung.javaxval.methodvalidation.model.Customer)11 CmsDocumentBlobSegment (gov.ca.cwds.data.persistence.cms.CmsDocumentBlobSegment)10 List (java.util.List)10 XmEntity (com.icthh.xm.ms.entity.domain.XmEntity)9