Search in sources :

Example 36 with ValidationModel

use of org.apache.sling.validation.model.ValidationModel in project sling by apache.

the class ValidationServiceImplTest method testValidateResourceRecursivelyWithMissingValidatorAndNoEnforcement.

@Test()
public void testValidateResourceRecursivelyWithMissingValidatorAndNoEnforcement() throws Exception {
    // set model retriever which never retrieves anything
    validationService.modelRetriever = new ValidationModelRetriever() {

        @Override
        @CheckForNull
        public ValidationModel getValidationModel(@Nonnull String resourceType, String resourcePath, boolean considerResourceSuperTypeModels) {
            return null;
        }
    };
    ResourceResolver rr = context.resourceResolver();
    // resource is having no connected validation model
    Resource testResource = ResourceUtil.getOrCreateResource(rr, "/content/validation/1/resource", "resourcetype1", JcrConstants.NT_UNSTRUCTURED, true);
    ValidationResult vr = validationService.validateResourceRecursively(testResource, false, null, false);
    Assert.assertTrue(vr.isValid());
}
Also used : ValidationModel(org.apache.sling.validation.model.ValidationModel) ValidationModelRetriever(org.apache.sling.validation.model.spi.ValidationModelRetriever) CheckForNull(javax.annotation.CheckForNull) 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) DefaultValidationResult(org.apache.sling.validation.spi.support.DefaultValidationResult) ValidationResult(org.apache.sling.validation.ValidationResult) Test(org.junit.Test)

Example 37 with ValidationModel

use of org.apache.sling.validation.model.ValidationModel in project sling by apache.

the class ValidationServiceImplTest method testResourceWithMissingGrandChildProperty.

@Test
public void testResourceWithMissingGrandChildProperty() throws Exception {
    // accept any digits
    propertyBuilder.validator(REGEX_VALIDATOR_ID, 0, RegexValidator.REGEX_PARAM, "\\d");
    ResourceProperty property = propertyBuilder.build("field1");
    modelBuilder.resourceProperty(property);
    ChildResource modelGrandChild = new ChildResourceImpl("grandchild", null, true, Collections.singletonList(property), Collections.<ChildResource>emptyList());
    ChildResource modelChild = new ChildResourceImpl("child", null, true, Collections.singletonList(property), Collections.singletonList(modelGrandChild));
    modelBuilder.childResource(modelChild);
    ValidationModel vm = modelBuilder.build("sometype", "some source");
    // create a resource
    ResourceResolver rr = context.resourceResolver();
    Resource testResource = ResourceUtil.getOrCreateResource(rr, "/content/validation/1/resource", JcrConstants.NT_UNSTRUCTURED, JcrConstants.NT_UNSTRUCTURED, true);
    ModifiableValueMap mvm = testResource.adaptTo(ModifiableValueMap.class);
    mvm.put("field1", "1");
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("field1", "1");
    Resource resourceChild = rr.create(testResource, "child", properties);
    // resourceGrandChild is missing the mandatory field1 property
    rr.create(resourceChild, "grandchild", null);
    ValidationResult vr = validationService.validate(testResource, vm);
    Assert.assertFalse("resource should have been considered invalid", vr.isValid());
    Assert.assertThat(vr.getFailures(), Matchers.<ValidationFailure>contains(new DefaultValidationFailure("child/grandchild", 20, defaultResourceBundle, ValidationServiceImpl.I18N_KEY_MISSING_REQUIRED_PROPERTY_WITH_NAME, "field1")));
}
Also used : HashMap(java.util.HashMap) 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) ChildResource(org.apache.sling.validation.model.ChildResource) DefaultValidationResult(org.apache.sling.validation.spi.support.DefaultValidationResult) ValidationResult(org.apache.sling.validation.ValidationResult) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) 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) DefaultValidationFailure(org.apache.sling.validation.spi.support.DefaultValidationFailure) Test(org.junit.Test)

Example 38 with ValidationModel

use of org.apache.sling.validation.model.ValidationModel in project sling by apache.

the class ResourceValidationModelProviderImpl method handleEvent.

