Search in sources :

Example 1 with ResourceProperty

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

the class ValidationServiceImpl method validateValueMap.

private void validateValueMap(ValueMap valueMap, Resource resource, @Nonnull String relativePath, @Nonnull Collection<ResourceProperty> resourceProperties, @Nonnull CompositeValidationResult result, @Nonnull ResourceBundle defaultResourceBundle) {
    if (valueMap == null) {
        throw new IllegalArgumentException("ValueMap may not be null");
    }
    for (ResourceProperty resourceProperty : resourceProperties) {
        Pattern pattern = resourceProperty.getNamePattern();
        if (pattern != null) {
            boolean foundMatch = false;
            for (String key : valueMap.keySet()) {
                if (pattern.matcher(key).matches()) {
                    foundMatch = true;
                    validatePropertyValue(key, valueMap, resource, relativePath, resourceProperty, result, defaultResourceBundle);
                }
            }
            if (!foundMatch && resourceProperty.isRequired()) {
                result.addFailure(relativePath, configuration.defaultSeverity(), defaultResourceBundle, I18N_KEY_MISSING_REQUIRED_PROPERTY_MATCHING_PATTERN, pattern.toString());
            }
        } else {
            validatePropertyValue(resourceProperty.getName(), valueMap, resource, relativePath, resourceProperty, result, defaultResourceBundle);
        }
    }
}
Also used : ResourceProperty(org.apache.sling.validation.model.ResourceProperty) Pattern(java.util.regex.Pattern)

Example 2 with ResourceProperty

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

the class ResourceValidationModelProviderImplTest method setUp.

@Before
public void setUp() throws LoginException, PersistenceException, RepositoryException {
    primaryTypeUnstructuredMap = new HashMap<String, Object>();
    primaryTypeUnstructuredMap.put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED);
    modelProvider = new ResourceValidationModelProviderImpl();
    // one default model
    modelBuilder = new ValidationModelBuilder();
    modelBuilder.setApplicablePath("/content/site1");
    ResourcePropertyBuilder propertyBuilder = new ResourcePropertyBuilder();
    propertyBuilder.validator("validatorId", 10, RegexValidator.REGEX_PARAM, "prefix.*");
    ResourceProperty property = propertyBuilder.build("field1");
    modelBuilder.resourceProperty(property);
    prefixBasedResultHandler = new MockQueryResultHandler() {

        @Override
        public MockQueryResult executeQuery(MockQuery query) {
            if (!"xpath".equals(query.getLanguage())) {
                return null;
            }
            String statement = query.getStatement();
            // @validatingResourceType="<some-resource-type>"]
            if (statement.startsWith("/jcr:root/")) {
                statement = statement.substring("/jcr:root/".length() - 1);
            }
            // extract the prefix from the statement
            String prefix = Text.getAbsoluteParent(statement, 0);
            // extract the resource type from the statement
            Matcher matcher = RESOURCE_TYPE_PATTERN.matcher(statement);
            if (!matcher.matches()) {
                throw new IllegalArgumentException("Can only process query statements which contain a validatedResourceType but the statement is: " + statement);
            }
            String resourceType = matcher.group(1);
            PrefixAndResourceType prefixAndResourceType = new PrefixAndResourceType(prefix, resourceType);
            if (validatorModelNodesPerPrefixAndResourceType.keySet().contains(prefixAndResourceType)) {
                return new MockQueryResult(validatorModelNodesPerPrefixAndResourceType.get(prefixAndResourceType));
            }
            return null;
        }
    };
    rr = context.resourceResolver();
    modelProvider.rrf = resourceResolverFactory;
    // create a wrapper resource resolver, which cannot be closed (as the SlingContext will take care of that)
    ResourceResolver nonClosableResourceResolverWrapper = Mockito.spy(rr);
    // intercept all close calls
    Mockito.doNothing().when(nonClosableResourceResolverWrapper).close();
    // always use the context's resource resolver (because we never commit)
    Mockito.when(resourceResolverFactory.getServiceResourceResolver(Mockito.anyObject())).thenReturn(nonClosableResourceResolverWrapper);
    MockJcr.addQueryResultHandler(rr.adaptTo(Session.class), prefixBasedResultHandler);
    validatorModelNodesPerPrefixAndResourceType = new HashMap<PrefixAndResourceType, List<Node>>();
    appsValidatorsRoot = ResourceUtil.getOrCreateResource(rr, APPS + "/" + VALIDATION_MODELS_RELATIVE_PATH, (Map<String, Object>) null, "sling:Folder", true);
    libsValidatorsRoot = ResourceUtil.getOrCreateResource(rr, LIBS + "/" + VALIDATION_MODELS_RELATIVE_PATH, (Map<String, Object>) null, "sling:Folder", true);
}
Also used : Matcher(java.util.regex.Matcher) ResourcePropertyBuilder(org.apache.sling.validation.impl.model.ResourcePropertyBuilder) MockQueryResultHandler(org.apache.sling.testing.mock.jcr.MockQueryResultHandler) ResourceProperty(org.apache.sling.validation.model.ResourceProperty) MockQueryResult(org.apache.sling.testing.mock.jcr.MockQueryResult) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) ArrayList(java.util.ArrayList) List(java.util.List) MockQuery(org.apache.sling.testing.mock.jcr.MockQuery) ValueMap(org.apache.sling.api.resource.ValueMap) HashMap(java.util.HashMap) Map(java.util.Map) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) ValidationModelBuilder(org.apache.sling.validation.impl.model.ValidationModelBuilder) Session(javax.jcr.Session) Before(org.junit.Before)

Example 3 with ResourceProperty

use of org.apache.sling.validation.model.ResourceProperty 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)

