May 10, 2020
Estimated Post Reading Time ~

Storing data in AEM JCR

Store data in remote AEM JCR repository.
We can store data in the AEM's data repository i.e. the JCR repository very easily as shown below in the code sample. The only thing we have a lookout for is the username and the password we are using to access the repository.
Sometimes we do not have permission for writing to the JCR in those cases this will not work.
Here I am using the "Administrator" login for writing data into the AEM JCR.

Please make necessary changes to the port and the host URL as required.

This creates a node in AEM under the "content" folder as shown here.



The properties that will be set are shown below.


Step1: Download the Jack Rabbit Jar File form 
http://www.apache.org/dyn/closer.cgi/jackrabbit/2.8.1/jackrabbit-standalone-2.8.1.jar and place the Jack Rabbit jar in the build path of your project.

Step 2: Create and execute a class as shown below.

File: StoreData.java
package net.codermag.jcr.test;

import javax.jcr.Node;
import javax.jcr.Repository;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;

import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.jackrabbit.core.TransientRepository;

public class StoreData {

 public static void main(String[] args) throws Exception {
  
  Repository repository = new TransientRepository();
  repository = JcrUtils.getRepository("http://localhost:4502/crx/server");

  // Create a Session
  Session session = repository.login(new SimpleCredentials("admin","admin".toCharArray()));

  // Create a node that represents the root node. For this, you need root permission.
  Node root = session.getRootNode();

  // Getting the content node (This can be any node like etc/bin....)
  Node contentNode = root.getNode("content");

  if (contentNode.hasNode("codermagnet")) {

   Node coderMagnetNode = contentNode.getNode("codermagnet");
   
   //Setting the primary type. This can be any of the primary properties that AEM supports
   coderMagnetNode.setPrimaryType("nt:unstructured");

   coderMagnetNode.setProperty("name", "John Doe");
   coderMagnetNode.setProperty("email", "John@mail.com");
   coderMagnetNode.setProperty("isEmployed", true);
   coderMagnetNode.setProperty("roles", new String[] { "Manager","Admin", "Developer" });

   System.out.println("Data has been set..!");

  } else {
   System.out.println("Node Not Found..!");
  }
  session.save();
 }
}

Output:
Data has been set..!


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.