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