Example 4 with ResourceProperty

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

the class ResourceValidationModelProviderImpl method buildProperties.

/** Creates a set of the properties that a resource is expected to have, together with the associated validators.
     *
     * @param propertiesResource the resource identifying the properties node from a validation model's structure (might be {@code null})
     * @return a set of properties or an empty set if no properties are defined
     * @see ResourceProperty */
@Nonnull
private List<ResourceProperty> buildProperties(@Nonnull Resource propertiesResource) {
    List<ResourceProperty> properties = new ArrayList<ResourceProperty>();
    if (propertiesResource != null) {
        for (Resource propertyResource : propertiesResource.getChildren()) {
            ResourcePropertyBuilder resourcePropertyBuilder = new ResourcePropertyBuilder();
            String fieldName = propertyResource.getName();
            ValueMap propertyValueMap = propertyResource.getValueMap();
            if (propertyValueMap.get(ResourceValidationModelProviderImpl.PROPERTY_MULTIPLE, false)) {
                resourcePropertyBuilder.multiple();
            }
            if (propertyValueMap.get(ResourceValidationModelProviderImpl.OPTIONAL, false)) {
                resourcePropertyBuilder.optional();
            }
            String nameRegex = propertyValueMap.get(ResourceValidationModelProviderImpl.NAME_REGEX, String.class);
            if (nameRegex != null) {
                resourcePropertyBuilder.nameRegex(nameRegex);
            }
            Resource validators = propertyResource.getChild(ResourceValidationModelProviderImpl.VALIDATORS);
            if (validators != null) {
                Iterator<Resource> validatorsIterator = validators.listChildren();
                while (validatorsIterator.hasNext()) {
                    Resource validatorResource = validatorsIterator.next();
                    ValueMap validatorProperties = validatorResource.adaptTo(ValueMap.class);
                    if (validatorProperties == null) {
                        throw new IllegalStateException("Could not adapt resource at '" + validatorResource.getPath() + "' to ValueMap");
                    }
                    String validatorId = validatorResource.getName();
                    // get arguments for validator
                    String[] validatorArguments = validatorProperties.get(ResourceValidationModelProviderImpl.VALIDATOR_ARGUMENTS, String[].class);
                    Map<String, Object> validatorArgumentsMap = new HashMap<String, Object>();
                    if (validatorArguments != null) {
                        for (String arg : validatorArguments) {
                            int positionOfSeparator = arg.indexOf("=");
                            if (positionOfSeparator < 1 || positionOfSeparator >= arg.length() - 1) {
                                throw new IllegalArgumentException("Invalid validator argument '" + arg + "' found, because it does not follow the format '<key>=<value>'");
                            }
                            String key = arg.substring(0, positionOfSeparator);
                            String value = arg.substring(positionOfSeparator + 1);
                            Object newValue;
                            if (validatorArgumentsMap.containsKey(key)) {
                                Object oldValue = validatorArgumentsMap.get(key);
                                // either extend old array
                                if (oldValue instanceof String[]) {
                                    String[] oldArray = (String[]) oldValue;
                                    int newLength = oldArray.length + 1;
                                    String[] newArray = Arrays.copyOf(oldArray, oldArray.length + 1);
                                    newArray[newLength - 1] = value;
                                    newValue = newArray;
                                } else {
                                    // or turn the single value into a multi-value array
                                    newValue = new String[] { (String) oldValue, value };
                                }
                            } else {
                                newValue = value;
                            }
                            validatorArgumentsMap.put(key, newValue);
                        }
                    }
                    // get severity
                    Integer severity = validatorProperties.get(SEVERITY, Integer.class);
                    resourcePropertyBuilder.validator(validatorId, severity, validatorArgumentsMap);
                }
            }
            properties.add(resourcePropertyBuilder.build(fieldName));
        }
    }
    return properties;
}
Also used : HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) 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) ResourcePropertyBuilder(org.apache.sling.validation.impl.model.ResourcePropertyBuilder) ResourceProperty(org.apache.sling.validation.model.ResourceProperty) Nonnull(javax.annotation.Nonnull)

Example 5 with ResourceProperty

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

the class ValidationServiceImplTest method testNonExistingResource.

// see https://issues.apache.org/jira/browse/SLING-5674
@Test
public void testNonExistingResource() 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 NonExistingResource(rr, "non-existing-resource");
    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) NonExistingResource(org.apache.sling.api.resource.NonExistingResource) 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) 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

ResourceProperty (org.apache.sling.validation.model.ResourceProperty)11 ChildResource (org.apache.sling.validation.model.ChildResource)9 Resource (org.apache.sling.api.resource.Resource)8 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)8 ChildResourceImpl (org.apache.sling.validation.impl.model.ChildResourceImpl)7 ValidationModel (org.apache.sling.validation.model.ValidationModel)7 Test (org.junit.Test)7 HashMap (java.util.HashMap)6 NonExistingResource (org.apache.sling.api.resource.NonExistingResource)6 SyntheticResource (org.apache.sling.api.resource.SyntheticResource)6 ValidationResult (org.apache.sling.validation.ValidationResult)6 DefaultValidationResult (org.apache.sling.validation.spi.support.DefaultValidationResult)6 DefaultValidationFailure (org.apache.sling.validation.spi.support.DefaultValidationFailure)4 ModifiableValueMap (org.apache.sling.api.resource.ModifiableValueMap)3 ValueMap (org.apache.sling.api.resource.ValueMap)3 ResourcePropertyBuilder (org.apache.sling.validation.impl.model.ResourcePropertyBuilder)3 ArrayList (java.util.ArrayList)2 Pattern (java.util.regex.Pattern)2 List (java.util.List)1 Map (java.util.Map)1