Expand my Community achievements bar.

Dive into Adobe Summit 2024! Explore curated list of AEM sessions & labs, register, connect with experts, ask questions, engage, and share insights. Don't miss the excitement.
SOLVED

CRUD operations for Nodes.

Avatar

Level 3

I need to create, update, delete nodes programmatically by adapting resource to a node. If anyone can provide any code samples for the same. 

1 Accepted Solution

Avatar

Correct answer by
Level 2

You need to adapt the resource to a Node.class

 

Node node = resource.adaptTo(Node.class);

 

to create a child node you can use the "addNode" methods which returns the new created node

 

Node childNode = node.addNode("newNode");

 

to read it from its parent you can do the following

 

Node childNode = node.getNode("newNode");

 

to update its properties you can use the methods "setProperty", but you can add or remove mixin types and more with other methods if I remember properly

 

Property property = childNode.setProperty("propertyName", "itsValue")

 

to remove a node (or a property) you can use the remove method of the superclass Item

 

childNode.getProperty("propertyName").remove();

childNode.remove();

 

https://developer.adobe.com/experience-manager/reference-materials/spec/jsr170/javadocs/jcr-2.0/java...

https://developer.adobe.com/experience-manager/reference-materials/spec/jsr170/javadocs/jcr-2.0/java...

 

The same operations, with the absolute paths can be done with the java.jcr.Session instance, which in any case it's necessary to commit or discard the changes. With the JCR API you have to use the save() and the refresh(boolean keepChanges) methods. 

 

https://developer.adobe.com/experience-manager/reference-materials/spec/jsr170/javadocs/jcr-2.0/java...()

 

View solution in original post

3 Replies

Avatar

Employee Advisor

Hi @Manasi29 ,

 

You can find that all operations are possible and are documented here :
https://sling.apache.org/apidocs/sling11/org/apache/sling/api/resource/ResourceResolver.html

 

You can also find some code examples in the below link for reference:

https://www.tabnine.com/code/java/classes/org.apache.sling.api.resource.ResourceResolver

 

Thanks,

Milind

Avatar

Employee Advisor

Sharing this piece of code associated with create operation -

 

 

/**
 * 
 */
package com.aem.demo.core.services.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;
import com.aem.demo.core.models.Employee;
import com.aem.demo.core.services.WriteEmployeeData;
import com.drew.lang.annotations.NotNull;
import com.drew.lang.annotations.Nullable;

/**
 * @author debal
 * 
 *         This implementation class is responsible to store Employee form data
 *         into AEM repository Employee information will be persisted in terms
 *         of node and property as user generated content
 */
@Component(service = WriteEmployeeData.class, immediate = true)
public class WriteEmployeeDataImpl implements WriteEmployeeData {

	private final Logger logger = LoggerFactory.getLogger(WriteEmployeeDataImpl.class);

	@Reference
	ResourceResolverFactory resourceResolverFactory;

	Map<String, Object> map = new HashMap<String, Object>();

	@Override
	public void storeEmployeeData(Employee employee) {

		String uniqueID = UUID.randomUUID().toString();
		ResourceResolver resourceResolver = getResourceResolver();
		@Nullable
		Resource resource = resourceResolver.getResource("/content/usergenerated/formdata");

		if (Objects.nonNull(resource)) {
			map.put("firstName", employee.getFirstName());
			map.put("lastName", employee.getLastName());
			map.put("designation", employee.getDesignation());
			try {
				@NotNull
				Resource employeeData = resourceResolver.create(resource, uniqueID, map);
				logger.info(" Resource Name {}", employeeData.getName());

				resourceResolver.commit();

			} catch (PersistenceException pe) {
				logger.error("Unable to save Employee details {} ", pe.getMessage());

			} finally {
				if (Objects.nonNull(resourceResolver)) {
					resourceResolver.close();
				}

			}

		}

	}

	private ResourceResolver getResourceResolver() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(resourceResolverFactory.SUBSERVICE, "readWriteService");
		ResourceResolver serviceResourceResolver = null;
		try {

			serviceResourceResolver = resourceResolverFactory.getServiceResourceResolver(map);
		} catch (LoginException e) {
			logger.error("Could not get service user [ {} ]", "demoSystemUser", e.getMessage());
		}
		return serviceResourceResolver;

	}

}

for delete operation you need to do -

resourceResolver.delete(Resource);

 

for update -

Resource myResource = resourceResolver.getResource("/myresource"); ModifiableValueMap properties = myResource.adaptTo(ModifiableValueMap.class); properties.put("title", {TITLE}); properties.put("body", {BODY}); resourceResolver.commit();

 

Important point: All changes are transient and require to commit them at the end.

Avatar

Correct answer by
Level 2

You need to adapt the resource to a Node.class

 

Node node = resource.adaptTo(Node.class);

 

to create a child node you can use the "addNode" methods which returns the new created node

 

Node childNode = node.addNode("newNode");

 

to read it from its parent you can do the following

 

Node childNode = node.getNode("newNode");

 

to update its properties you can use the methods "setProperty", but you can add or remove mixin types and more with other methods if I remember properly

 

Property property = childNode.setProperty("propertyName", "itsValue")

 

to remove a node (or a property) you can use the remove method of the superclass Item

 

childNode.getProperty("propertyName").remove();

childNode.remove();

 

https://developer.adobe.com/experience-manager/reference-materials/spec/jsr170/javadocs/jcr-2.0/java...

https://developer.adobe.com/experience-manager/reference-materials/spec/jsr170/javadocs/jcr-2.0/java...

 

The same operations, with the absolute paths can be done with the java.jcr.Session instance, which in any case it's necessary to commit or discard the changes. With the JCR API you have to use the save() and the refresh(boolean keepChanges) methods. 

 

https://developer.adobe.com/experience-manager/reference-materials/spec/jsr170/javadocs/jcr-2.0/java...()