May 10, 2020
Estimated Post Reading Time ~

Connect to the JCR repository using a simple Java main method.

When using Adobe Experience Manager (CQ) as our content management tool we sometimes need to connect to an AEM JCR repository from our integrated development environments (IDE) like Eclipse or NetBeans.

The following code shows a simple executable Java program for connecting to any AEM JCR Repository using a main() method. This can be used to connect to any remote or local JCR repository.

The Steps to do so are as follows:

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:
File: ConnectJCR.java

package net.codermag.jcr.test;

import javax.jcr.Node;
import javax.jcr.NodeIterator;
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 ConnectJCR {

 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()));
  //If you get javax.jcr.lock.LockException please use the line below
  //instead of the above one
  //Session session = repository.login( new SimpleCredentials("admin", "admin".toCharArray()),"crx.default");
  
  // Create a node that represents the root node
  Node root = session.getRootNode();
  Node content = root.getNode("content");
  Node subContent = content.getNode("dam");

  //Getting the iterator over the nodes
  NodeIterator childNodeIterator = subContent.getNodes();

  //Iterating over the nodes and printing their names
  while(childNodeIterator.hasNext()){
   Node childNode=(Node) childNodeIterator.next();
   System.out.println(childNode.getName());
   
  }
 }
}

javax.jcr.lock.LockException: Precondition Failed
If you are getting the javax.jcr.lock.LockException with the above program then please follow this link
http://www.codermag.net/2016/10/how-to-fix-javax-jcr-lock-lockexception-precondition-failed.html



By aem4beginner

No comments:

Post a Comment

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