Search in sources :

Example 1 with ValidatorInvocation

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

the class ValidationServiceImpl method validatePropertyValue.

private void validatePropertyValue(@Nonnull String property, ValueMap valueMap, Resource resource, @Nonnull String relativePath, @Nonnull ResourceProperty resourceProperty, @Nonnull CompositeValidationResult result, @Nonnull ResourceBundle defaultResourceBundle) {
    Object fieldValues = valueMap.get(property);
    if (fieldValues == null) {
        if (resourceProperty.isRequired()) {
            result.addFailure(relativePath, configuration.defaultSeverity(), defaultResourceBundle, I18N_KEY_MISSING_REQUIRED_PROPERTY_WITH_NAME, property);
        }
        return;
    }
    List<ValidatorInvocation> validatorInvocations = resourceProperty.getValidatorInvocations();
    if (resourceProperty.isMultiple()) {
        if (!fieldValues.getClass().isArray()) {
            result.addFailure(relativePath + property, configuration.defaultSeverity(), defaultResourceBundle, I18N_KEY_EXPECTED_MULTIVALUE_PROPERTY);
            return;
        }
    }
    for (ValidatorInvocation validatorInvocation : validatorInvocations) {
        // lookup validator by id
        ValidatorMetadata validatorMetadata = validatorMap.get(validatorInvocation.getValidatorId());
        if (validatorMetadata == null) {
            throw new IllegalStateException("Could not find validator with id '" + validatorInvocation.getValidatorId() + "'");
        }
        int severity = getSeverityForValidator(validatorInvocation.getSeverity(), validatorMetadata.getSeverity());
        // convert the type always to an array
        Class<?> type = validatorMetadata.getType();
        if (!type.isArray()) {
            try {
                // https://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getName%28%29 has some hints on class names
                type = Class.forName("[L" + type.getName() + ";", false, type.getClassLoader());
            } catch (ClassNotFoundException e) {
                throw new SlingValidationException("Could not generate array class for type " + type, e);
            }
        }
        // it is already validated here that the property exists in the value map
        Object[] typedValue = (Object[]) valueMap.get(property, type);
        // see https://issues.apache.org/jira/browse/SLING-4178 for why the second check is necessary
        if (typedValue == null || (typedValue.length > 0 && typedValue[0] == null)) {
            // here the missing required property case was already treated in validateValueMap
            result.addFailure(relativePath + property, severity, defaultResourceBundle, I18N_KEY_WRONG_PROPERTY_TYPE, validatorMetadata.getType());
            return;
        }
        // see https://issues.apache.org/jira/browse/SLING-662 for a description on how multivalue properties are treated with ValueMap
        if (validatorMetadata.getType().isArray()) {
            // ValueMap already returns an array in both cases (property is single value or multivalue)
            validateValue(result, typedValue, property, relativePath, valueMap, resource, validatorMetadata.getValidator(), validatorInvocation.getParameters(), defaultResourceBundle, severity);
        } else {
            // call validate for each entry in the array (supports both singlevalue and multivalue)
            @Nonnull Object[] array = (Object[]) typedValue;
            if (array.length == 1) {
                validateValue(result, array[0], property, relativePath, valueMap, resource, validatorMetadata.getValidator(), validatorInvocation.getParameters(), defaultResourceBundle, severity);
            } else {
                int n = 0;
                for (Object item : array) {
                    validateValue(result, item, property + "[" + n++ + "]", relativePath, valueMap, resource, validatorMetadata.getValidator(), validatorInvocation.getParameters(), defaultResourceBundle, severity);
                }
            }
        }
    }
}
Also used : ValidatorInvocation(org.apache.sling.validation.model.ValidatorInvocation) Nonnull(javax.annotation.Nonnull) ValidatorMetadata(org.apache.sling.validation.impl.ValidatorMap.ValidatorMetadata) SlingValidationException(org.apache.sling.validation.SlingValidationException)

Example 2 with ValidatorInvocation

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

