Search in sources :

Example 91 with ModifiableValueMap

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

the class ResourceValidationModelProviderImplTest method testGetValidationModelsWithInvalidValidatorArguments3.

@Test(expected = IllegalStateException.class)
public void testGetValidationModelsWithInvalidValidatorArguments3() throws Exception {
    // create a model with neither children nor properties
    ValidationModel model1 = modelBuilder.build("sling/validation/test", libsValidatorsRoot.getPath() + "/testValidationModel1");
    // create valid model first
    Resource modelResource = createValidationModelResource(rr, libsValidatorsRoot.getPath(), "testValidationModel1", model1);
    // and make parametrization of validator invalid afterwards
    Resource validatorResource = modelResource.getChild("properties/field1/validators/validatorId");
    ModifiableValueMap validatorArguments = validatorResource.adaptTo(ModifiableValueMap.class);
    // ending with "="
    validatorArguments.put("validatorArguments", "key1=");
    Collection<ValidationModel> models = modelProvider.getValidationModels("sling/validation/test");
    Assert.assertThat(models, Matchers.contains(model1));
}
Also used : ValidationModel(org.apache.sling.validation.model.ValidationModel) Resource(org.apache.sling.api.resource.Resource) ChildResource(org.apache.sling.validation.model.ChildResource) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) Test(org.junit.Test)

Example 92 with ModifiableValueMap

use of org.apache.sling.api.resource.ModifiableValueMap 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)

Example 93 with ModifiableValueMap

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

the class SlingFileUploadHandler method processChunk.

/**
     * Process chunk upload. For first and intermediate chunks request persists
     * chunks at jcr:content/chunk_start_end/jcr:data or
     * nt:resource/chunk_start_end/jcr:data. For last last chunk,
     * merge all previous chunks and last chunk and replace binary at
     * destination.
     */
