use of org.apache.sling.api.resource.ValueMap in project sling by apache.
the class ResourceAssertions method assertProperties.
public void assertProperties(String path, Object... props) {
final Map<String, Object> expected = MapArgsConverter.toMap(props);
final Resource r = assertResource(path);
final ValueMap vm = r.adaptTo(ValueMap.class);
for (Map.Entry<String, Object> e : expected.entrySet()) {
final Object value = vm.get(e.getKey());
assertNotNull("Expecting property " + e.getKey() + " for resource " + r.getPath());
assertEquals("Expecting value " + e.getValue() + " for property " + e.getKey() + " of resource " + r.getPath(), e.getValue(), value);
}
}
use of org.apache.sling.api.resource.ValueMap in project sling by apache.
the class ValidationServiceImplTest method testValidateNeverCalledWithNullValues.
@Test
public void testValidateNeverCalledWithNullValues() throws Exception {
Validator<String> myValidator = new Validator<String>() {
@Override
@Nonnull
public ValidationResult validate(@Nonnull String data, @Nonnull ValidatorContext context, @Nonnull ValueMap arguments) throws SlingValidationException {
Assert.assertNotNull("data parameter for validate should never be null", data);
Assert.assertNotNull("location of context parameter for validate should never be null", context.getLocation());
Assert.assertNotNull("valueMap of context parameter for validate should never be null", context.getValueMap());
Assert.assertNull("resource of context parameter for validate cannot be set if validate was called only with a value map", context.getResource());
Assert.assertNotNull("arguments parameter for validate should never be null", arguments);
return DefaultValidationResult.VALID;
}
};
validationService.validatorMap.put("someId", myValidator, validatorServiceReference, 10);
propertyBuilder.validator("someId", 20);
modelBuilder.resourceProperty(propertyBuilder.build("field1"));
ValidationModel vm = modelBuilder.build("sling/validation/test", "some source");
HashMap<String, Object> hashMap = new HashMap<String, Object>();
hashMap.put("field1", "1");
ValidationResult vr = validationService.validate(new ValueMapDecorator(hashMap), vm);
Assert.assertThat(vr.getFailures(), Matchers.hasSize(0));
Assert.assertTrue(vr.isValid());
}
use of org.apache.sling.api.resource.ValueMap 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.api.resource.ValueMap in project sling by apache.
the class ModifyUserServlet method doPost.
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
ValueMap requestParameters = request.adaptTo(ValueMap.class);
String[] resourceTypeValues = requestParameters.get("sling:resourceType", String[].class);
String resourceType = null;
if (resourceTypeValues != null && resourceTypeValues.length > 0) {
resourceType = resourceTypeValues[0];
}
if (resourceType != null && !"".equals(resourceType)) {
String resourcePath = request.getRequestPathInfo().getResourcePath();
ValidationModel vm = validationService.getValidationModel(resourceType, resourcePath, false);
if (vm != null) {
ValidationResult vr = validationService.validate(requestParameters, vm);
if (vr.isValid()) {
RequestDispatcherOptions options = new RequestDispatcherOptions();
options.setReplaceSelectors(" ");
request.getRequestDispatcher(request.getResource(), options).forward(request, response);
} else {
response.setContentType("application/json");
JSONWriter writer = new JSONWriter(response.getWriter());
writer.object();
writer.key("success").value(false);
writer.key("failures").array();
for (ValidationFailure failure : vr.getFailures()) {
writer.object();
writer.key("message").value(failure.getMessage(request.getResourceBundle(Locale.US)));
writer.key("location").value(failure.getLocation());
writer.endObject();
}
writer.endArray();
writer.endObject();
response.setStatus(400);
}
}
}
}
use of org.apache.sling.api.resource.ValueMap in project sling by apache.
the class ResourceAccessSecurityImplTests method testCannotUpdateAccidentallyUsingReadableResourceIfCannotUpdate.
@Test
public void testCannotUpdateAccidentallyUsingReadableResourceIfCannotUpdate() {
initMocks("/content", new String[] { "read", "update" });
Resource resource = mock(Resource.class);
when(resource.getPath()).thenReturn("/content");
ModifiableValueMap valueMap = mock(ModifiableValueMap.class);
when(resource.adaptTo(ModifiableValueMap.class)).thenReturn(valueMap);
when(resourceAccessGate.canRead(resource)).thenReturn(ResourceAccessGate.GateResult.GRANTED);
when(resourceAccessGate.canUpdate(resource)).thenReturn(ResourceAccessGate.GateResult.DENIED);
Resource readableResource = resourceAccessSecurity.getReadableResource(resource);
ValueMap resultValueMap = readableResource.adaptTo(ValueMap.class);
resultValueMap.put("modified", "value");
verify(valueMap, times(0)).put("modified", "value");
}
Aggregations