the class ResourceValidationModelProviderImplTest method createValidationModelProperties.

/**
     * Always uses the validator's class name as validator resource name.
     * @param model
     * @param properties
     * @throws PersistenceException
     */
private void createValidationModelProperties(Resource model, @Nonnull Collection<ResourceProperty> properties) throws PersistenceException {
    ResourceResolver rr = model.getResourceResolver();
    if (properties.isEmpty()) {
        return;
    }
    Resource propertiesResource = ResourceUtil.getOrCreateResource(rr, model.getPath() + "/" + ResourceValidationModelProviderImpl.PROPERTIES, JcrConstants.NT_UNSTRUCTURED, null, true);
    for (ResourceProperty property : properties) {
        Map<String, Object> modelPropertyJCRProperties = new HashMap<String, Object>();
        modelPropertyJCRProperties.put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED);
        Resource propertyResource = ResourceUtil.getOrCreateResource(rr, propertiesResource.getPath() + "/" + property.getName(), modelPropertyJCRProperties, null, true);
        if (propertyResource != null) {
            ModifiableValueMap values = propertyResource.adaptTo(ModifiableValueMap.class);
            Pattern pattern = property.getNamePattern();
            if (pattern != null) {
                values.put(ResourceValidationModelProviderImpl.NAME_REGEX, pattern.pattern());
            }
            values.put(ResourceValidationModelProviderImpl.PROPERTY_MULTIPLE, property.isMultiple());
            values.put(ResourceValidationModelProviderImpl.OPTIONAL, !property.isRequired());
            Resource validators = ResourceUtil.getOrCreateResource(rr, propertyResource.getPath() + "/" + ResourceValidationModelProviderImpl.VALIDATORS, JcrConstants.NT_UNSTRUCTURED, null, true);
            if (validators != null) {
                for (ValidatorInvocation validatorIncovation : property.getValidatorInvocations()) {
                    Map<String, Object> validatorProperties = new HashMap<String, Object>();
                    validatorProperties.put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED);
                    ValueMap parameters = validatorIncovation.getParameters();
                    if (!parameters.isEmpty()) {
                        // convert to right format
                        validatorProperties.put(ResourceValidationModelProviderImpl.VALIDATOR_ARGUMENTS, convertMapToJcrValidatorArguments(parameters));
                    }
                    Integer severity = validatorIncovation.getSeverity();
                    if (severity != null) {
                        validatorProperties.put(ResourceValidationModelProviderImpl.SEVERITY, severity);
                    }
                    ResourceUtil.getOrCreateResource(rr, validators.getPath() + "/" + validatorIncovation.getValidatorId(), validatorProperties, null, true);
                }
            }
        }
    }
}
Also used : ResourceProperty(org.apache.sling.validation.model.ResourceProperty) Pattern(java.util.regex.Pattern) ValidatorInvocation(org.apache.sling.validation.model.ValidatorInvocation) HashMap(java.util.HashMap) ValueMap(org.apache.sling.api.resource.ValueMap) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Resource(org.apache.sling.api.resource.Resource) ChildResource(org.apache.sling.validation.model.ChildResource) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap)

Aggregations

ValidatorInvocation (org.apache.sling.validation.model.ValidatorInvocation)2 HashMap (java.util.HashMap)1 Pattern (java.util.regex.Pattern)1 Nonnull (javax.annotation.Nonnull)1 ModifiableValueMap (org.apache.sling.api.resource.ModifiableValueMap)1 Resource (org.apache.sling.api.resource.Resource)1 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)1 ValueMap (org.apache.sling.api.resource.ValueMap)1 SlingValidationException (org.apache.sling.validation.SlingValidationException)1 ValidatorMetadata (org.apache.sling.validation.impl.ValidatorMap.ValidatorMetadata)1 ChildResource (org.apache.sling.validation.model.ChildResource)1 ResourceProperty (org.apache.sling.validation.model.ResourceProperty)1