private void processChunk(final Resource resParent, final Resource res, final RequestProperty prop, final RequestParameter value, final List<Modification> changes) throws PersistenceException {
    try {
        final ModifiableValueMap mvm = res.adaptTo(ModifiableValueMap.class);
        long chunkOffset = prop.getChunk().getOffset();
        if (chunkOffset == 0) {
            // first chunk
            // check if another chunk upload is already in progress. throw
            // exception
            final Iterator<Resource> itr = new FilteringResourceIterator(res.listChildren(), SlingPostConstants.CHUNK_NODE_NAME);
            if (itr.hasNext()) {
                throw new PersistenceException("Chunk upload already in progress at {" + res.getPath() + "}");
            }
            addChunkMixin(mvm);
            mvm.put(SlingPostConstants.NT_SLING_CHUNKS_LENGTH, 0);
            changes.add(Modification.onModified(res.getPath() + "/" + SlingPostConstants.NT_SLING_CHUNKS_LENGTH));
            if (mvm.get(JcrConstants.JCR_DATA) == null) {
                // create a empty jcr:data property
                mvm.put(JcrConstants.JCR_DATA, new ByteArrayInputStream("".getBytes()));
            }
        }
        if (mvm.get(SlingPostConstants.NT_SLING_CHUNKS_LENGTH) == null) {
            throw new PersistenceException("no chunk upload found at {" + res.getPath() + "}");
        }
        long currentLength = mvm.get(SlingPostConstants.NT_SLING_CHUNKS_LENGTH, Long.class);
        long totalLength = prop.getChunk().getLength();
        if (chunkOffset != currentLength) {
            throw new PersistenceException("Chunk's offset {" + chunkOffset + "} doesn't match expected offset {" + currentLength + "}");
        }
        if (totalLength != 0) {
            if (mvm.get(SlingPostConstants.NT_SLING_FILE_LENGTH) != null) {
                long expectedLength = mvm.get(SlingPostConstants.NT_SLING_FILE_LENGTH, Long.class);
                if (totalLength != expectedLength) {
                    throw new PersistenceException("File length {" + totalLength + "} doesn't match expected length {" + expectedLength + "}");
                }
            } else {
                mvm.put(SlingPostConstants.NT_SLING_FILE_LENGTH, totalLength);
            }
        }
        final Iterator<Resource> itr = new FilteringResourceIterator(res.listChildren(), SlingPostConstants.CHUNK_NODE_NAME + "_" + String.valueOf(chunkOffset));
        if (itr.hasNext()) {
            throw new PersistenceException("Chunk already present at {" + itr.next().getPath() + "}");
        }
        String nodeName = SlingPostConstants.CHUNK_NODE_NAME + "_" + String.valueOf(chunkOffset) + "_" + String.valueOf(chunkOffset + value.getSize() - 1);
        if (totalLength == (currentLength + value.getSize()) || prop.getChunk().isCompleted()) {
            File file = null;
            InputStream fileIns = null;
            try {
                file = mergeChunks(res, value.getInputStream());
                fileIns = new FileInputStream(file);
                mvm.put(JcrConstants.JCR_DATA, fileIns);
                changes.add(Modification.onModified(res.getPath() + "/" + JcrConstants.JCR_DATA));
                final Iterator<Resource> rsrcItr = new FilteringResourceIterator(res.listChildren(), SlingPostConstants.CHUNK_NODE_NAME);
                while (rsrcItr.hasNext()) {
                    Resource rsrcRange = rsrcItr.next();
                    changes.add(Modification.onDeleted(rsrcRange.getPath()));
                    rsrcRange.getResourceResolver().delete(rsrcRange);
                }
                if (mvm.get(SlingPostConstants.NT_SLING_FILE_LENGTH) != null) {
                    changes.add(Modification.onDeleted(res.getPath() + "/" + SlingPostConstants.NT_SLING_FILE_LENGTH));
                    mvm.remove(SlingPostConstants.NT_SLING_FILE_LENGTH);
                }
                if (mvm.get(SlingPostConstants.NT_SLING_CHUNKS_LENGTH) != null) {
                    changes.add(Modification.onDeleted(res.getPath() + "/" + SlingPostConstants.NT_SLING_CHUNKS_LENGTH));
                    mvm.remove(SlingPostConstants.NT_SLING_CHUNKS_LENGTH);
                }
                removeChunkMixin(mvm);
            } finally {
                try {
                    fileIns.close();
                    file.delete();
                } catch (IOException ign) {
                }
            }
        } else {
            final Map<String, Object> props = new HashMap<>();
            props.put(JcrConstants.JCR_DATA, value.getInputStream());
            props.put(SlingPostConstants.NT_SLING_CHUNK_OFFSET, chunkOffset);
            props.put(SlingPostConstants.NT_SLING_CHUNKS_LENGTH, currentLength + value.getSize());
            for (final String key : props.keySet()) {
                changes.add(Modification.onModified(res.getPath() + "/" + nodeName + "/" + key));
            }
            props.put(ResourceResolver.PROPERTY_RESOURCE_TYPE, SlingPostConstants.NT_SLING_CHUNK_NODETYPE);
            final Resource rangeRsrc = res.getResourceResolver().create(res, nodeName, props);
            changes.add(Modification.onCreated(rangeRsrc.getPath()));
        }
    } catch (IOException e) {
        throw new PersistenceException("Error while retrieving inputstream from parameter value.", e);
    }
}
Also used : HashMap(java.util.HashMap) ByteArrayInputStream(java.io.ByteArrayInputStream) SequenceInputStream(java.io.SequenceInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Resource(org.apache.sling.api.resource.Resource) IOException(java.io.IOException) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) FileInputStream(java.io.FileInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) PersistenceException(org.apache.sling.api.resource.PersistenceException) File(java.io.File)

Example 94 with ModifiableValueMap

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

the class SlingFileUploadHandler method deleteChunks.

/**
     * Delete all chunks saved within a resource. If no chunks exist, it is no-op.
     */
