Search in sources :

Example 1 with ValidationResult

use of org.apache.sling.validation.ValidationResult in project sling by apache.

the class ValidationResourceVisitor method visit.

@Override
protected void visit(Resource resource) {
    if (isValidSubResource(resource)) {
        @SuppressWarnings("null") ValidationModel model = validationService.getValidationModel(resource, considerResourceSuperTypeModels);
        if (model == null) {
            if (enforceValidation) {
                throw new IllegalArgumentException("No model for resource type " + resource.getResourceType() + " found.");
            }
            return;
        }
        // calculate the property name correctly from the root
        // the relative path must not end with a slash and not start with a slash
        @Nonnull final String relativePath;
        if (resource.getPath().startsWith(rootResourcePath)) {
            relativePath = resource.getPath().substring(rootResourcePath.length());
        } else {
            relativePath = "";
        }
        ValidationResult localResult = validationService.validate(resource, model, relativePath);
        result.addValidationResult(localResult);
    }
}
Also used : ValidationModel(org.apache.sling.validation.model.ValidationModel) Nonnull(javax.annotation.Nonnull) ValidationResult(org.apache.sling.validation.ValidationResult)

Example 2 with ValidationResult

use of org.apache.sling.validation.ValidationResult in project sling by apache.

the class ValidationServiceImpl method validateValue.

@SuppressWarnings({ "rawtypes", "unchecked" })
private void validateValue(CompositeValidationResult result, @Nonnull Object value, String property, String relativePath, @Nonnull ValueMap valueMap, Resource resource, @Nonnull Validator validator, ValueMap validatorParameters, @Nonnull ResourceBundle defaultResourceBundle, int severity) {
    try {
        ValidatorContext validationContext = new ValidatorContextImpl(relativePath + property, severity, valueMap, resource, defaultResourceBundle);
        ValidationResult validatorResult = ((Validator) validator).validate(value, validationContext, validatorParameters);
        result.addValidationResult(validatorResult);
    } catch (SlingValidationException e) {
        // wrap in another SlingValidationException to include information about the property
        throw new SlingValidationException("Could not call validator " + validator.getClass().getName() + " for resourceProperty " + relativePath + property, e);
    }
}
Also used : ValidatorContext(org.apache.sling.validation.spi.ValidatorContext) SlingValidationException(org.apache.sling.validation.SlingValidationException) ValidationResult(org.apache.sling.validation.ValidationResult) Validator(org.apache.sling.validation.spi.Validator)

Example 3 with ValidationResult

use of org.apache.sling.validation.ValidationResult in project sling by apache.

the class ValidationServiceImplTest method testValidateNeverCalledWithNullValues.

@Test
public void testValidateNeverCalledWithNullValues() throws Exception {
    Validator<String> myValidator = new Validator<String>() {

        @Override
        @Nonnull
        public ValidationResult validate(@Nonnull String data, @Nonnull ValidatorContext context, @Nonnull ValueMap arguments) throws SlingValidationException {
            Assert.assertNotNull("data parameter for validate should never be null", data);
            Assert.assertNotNull("location of context parameter for validate should never be null", context.getLocation());
            Assert.assertNotNull("valueMap of context parameter for validate should never be null", context.getValueMap());
            Assert.assertNull("resource of context parameter for validate cannot be set if validate was called only with a value map", context.getResource());
            Assert.assertNotNull("arguments parameter for validate should never be null", arguments);
            return DefaultValidationResult.VALID;
        }
    };
    validationService.validatorMap.put("someId", myValidator, validatorServiceReference, 10);
    propertyBuilder.validator("someId", 20);
    modelBuilder.resourceProperty(propertyBuilder.build("field1"));
    ValidationModel vm = modelBuilder.build("sling/validation/test", "some source");
    HashMap<String, Object> hashMap = new HashMap<String, Object>();
    hashMap.put("field1", "1");
    ValidationResult vr = validationService.validate(new ValueMapDecorator(hashMap), vm);
    Assert.assertThat(vr.getFailures(), Matchers.hasSize(0));
    Assert.assertTrue(vr.isValid());
}
Also used : ValidationModel(org.apache.sling.validation.model.ValidationModel) Nonnull(javax.annotation.Nonnull) ValidatorContext(org.apache.sling.validation.spi.ValidatorContext) HashMap(java.util.HashMap) ValueMap(org.apache.sling.api.resource.ValueMap) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) ValueMapDecorator(org.apache.sling.api.wrappers.ValueMapDecorator) DefaultValidationResult(org.apache.sling.validation.spi.support.DefaultValidationResult) ValidationResult(org.apache.sling.validation.ValidationResult) DateValidator(org.apache.sling.validation.impl.util.examplevalidators.DateValidator) RegexValidator(org.apache.sling.validation.impl.validators.RegexValidator) Validator(org.apache.sling.validation.spi.Validator) Test(org.junit.Test)

