Programmatically add node in AEM?
Asked Answered
S

2

7

I need to create a node in AEM using java services. I created a workflow, in which a process triggers a java service inside content/dam/Test.

Do I need to create a node using java services or simply create a node programatically?

Saccular answered 11/8, 2016 at 6:28 Comment(2)
AFAIK AEM uses JCR API, so it should be enough to read its Javadoc and apply.Eulalia
Possible duplicate of Saving Data in JCR Node, what am I doing wrong?Jimjimdandy
R
4

There are various APIs which can be used to create a node :
1. Using Node API

  • Adapt the resource to Node
    Node node = resource.adaptTo(Node.class);
  • then add a node using function "addNode(java.lang.String relPath, java.lang.String primaryNodeTypeName)"
    node.addNode(nodeName, NodePrimaryType);
  • you can add properties using function "setProperty(java.lang.String name,Value value)"
  • Save the session so that the new Node and its properties are saved

  1. Using JcrUtil
    There are 2 APIs for JCRUtil :

    • One of Apache Jackrabbit 2.0 - JcrUtils
    • And the other Utility for common JCR tasks - JcrUtil

You can go through any of them to create a new node.

Resurrectionism answered 26/8, 2016 at 5:19 Comment(0)
S
1

The workflow session can be adapted to a JCR session, from there you have access to read/write via the JCR API.

import com.adobe.granite.workflow.WorkflowException;
import com.adobe.granite.workflow.WorkflowSession;
import com.adobe.granite.workflow.exec.WorkItem;
import com.adobe.granite.workflow.exec.WorkflowProcess;
import com.adobe.granite.workflow.metadata.MetaDataMap;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.osgi.framework.Constants;

import javax.jcr.Node;
import javax.jcr.Session;

@Component
@Service
@Properties({@Property(name = Constants.SERVICE_DESCRIPTION, value = "Some Service")})
public class AddTheNodeWorkflow implements WorkflowProcess {

    @Override
    public final void execute(WorkItem workItem, WorkflowSession workflowSession, MetaDataMap args) throws WorkflowException {
        try {
            final String payloadPath = getPayloadPath(workItem);
            final Session session = workflowSession.adaptTo(Session.class);

            // get the node for the workflow payload
            final Node payloadNode = session.getNode(payloadPath);

            // add the node
            final Node somenode = payloadNode.addNode("somenode");
            somenode.setProperty("myproperty", "my property value");


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getPayloadPath(WorkItem workItem) {
        return workItem.getWorkflowData().getPayload().toString();
    }
}
Scanty answered 11/8, 2016 at 10:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.