@Override
public void handleEvent(Event event) {
    String path = (String) event.getProperty(SlingConstants.PROPERTY_PATH);
    if (path == null) {
        LOG.warn("Received event {}, but could not get the affected path", event);
        return;
    }
    Set<String> resourceTypesToInvalidate = new HashSet<>();
    switch(event.getTopic()) {
        case SlingConstants.TOPIC_RESOURCE_REMOVED:
            // find cache entries below the removed resource
            for (Entry<String, List<ValidationModel>> validationModelByResourceType : validationModelCacheByResourceType.entrySet()) {
                for (ValidationModel model : validationModelByResourceType.getValue()) {
                    if (model.getSource().startsWith(path)) {
                        LOG.debug("Invalidate validation model at {}, because resource at {} has been removed", model.getSource(), path);
                        resourceTypesToInvalidate.add(validationModelByResourceType.getKey());
                    }
                }
            }
            break;
        default:
            // only consider additions/changes of resources with resource type = validation model resource type
            String resourceType = (String) event.getProperty(SlingConstants.PROPERTY_RESOURCE_TYPE);
            if (resourceType == null) {
                LOG.warn("Received event {}, but could not get the modified/added resource type", event);
                return;
            }
            if (VALIDATION_MODEL_RESOURCE_TYPE.equals(resourceType)) {
                // retrieve the resource types covered by the newly added model
                String resourceTypeToInvalidate = null;
                try {
                    resourceTypeToInvalidate = getResourceTypeOfValidationModel(path);
                } catch (Exception e) {
                    LOG.warn("Could not get covered resource type of newly added validation model at " + path, e);
                }
                if (resourceTypeToInvalidate != null) {
                    LOG.debug("Invalidate validation models for resource type {}, because resource at {} provides a new/modified validation model for that type", resourceType, path);
                    resourceTypesToInvalidate.add(resourceTypeToInvalidate);
                } else {
                    LOG.debug("Resource at {} provides a new/modified validation model but could not yet determine for which resource type", path);
                }
            }
            // or paths already covered by the cache
            for (Entry<String, List<ValidationModel>> validationModelByResourceType : validationModelCacheByResourceType.entrySet()) {
                for (ValidationModel model : validationModelByResourceType.getValue()) {
                    if (path.startsWith(model.getSource())) {
                        LOG.debug("Invalidate validation model at {}, because resource below (at {}) has been modified", model.getSource(), path);
                        resourceTypesToInvalidate.add(validationModelByResourceType.getKey());
                    }
                }
            }
    }
    for (String resourceTypeToInvalidate : resourceTypesToInvalidate) {
        validationModelCacheByResourceType.remove(resourceTypeToInvalidate);
    }
}
Also used : ValidationModel(org.apache.sling.validation.model.ValidationModel) ArrayList(java.util.ArrayList) List(java.util.List) LoginException(org.apache.sling.api.resource.LoginException) HashSet(java.util.HashSet)

Example 39 with ValidationModel

use of org.apache.sling.validation.model.ValidationModel in project sling by apache.

the class ResourceValidationModelProviderImpl method doGetModels.

/** Searches for validation models bound to a specific resource type through a search query.
     *
     * @param relativeResourceType the resource type to look for
     * @return a List of {@link ValidationModel}s. Never {@code null}, but might be empty collection in case no model for the given resource
     *         type could be found. Returns the models below "/apps" before the models below "/libs".
     * @throws IllegalStateException in case a validation model is found but it is invalid */