Example 4 with ValidationResult

use of org.apache.sling.validation.ValidationResult in project sling by apache.

the class ValidationServiceImplTest method testValidateResourceRecursively.

@Test()
public void testValidateResourceRecursively() throws Exception {
    modelBuilder.resourceProperty(propertyBuilder.build("field1"));
    final ValidationModel vm1 = modelBuilder.build("resourcetype1", "some source");
    modelBuilder = new ValidationModelBuilder();
    modelBuilder.resourceProperty(propertyBuilder.build("field2"));
    final ValidationModel vm2 = modelBuilder.build("resourcetype2", "some source");
    // set model retriever
    validationService.modelRetriever = new ValidationModelRetriever() {

        @Override
        @CheckForNull
        public ValidationModel getValidationModel(@Nonnull String resourceType, String resourcePath, boolean considerResourceSuperTypeModels) {
            if (resourceType.equals("resourcetype1")) {
                return vm1;
            } else if (resourceType.equals("resourcetype2")) {
                return vm2;
            } else {
                return null;
            }
        }
    };
    ResourceResolver rr = context.resourceResolver();
    // resource is lacking the required field (is invalid)
    Resource testResource = ResourceUtil.getOrCreateResource(rr, "/content/validation/1/resource", "resourcetype1", JcrConstants.NT_UNSTRUCTURED, true);
    // child1 is valid
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, "resourcetype2");
    properties.put("field2", "test");
    rr.create(testResource, "child1", properties);
    // child2 is invalid
    properties.clear();
    properties.put(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, "resourcetype2");
    rr.create(testResource, "child2", properties);
    // child3 has no model (but its resource type is ignored)
    properties.clear();
    properties.put(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, "resourcetype3");
    rr.create(testResource, "child3", properties);
    final Predicate<Resource> ignoreResourceType3Filter = new Predicate<Resource>() {

        @Override
        public boolean test(final Resource resource) {
            return !"resourcetype3".equals(resource.getResourceType());
        }
    };
    ValidationResult vr = validationService.validateResourceRecursively(testResource, true, ignoreResourceType3Filter, false);
    Assert.assertFalse("resource should have been considered invalid", vr.isValid());
    Assert.assertThat(vr.getFailures(), Matchers.<ValidationFailure>contains(new DefaultValidationFailure("", 20, defaultResourceBundle, ValidationServiceImpl.I18N_KEY_MISSING_REQUIRED_PROPERTY_WITH_NAME, "field1"), new DefaultValidationFailure("child2", 20, defaultResourceBundle, ValidationServiceImpl.I18N_KEY_MISSING_REQUIRED_PROPERTY_WITH_NAME, "field2")));
}
Also used : HashMap(java.util.HashMap) ValidationModelRetriever(org.apache.sling.validation.model.spi.ValidationModelRetriever) NonExistingResource(org.apache.sling.api.resource.NonExistingResource) Resource(org.apache.sling.api.resource.Resource) ChildResource(org.apache.sling.validation.model.ChildResource) SyntheticResource(org.apache.sling.api.resource.SyntheticResource) DefaultValidationResult(org.apache.sling.validation.spi.support.DefaultValidationResult) ValidationResult(org.apache.sling.validation.ValidationResult) Predicate(java.util.function.Predicate) ValidationModel(org.apache.sling.validation.model.ValidationModel) CheckForNull(javax.annotation.CheckForNull) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) DefaultValidationFailure(org.apache.sling.validation.spi.support.DefaultValidationFailure) ValidationModelBuilder(org.apache.sling.validation.impl.model.ValidationModelBuilder) Test(org.junit.Test)

