Arti­cle updat­ed on May 24, 2017.

In this blog post, I want to show you some code around a new way you can change resources via the ResourceRe­solver.

This arti­cle is the con­tin­u­a­tion of my post about the Val­ueMap and his friends.

In the new AEM ResourceRe­solver there are meth­ods avail­able to create/update/delete your Resources.

This is now quite a straight­for­ward way, I will demon­strate this via some basic code sam­ples.

Changing a resource

Here a code sam­ple how to add / change a prop­er­ty on an exist­ing resource. Via the Mod­i­fi­abl­e­Val­ueMap you can mod­i­fy the prop­er­ties.

ResourceResolver resourceResolver = getResourceResolver();
Resource resource = getSlingRequest().getResource();

ModifiableValueMap mvp = resource.adaptTo(ModifiableValueMap.class);

// adding and changing a property
if (mvp.containsKey("test")) {
    String propValue = mvp.get("test", String.class);
    mvp.put("test", propValue + "1");
} else {
    mvp.put("test", "test");
}

Create / Delete a resource

Via the meth­ods cre­ate() / delete() you can cre­ate and delete a new resource.

ResourceResolver resourceResolver = getResourceResolver();
Resource resource = getSlingRequest().getResource();

// adding and removing a child node
if (resource.getChild("person") == null) {
    Map props = new HashMap();
    props.put("firstname", "feike");
    props.put("lastname", "visser");

    Resource newResource = resourceResolver.create(resource, "person", props);
} else {
    resourceResolver.delete(resource.getChild("person"));
}

Saving / Reverting changes

Via the meth­ods .com­mit() and .revert() you can either save or roll­back the changes.

if (resourceResolver.hasChanges()) {
    resourceResolver.commit();
}

@heervisscher

1 comments
Kelly Almon
Kelly Almon

This is an interesting topic. I think it should be said that customer expectations may have changed - but only to match their desires. Whereas before customers didn't see the alternatives available to the fee-laden, single channel, bank-driven communication, they now see how other industries are engaging with their customers in more meaningful ways and are asking why financial services aren't doing so as well. I definitely agree with your last paragraph - imperative is the right word. Financial services is incredibly important on a very personal level, so why are financial organizations not engaging with their customers on a personal level, through the individual's choice of channels.