@Nonnull
private List<ValidationModel> doGetModels(@Nonnull String relativeResourceType) {
    List<ValidationModel> validationModels = new ArrayList<ValidationModel>();
    ResourceResolver resourceResolver = null;
    try {
        resourceResolver = rrf.getServiceResourceResolver(null);
        String[] searchPaths = resourceResolver.getSearchPath();
        for (String searchPath : searchPaths) {
            final String queryString = String.format(MODEL_XPATH_QUERY, searchPath, relativeResourceType);
            LOG.debug("Looking for validation models with query '{}'", queryString);
            Iterator<Resource> models = resourceResolver.findResources(queryString, "xpath");
            while (models.hasNext()) {
                Resource model = models.next();
                LOG.debug("Found validation model resource {}.", model.getPath());
                String resourcePath = model.getPath();
                try {
                    ValidationModelBuilder modelBuilder = new ValidationModelBuilder();
                    ValueMap validationModelProperties = model.getValueMap();
                    modelBuilder.addApplicablePaths(validationModelProperties.get(ResourceValidationModelProviderImpl.APPLICABLE_PATHS, new String[] {}));
                    Resource propertiesResource = model.getChild(ResourceValidationModelProviderImpl.PROPERTIES);
                    modelBuilder.resourceProperties(buildProperties(propertiesResource));
                    modelBuilder.childResources(buildChildren(model, model));
                    ValidationModel vm = modelBuilder.build(relativeResourceType, resourcePath);
                    validationModels.add(vm);
                } catch (IllegalArgumentException e) {
                    throw new IllegalStateException("Found invalid validation model in '" + resourcePath + "': " + e.getMessage(), e);
                }
            }
            if (!validationModels.isEmpty()) {
                // the applicable content paths do not matter here!
                break;
            }
        }
        return validationModels;
    } catch (LoginException e) {
        throw new IllegalStateException("Could not get service resource resolver", e);
    } finally {
        if (resourceResolver != null) {
            resourceResolver.close();
        }
    }
}
Also used : ValueMap(org.apache.sling.api.resource.ValueMap) ArrayList(java.util.ArrayList) Resource(org.apache.sling.api.resource.Resource) ChildResource(org.apache.sling.validation.model.ChildResource) ValidationModel(org.apache.sling.validation.model.ValidationModel) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) LoginException(org.apache.sling.api.resource.LoginException) ValidationModelBuilder(org.apache.sling.validation.impl.model.ValidationModelBuilder) Nonnull(javax.annotation.Nonnull)

Example 40 with ValidationModel

use of org.apache.sling.validation.model.ValidationModel in project sling by apache.

the class ValidationModelRetrieverImplTest method testGetModelWithResourceInheritanceAndNoModelForSuperTypeFound.

@Test
public void testGetModelWithResourceInheritanceAndNoModelForSuperTypeFound() {
    applicablePathPerResourceType.put("test/type", "/content/site1");
    Mockito.when(resourceResolver.getParentResourceType("test/type")).thenReturn("test/supertype");
    Mockito.when(resourceResolver.getParentResourceType("test/supertype")).thenReturn("test/supersupertype");
    // only model found for base type
    ValidationModel model = validationModelRetriever.getValidationModel("test/type", "/content/site1", true);
    Assert.assertNotNull(model);
    Assert.assertThat(model.getResourceProperties(), Matchers.contains(new ResourcePropertyNameMatcher("test/type")));
}
Also used : ValidationModel(org.apache.sling.validation.model.ValidationModel) ResourcePropertyNameMatcher(org.apache.sling.validation.impl.util.ResourcePropertyNameMatcher) Test(org.junit.Test)

Aggregations

ValidationModel (org.apache.sling.validation.model.ValidationModel)53 Test (org.junit.Test)43 ValidationResult (org.apache.sling.validation.ValidationResult)22 Resource (org.apache.sling.api.resource.Resource)20 ChildResource (org.apache.sling.validation.model.ChildResource)20 DefaultValidationResult (org.apache.sling.validation.spi.support.DefaultValidationResult)17 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)15 HashMap (java.util.HashMap)13 NonExistingResource (org.apache.sling.api.resource.NonExistingResource)12 SyntheticResource (org.apache.sling.api.resource.SyntheticResource)12 DefaultValidationFailure (org.apache.sling.validation.spi.support.DefaultValidationFailure)11 ModifiableValueMap (org.apache.sling.api.resource.ModifiableValueMap)9 ValueMapDecorator (org.apache.sling.api.wrappers.ValueMapDecorator)9 ResourcePropertyBuilder (org.apache.sling.validation.impl.model.ResourcePropertyBuilder)8 ChildResourceImpl (org.apache.sling.validation.impl.model.ChildResourceImpl)7 ResourceProperty (org.apache.sling.validation.model.ResourceProperty)7 ValidationModelBuilder (org.apache.sling.validation.impl.model.ValidationModelBuilder)6 CheckForNull (javax.annotation.CheckForNull)5 Nonnull (javax.annotation.Nonnull)5 ValueMap (org.apache.sling.api.resource.ValueMap)4