public void deleteChunks(final Resource rsrc) throws PersistenceException {
    final Resource chunkParent = getChunkParent(rsrc);
    if (chunkParent != null) {
        for (final Resource c : new FilteringResourceIterator(rsrc.listChildren(), SlingPostConstants.CHUNK_NODE_NAME)) {
            c.getResourceResolver().delete(c);
        }
        final ModifiableValueMap vm = chunkParent.adaptTo(ModifiableValueMap.class);
        vm.remove(SlingPostConstants.NT_SLING_FILE_LENGTH);
        vm.remove(SlingPostConstants.NT_SLING_CHUNKS_LENGTH);
        removeChunkMixin(vm);
    }
}
Also used : Resource(org.apache.sling.api.resource.Resource) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap)

Example 95 with ModifiableValueMap

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

the class StreamedChunk method updateState.

/**
     * Update the state of the content resource to reflect a new body part being streamd.
     * @param contentResource the content resource
     * @param changes changes made.
     * @throws IllegalStateException if the contentResource is not consistent with the part being streamed.
     * @throws PersistenceException if the part cant be streamed.
     */
private void updateState(Resource contentResource, List<Modification> changes) throws IllegalStateException, PersistenceException {
    final ModifiableValueMap vm = contentResource.adaptTo(ModifiableValueMap.class);
    if (vm == null) {
        throw new PersistenceException("Resource at " + contentResource.getPath() + " is not modifiable.");
    }
    vm.put(JcrConstants.JCR_LASTMODIFIED, Calendar.getInstance());
    vm.put(JcrConstants.JCR_MIMETYPE, getContentType(part));
    if (chunked) {
        if (vm.containsKey(SLING_FILE_LENGTH)) {
            long previousFileLength = vm.get(SLING_FILE_LENGTH, Long.class);
            if (previousFileLength != fileLength) {
                throw new IllegalStateException("Chunk file length has changed while cunks were being uploaded expected " + previousFileLength + " chunk contained  " + fileLength);
            }
        }
        long previousChunksLength = 0;
        if (vm.containsKey(SLING_CHUNKS_LENGTH)) {
            previousChunksLength = vm.get(SLING_CHUNKS_LENGTH, Long.class);
            if (previousChunksLength != offset) {
                throw new IllegalStateException("Chunks recieved out of order, was expecting chunk starting at " + offset + " found last chunk ending at " + previousChunksLength);
            }
        }
        vm.put(SLING_CHUNKS_LENGTH, previousChunksLength + chunkLength);
        vm.put(JcrConstants.JCR_MIXINTYPES, SLING_CHUNK_MIXIN);
    } else {
        try {
            vm.put(JcrConstants.JCR_DATA, part.getInputStream());
        } catch (IOException e) {
            throw new PersistenceException("Error while retrieving inputstream from request part.", e);
        }
    }
}
Also used : PersistenceException(org.apache.sling.api.resource.PersistenceException) IOException(java.io.IOException) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap)

Aggregations

ModifiableValueMap (org.apache.sling.api.resource.ModifiableValueMap)111 Resource (org.apache.sling.api.resource.Resource)74 PersistenceException (org.apache.sling.api.resource.PersistenceException)32 Test (org.junit.Test)28 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)26 HashMap (java.util.HashMap)22 ValueMap (org.apache.sling.api.resource.ValueMap)22 Calendar (java.util.Calendar)13 LoginException (org.apache.sling.api.resource.LoginException)9 ChildResource (org.apache.sling.validation.model.ChildResource)9 Date (java.util.Date)8 HashSet (java.util.HashSet)8 Map (java.util.Map)8 NonExistingResource (org.apache.sling.api.resource.NonExistingResource)8 ByteArrayInputStream (java.io.ByteArrayInputStream)7 IOException (java.io.IOException)7 ValidationModel (org.apache.sling.validation.model.ValidationModel)7 InputStream (java.io.InputStream)6 Node (javax.jcr.Node)6 RepositoryException (javax.jcr.RepositoryException)6