Thursday, 28 January 2016

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. Only thing we have look out 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 is shown below.

Download the Jack Rabbit Jar File form 
and place the Jack Rabbit jar in build path of your project.

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


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.setProperty("name", "John Doe");
   coderMagnetNode.setProperty("email", "");
   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..!");



Data has been set..!