Example 5 with ValidationResult

use of org.apache.sling.validation.ValidationResult in project sling by apache.

the class ValidationServiceImplTest method testSyntheticResource.

// see https://issues.apache.org/jira/browse/SLING-5749
@Test
public void testSyntheticResource() throws Exception {
    // accept any digits
    propertyBuilder.validator(REGEX_VALIDATOR_ID, 0, RegexValidator.REGEX_PARAM, "\\d");
    ResourceProperty property = propertyBuilder.build("field1");
    modelBuilder.resourceProperty(property);
    ChildResource modelChild = new ChildResourceImpl("child", null, true, Collections.singletonList(property), Collections.emptyList());
    modelBuilder.childResource(modelChild);
    modelChild = new ChildResourceImpl("optionalChild", null, false, Collections.singletonList(property), Collections.emptyList());
    modelBuilder.childResource(modelChild);
    ValidationModel vm = modelBuilder.build("sometype", "some source");
    ResourceResolver rr = context.resourceResolver();
    Resource nonExistingResource = new SyntheticResource(rr, "someresource", "resourceType");
    ValidationResult vr = validationService.validate(nonExistingResource, vm);
    Assert.assertFalse("resource should have been considered invalid", vr.isValid());
    Assert.assertThat(vr.getFailures(), Matchers.<ValidationFailure>containsInAnyOrder(new DefaultValidationFailure("", 20, defaultResourceBundle, ValidationServiceImpl.I18N_KEY_MISSING_REQUIRED_PROPERTY_WITH_NAME, "field1"), new DefaultValidationFailure("", 20, defaultResourceBundle, ValidationServiceImpl.I18N_KEY_MISSING_REQUIRED_CHILD_RESOURCE_WITH_NAME, "child")));
}
Also used : ResourceProperty(org.apache.sling.validation.model.ResourceProperty) ValidationModel(org.apache.sling.validation.model.ValidationModel) ChildResourceImpl(org.apache.sling.validation.impl.model.ChildResourceImpl) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) NonExistingResource(org.apache.sling.api.resource.NonExistingResource) Resource(org.apache.sling.api.resource.Resource) ChildResource(org.apache.sling.validation.model.ChildResource) SyntheticResource(org.apache.sling.api.resource.SyntheticResource) SyntheticResource(org.apache.sling.api.resource.SyntheticResource) ChildResource(org.apache.sling.validation.model.ChildResource) DefaultValidationFailure(org.apache.sling.validation.spi.support.DefaultValidationFailure) DefaultValidationResult(org.apache.sling.validation.spi.support.DefaultValidationResult) ValidationResult(org.apache.sling.validation.ValidationResult) Test(org.junit.Test)

Aggregations

ValidationResult (org.apache.sling.validation.ValidationResult)25 ValidationModel (org.apache.sling.validation.model.ValidationModel)22 Test (org.junit.Test)19 DefaultValidationResult (org.apache.sling.validation.spi.support.DefaultValidationResult)18 Resource (org.apache.sling.api.resource.Resource)14 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)13 NonExistingResource (org.apache.sling.api.resource.NonExistingResource)12 SyntheticResource (org.apache.sling.api.resource.SyntheticResource)12 ChildResource (org.apache.sling.validation.model.ChildResource)12 HashMap (java.util.HashMap)11 DefaultValidationFailure (org.apache.sling.validation.spi.support.DefaultValidationFailure)11 ValueMapDecorator (org.apache.sling.api.wrappers.ValueMapDecorator)8 ChildResourceImpl (org.apache.sling.validation.impl.model.ChildResourceImpl)6 ResourceProperty (org.apache.sling.validation.model.ResourceProperty)6 ModifiableValueMap (org.apache.sling.api.resource.ModifiableValueMap)5 Nonnull (javax.annotation.Nonnull)3 ValueMap (org.apache.sling.api.resource.ValueMap)3 Validator (org.apache.sling.validation.spi.Validator)3 ValidatorContext (org.apache.sling.validation.spi.ValidatorContext)3 LinkedHashMap (java.util.LinkedHashMap)2