Search in sources :

Example 21 with ModifiableValueMap

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

the class ResourceBuilderImpl method resource.

@Override
public ResourceBuilder resource(String path, Map<String, Object> properties) {
    Resource r = null;
    final String parentPath;
    final String fullPath;
    boolean absolutePath = isAbsolutePath(path);
    if (absolutePath) {
        parentPath = ResourceUtil.getParent(path);
        fullPath = path;
    } else {
        checkRelativePath(path);
        parentPath = parentPath(path);
        fullPath = currentParent.getPath() + "/" + path;
    }
    final Resource myParent = ensureResourceExists(parentPath);
    try {
        r = currentParent.getResourceResolver().getResource(fullPath);
        if (r == null) {
            r = currentParent.getResourceResolver().create(myParent, ResourceUtil.getName(fullPath), properties);
        } else {
            // Resource exists, set our properties
            final ModifiableValueMap mvm = r.adaptTo(ModifiableValueMap.class);
            if (mvm == null) {
                throw new IllegalStateException("Cannot modify properties of " + r.getPath());
            }
            for (Map.Entry<String, Object> e : properties.entrySet()) {
                mvm.put(e.getKey(), e.getValue());
            }
        }
    } catch (PersistenceException pex) {
        throw new RuntimeException("PersistenceException while creating Resource " + fullPath, pex);
    }
    if (r == null) {
        throw new RuntimeException("Failed to get or create resource " + fullPath);
    } else if (hierarchyMode || absolutePath) {
        return cloneResourceBuilder(r, this.intermediatePrimaryType, true);
    }
    return this;
}
Also used : Resource(org.apache.sling.api.resource.Resource) PersistenceException(org.apache.sling.api.resource.PersistenceException) ValueMap(org.apache.sling.api.resource.ValueMap) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) Map(java.util.Map) HashMap(java.util.HashMap) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap)

Example 22 with ModifiableValueMap

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

the class ResourceValidationModelProviderImplTest method testGetValidationModelsWithoutApplicablePath.

@Test
public void testGetValidationModelsWithoutApplicablePath() throws Exception {
    modelBuilder = new ValidationModelBuilder();
    // build two models manually (which are identical except for the applicable path)
    ResourcePropertyBuilder resourcePropertyBuilder = new ResourcePropertyBuilder();
    ValidationModel model1 = modelBuilder.resourceProperty(resourcePropertyBuilder.build("property1")).build("sling/validation/test", libsValidatorsRoot.getPath() + "/testValidationModel1");
    // build models in JCR
    Resource modelResource = createValidationModelResource(rr, libsValidatorsRoot.getPath(), "testValidationModel1", model1);
    ModifiableValueMap properties = modelResource.adaptTo(ModifiableValueMap.class);
    properties.remove("applicablePaths");
    // check that both models are returned
    Collection<ValidationModel> models = modelProvider.getValidationModels("sling/validation/test");
    Assert.assertThat(models, Matchers.containsInAnyOrder(model1));
}
Also used : ValidationModel(org.apache.sling.validation.model.ValidationModel) Resource(org.apache.sling.api.resource.Resource) ChildResource(org.apache.sling.validation.model.ChildResource) ResourcePropertyBuilder(org.apache.sling.validation.impl.model.ResourcePropertyBuilder) ValidationModelBuilder(org.apache.sling.validation.impl.model.ValidationModelBuilder) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) Test(org.junit.Test)

Example 23 with ModifiableValueMap

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

the class ValidationServiceImplTest method testResourceWithPropertyPatternMatching.

@Test
public void testResourceWithPropertyPatternMatching() throws Exception {
    // accept any digits
    propertyBuilder.validator(REGEX_VALIDATOR_ID, 1, RegexValidator.REGEX_PARAM, "\\d");
    propertyBuilder.nameRegex("field.*");
    modelBuilder.resourceProperty(propertyBuilder.build("field"));
    propertyBuilder.nameRegex("otherfield.*");
    modelBuilder.resourceProperty(propertyBuilder.build("otherfield"));
    propertyBuilder.nameRegex("optionalfield.*").optional();
    modelBuilder.resourceProperty(propertyBuilder.build("optionalfield"));
    ValidationModel vm = modelBuilder.build("type", "some source");
    // create a resource
    ResourceResolver rr = context.resourceResolver();
    Resource testResource = ResourceUtil.getOrCreateResource(rr, "/content/validation/1/resource", JcrConstants.NT_UNSTRUCTURED, JcrConstants.NT_UNSTRUCTURED, true);
    ModifiableValueMap mvm = testResource.adaptTo(ModifiableValueMap.class);
    mvm.put("field1", "1");
    mvm.put("field2", "1");
    // does not validate
    mvm.put("field3", "abc");
    // otherfield.* property is missing
    ValidationResult vr = validationService.validate(testResource, vm);
    Assert.assertFalse("resource should have been considered invalid", vr.isValid());
    Assert.assertThat(vr.getFailures(), Matchers.<ValidationFailure>contains(new DefaultValidationFailure("field3", 1, defaultResourceBundle, RegexValidator.I18N_KEY_PATTERN_DOES_NOT_MATCH, "\\d"), new DefaultValidationFailure("", 20, defaultResourceBundle, ValidationServiceImpl.I18N_KEY_MISSING_REQUIRED_PROPERTY_MATCHING_PATTERN, "otherfield.*")));
}
Also used : ValidationModel(org.apache.sling.validation.model.ValidationModel) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) NonExistingResource(org.apache.sling.api.resource.NonExistingResource) Resource(org.apache.sling.api.resource.Resource) ChildResource(org.apache.sling.validation.model.ChildResource) SyntheticResource(org.apache.sling.api.resource.SyntheticResource) DefaultValidationFailure(org.apache.sling.validation.spi.support.DefaultValidationFailure) DefaultValidationResult(org.apache.sling.validation.spi.support.DefaultValidationResult) ValidationResult(org.apache.sling.validation.ValidationResult) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) Test(org.junit.Test)

