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());
}
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")));
}
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);
}
}
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();
}
}
}
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")));
}
Aggregations