Search in sources :

Example 56 with ValueMap

use of org.apache.sling.api.resource.ValueMap in project sling by apache.

the class ResourceSerializer method create.

/** Dump given resource in JSON, optionally recursing into its objects */
private void create(final Resource resource, final JsonGenerator jgen, final int currentRecursionLevel, final SerializerProvider provider) throws IOException {
    jgen.writeStartObject();
    final ValueMap valueMap = resource.adaptTo(ValueMap.class);
    final Map propertyMap = (valueMap != null) ? valueMap : resource.adaptTo(Map.class);
    if (propertyMap == null) {
        // no map available, try string
        final String value = resource.adaptTo(String.class);
        if (value != null) {
            // single value property or just plain String resource or...
            jgen.writeStringField(resource.getName(), value);
        } else {
            // Try multi-value "property"
            final String[] values = resource.adaptTo(String[].class);
            if (values != null) {
                jgen.writeArrayFieldStart(resource.getName());
                for (final String s : values) {
                    jgen.writeString(s);
                }
                jgen.writeEndArray();
            }
        }
    } else {
        @SuppressWarnings("unchecked") final Iterator<Map.Entry> props = propertyMap.entrySet().iterator();
        // the node's actual properties
        while (props.hasNext()) {
            final Map.Entry prop = props.next();
            if (prop.getValue() != null) {
                createProperty(jgen, valueMap, prop.getKey().toString(), prop.getValue(), provider);
            }
        }
    }
    // the child nodes
    if (recursionLevelActive(currentRecursionLevel)) {
        for (final Resource n : resource.getChildren()) {
            jgen.writeObjectFieldStart(n.getName());
            create(n, jgen, currentRecursionLevel + 1, provider);
        }
    }
    jgen.writeEndObject();
}
Also used : ValueMap(org.apache.sling.api.resource.ValueMap) Resource(org.apache.sling.api.resource.Resource) ValueMap(org.apache.sling.api.resource.ValueMap) Map(java.util.Map)

Example 57 with ValueMap

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);
    }
}
Also used : ValueMap(org.apache.sling.api.resource.ValueMap) Resource(org.apache.sling.api.resource.Resource) ValueMap(org.apache.sling.api.resource.ValueMap) Map(java.util.Map)

Example 58 with ValueMap

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());
}
Also used : ValidationModel(org.apache.sling.validation.model.ValidationModel) Nonnull(javax.annotation.Nonnull) ValidatorContext(org.apache.sling.validation.spi.ValidatorContext) HashMap(java.util.HashMap) ValueMap(org.apache.sling.api.resource.ValueMap) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) ValueMapDecorator(org.apache.sling.api.wrappers.ValueMapDecorator) DefaultValidationResult(org.apache.sling.validation.spi.support.DefaultValidationResult) ValidationResult(org.apache.sling.validation.ValidationResult) DateValidator(org.apache.sling.validation.impl.util.examplevalidators.DateValidator) RegexValidator(org.apache.sling.validation.impl.validators.RegexValidator) Validator(org.apache.sling.validation.spi.Validator) Test(org.junit.Test)

Example 59 with ValueMap

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;
}
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 60 with ValueMap

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);
            }
        }
    }
}
Also used : JSONWriter(org.apache.felix.utils.json.JSONWriter) ValidationModel(org.apache.sling.validation.model.ValidationModel) RequestDispatcherOptions(org.apache.sling.api.request.RequestDispatcherOptions) ValueMap(org.apache.sling.api.resource.ValueMap) ValidationResult(org.apache.sling.validation.ValidationResult) ValidationFailure(org.apache.sling.validation.ValidationFailure)

Aggregations

ValueMap (org.apache.sling.api.resource.ValueMap)278 Resource (org.apache.sling.api.resource.Resource)205 Test (org.junit.Test)160 ModifiableValueMap (org.apache.sling.api.resource.ModifiableValueMap)59 HashMap (java.util.HashMap)54 ValueMapDecorator (org.apache.sling.api.wrappers.ValueMapDecorator)44 SlingHttpServletRequest (org.apache.sling.api.SlingHttpServletRequest)26 Map (java.util.Map)21 SlingHttpServletResponse (org.apache.sling.api.SlingHttpServletResponse)21 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)20 RewriterResponse (org.apache.sling.security.impl.ContentDispositionFilter.RewriterResponse)20 Expectations (org.jmock.Expectations)20 ArrayList (java.util.ArrayList)18 PersistenceException (org.apache.sling.api.resource.PersistenceException)17 Calendar (java.util.Calendar)16 Date (java.util.Date)15 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)15 NonExistingResource (org.apache.sling.api.resource.NonExistingResource)12 InputStream (java.io.InputStream)11 Node (javax.jcr.Node)11