Example 24 with ModifiableValueMap

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

the class SlingFileUploadHandler method setFile.

/**
     * Uses the file(s) in the request parameter for creation of new nodes.
     * if the parent node is a nt:folder a new nt:file is created. otherwise
     * just a nt:resource. if the <code>name</code> is '*', the filename of
     * the uploaded file is used.
     *
     * @param parent the parent node
     * @param prop the assembled property info
     * @throws PersistenceException if an error occurs
     */
private void setFile(final Resource parentResource, final RequestProperty prop, final RequestParameter value, final List<Modification> changes, String name, final String contentType) throws PersistenceException {
    // check type hint. if the type is ok and extends from nt:file,
    // create an nt:file with that type. if it's invalid, drop it and let
    // the parent node type decide.
    boolean createNtFile = parentResource.isResourceType(JcrConstants.NT_FOLDER) || this.jcrSupport.isNodeType(parentResource, JcrConstants.NT_FOLDER);
    String typeHint = prop.getTypeHint();
    if (typeHint != null) {
        Boolean isFileNodeType = this.jcrSupport.isFileNodeType(parentResource.getResourceResolver(), typeHint);
        if (isFileNodeType == null) {
            // assuming type not valid.
            createNtFile = false;
            typeHint = null;
        } else {
            createNtFile = isFileNodeType;
        }
    }
    // an nt:file, and an image name with an extension is probably "important"
    if (!createNtFile && name.indexOf('.') > 0) {
        createNtFile = true;
    }
    // set empty type
    if (typeHint == null) {
        typeHint = createNtFile ? JcrConstants.NT_FILE : JcrConstants.NT_RESOURCE;
    }
    // create nt:file resource if needed
    Resource resParent;
    if (createNtFile) {
        // create nt:file
        resParent = getOrCreateChildResource(parentResource, name, typeHint, changes);
        name = JcrConstants.JCR_CONTENT;
        typeHint = JcrConstants.NT_RESOURCE;
    } else {
        resParent = parentResource;
    }
    // create resource
    final Resource newResource = getOrCreateChildResource(resParent, name, typeHint, changes);
    final ModifiableValueMap mvm = newResource.adaptTo(ModifiableValueMap.class);
    // set properties
    mvm.put(JcrConstants.JCR_LASTMODIFIED, Calendar.getInstance());
    mvm.put(JcrConstants.JCR_MIMETYPE, contentType);
    changes.add(Modification.onModified(newResource.getPath() + "/" + JcrConstants.JCR_LASTMODIFIED));
    changes.add(Modification.onModified(newResource.getPath() + "/" + JcrConstants.JCR_MIMETYPE));
    try {
        // process chunk upload request separately
        if (prop.isChunkUpload()) {
            processChunk(resParent, newResource, prop, value, changes);
        } else {
            mvm.put(JcrConstants.JCR_DATA, value.getInputStream());
            changes.add(Modification.onModified(newResource.getPath() + "/" + JcrConstants.JCR_DATA));
        }
    } catch (IOException e) {
        throw new PersistenceException("Error while retrieving inputstream from parameter value.", e);
    }
}
Also used : Resource(org.apache.sling.api.resource.Resource) PersistenceException(org.apache.sling.api.resource.PersistenceException) IOException(java.io.IOException) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap)

Example 25 with ModifiableValueMap

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

the class AbstractNoSqlResourceProviderRootTest method testUpdateRootPath.

@Test
public void testUpdateRootPath() throws PersistenceException {
    Resource root = context.resourceResolver().getResource("/");
    ModifiableValueMap props = root.adaptTo(ModifiableValueMap.class);
    props.put("prop1", "value1");
    context.resourceResolver().commit();
    root = context.resourceResolver().getResource("/");
    assertThat(root.getValueMap().get("prop1", String.class), equalTo("value1"));
}
Also used : Resource(org.apache.sling.api.resource.Resource) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) Test(org.junit.Test)

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