Search in sources :

Example 11 with ConstraintViolation

use of javax.validation.ConstraintViolation in project dropwizard by dropwizard.

the class ParamValidatorUnwrapperTest method failsWithInvalidNonEmptyStringParam.

@Test
public void failsWithInvalidNonEmptyStringParam() {
    final Example example = new Example();
    example.name = new NonEmptyStringParam("hello");
    final Set<ConstraintViolation<Example>> validate = validator.validate(example);
    assertThat(validate).hasSize(1);
}
Also used : NonEmptyStringParam(io.dropwizard.jersey.params.NonEmptyStringParam) ConstraintViolation(javax.validation.ConstraintViolation) Test(org.junit.Test)

Example 12 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 13 with ConstraintViolation

use of javax.validation.ConstraintViolation in project dropwizard by dropwizard.

the class DropwizardConfiguredValidator method validateResourceAndInputParams.

@Override
public void validateResourceAndInputParams(Object resource, final Invocable invocable, Object[] objects) throws ConstraintViolationException {
    final Class<?>[] groups = getGroup(invocable);
    final Set<ConstraintViolation<Object>> violations = new HashSet<>();
    final BeanDescriptor beanDescriptor = getConstraintsForClass(resource.getClass());
    if (beanDescriptor.isBeanConstrained()) {
        violations.addAll(validate(resource, groups));
    }
    violations.addAll(forExecutables().validateParameters(resource, invocable.getHandlingMethod(), objects, groups));
    if (!violations.isEmpty()) {
        throw new JerseyViolationException(violations, invocable);
    }
}
Also used : BeanDescriptor(javax.validation.metadata.BeanDescriptor) ConstraintViolation(javax.validation.ConstraintViolation) HashSet(java.util.HashSet)

Example 14 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 15 with ConstraintViolation

use of javax.validation.ConstraintViolation in project dropwizard by dropwizard.

the class ConstraintViolationBenchmark method prepare.

@Setup
public void prepare() {
    final Validator validator = Validators.newValidator();
    final ExecutableValidator execValidator = validator.forExecutables();
    final Set<ConstraintViolation<ConstraintViolationBenchmark.Resource>> paramViolations = execValidator.validateParameters(new Resource(), getAccessibleMethod(ConstraintViolationBenchmark.Resource.class, "paramFunc", String.class), // the parameter value
    new Object[] { "" });
    paramViolation = paramViolations.iterator().next();
    final Set<ConstraintViolation<ConstraintViolationBenchmark.Resource>> objViolations = execValidator.validateParameters(new Resource(), getAccessibleMethod(ConstraintViolationBenchmark.Resource.class, "objectFunc", Foo.class), // the parameter value
    new Object[] { new Foo() });
    objViolation = objViolations.iterator().next();
}
Also used : ExecutableValidator(javax.validation.executable.ExecutableValidator) ConstraintViolation(javax.validation.ConstraintViolation) Validator(javax.validation.Validator) ExecutableValidator(javax.validation.executable.ExecutableValidator) Setup(org.openjdk.jmh.annotations.Setup)

Aggregations

ConstraintViolation (javax.validation.ConstraintViolation)95 Test (org.junit.Test)78 Validator (javax.validation.Validator)19 ConstraintViolationException (javax.validation.ConstraintViolationException)12 SMSMessage (org.apache.camel.component.cm.client.SMSMessage)12 ChangePasswordForm (org.orcid.frontend.web.forms.ChangePasswordForm)11 CmsDocumentBlobSegment (gov.ca.cwds.data.persistence.cms.CmsDocumentBlobSegment)10 ValidatorFactory (javax.validation.ValidatorFactory)9 ManagePasswordOptionsForm (org.orcid.frontend.web.forms.ManagePasswordOptionsForm)8 ArrayList (java.util.ArrayList)6 HashSet (java.util.HashSet)6 CMConfiguration (org.apache.camel.component.cm.CMConfiguration)6 Set (java.util.Set)5 InitialContext (javax.naming.InitialContext)5 Session (org.hibernate.Session)5 Transaction (org.hibernate.Transaction)5 Method (java.lang.reflect.Method)4 ExecutableValidator (javax.validation.executable.ExecutableValidator)4 CamelExecutionException (org.apache.camel.CamelExecutionException)4 Exchange (org.apache.camel.Exchange)4