You can access any JCR repository from a Java environment. This section explains how to set up your Java development environment and how to write a Java or a web application that connects to a remote repository.

Note

The examples connect to a CRX repository that is available for RMI on port 1099 (the default RMI port). Make sure that you have enabled RMI access to the repository.

If you need to access legacy repositories that have been created by application-specific mechanisms and proprietary APIs, you can access these repositories by using one of Day’s JCR connectors. For a list of available connectors, see www.day.com. To install connectors, see the documentation that came with your connector.

A Short Introduction to JCR Development

The Java Content Repository (JCR) framework lets you access content at the following levels:  

  • Repository: The entire CRX repository. A repository contains one or more workspaces.
  • Workspace: One data container in the repository. A workspace stores content as a hierarchy of nodes and properties.
  • Session: A session is a connection to a workspace by a user. Depending on the user access rights, a session can see part of or all of a workspace, and may have different access rights (read or write) for different parts of the workspace. Also, a session offers temporary storage, so you may modify items in a session, and then later save the modifications to the workspace.
  • Node: A node is a hierarchical entity in the workspace. Nodes can have different types, which you can define freely. Depending on the node type, a node may have required or optional sub-nodes and properties, or may freely allow any nodes and properties below it.
  • Property: A property is a content entity. Properties can store text data, numbers, dates and binary data. A property cannot have nodes and other properties below it.

For more information, read the JSR-283 specification

Connecting to a JCR Repository

There are different ways to access a JCR repository in a Java environment: via RMI, JNDI, WebDAV or via the JCA connector. Please refer to the section Accessing the CRX Repository to get more information on each method.

The following code connects to a JCR repository via RMI (see below for how to use the code in a Java application or in a Web application):

// RMI remoting access to a CRX server (with RMI enabled)
Repository repository = JcrUtils.getRepository("rmi://localhost:1099/crx");

Getting a JCR Session

When you log in to a workspace, you receive a session. The session is your copy of the workspace content, according to what you are allowed to see. The following code logs in to the default workspace, with the admin user and password:
SimpleCredentials creds = 
   new SimpleCredentials("admin", "admin".toCharArray());
Session session = null;
session = repository.login(creds, "crx.default");

Reading Workspace Content

The following code lists the contents of the current workspace. Use the following lines in your main code:
System.out.println("Workspace: " + 
   session.getWorkspace().getName() + "\n");
listChildren( "", session.getRootNode() );
The following method then lists the workspace content (as far as it is visible to the user who requested the session):
private static void listChildren(String indent, 
   Node node ) throws RepositoryException {
   System.out.println(indent + node.getName() ); 
   NodeIterator ni = node.getNodes();
   while(ni.hasNext()) {
      listChildren(indent+"  ", ni.nextNode());
   }
See the sections that follow for details on how to use this code in your Java application or Web application.

Writing a Java Application

This example shows you how to set up the Eclipse development environment, and how to write a Java application that lists the content of a workspace.
You can run the application from the command line or from the Eclipse development environment. Typically, the application runs once and then quits automatically. You can also run the application continuously until you quit it manually.
Java applications are easier to set up and require less overhead and infrastructure than Web applications, but they are more limited in their interactions, especially with Web users. Also, you can change code freely at any time, without having to restart the server or anything.

Creating the Project

To create a Hello World project in Eclipse, proceed as follows:  

1. In the File menu, point to New, and then click Project. The New Project Window opens.

2. Click Java Project, and then click Next.

3. In the Project name field, type the name of the project, for example Hello World. Click Next.

4. Click the Libraries tab, and then click Add External JARs. From the folder lib of your connector installation folder, add the libraries jcr-2.0.jar and crx-rmi-2.0.jar from the folder server/runtime/0/_crx/WEB-INF/lib of your CRX installation folder.

5. Click Finish. You have now created a new Java application project.

Creating the Hello World Class

To create a Hello World class, proceed as follows:  

1. Right-click the project you have created, point to New, and then click Class. The New Java Class window opens.

2. In the Name field, type the name of the class, for example HelloWorld.

3. Click Finish. Eclipse creates the new class for you and opens it in the edit window.

4. Paste the following code into the class:

public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World.");
}
}

Note

Note: To run the class, click the Run button (green, right arrow). To configure how Eclipse runs the class, click the Run menu, and then click Run.

Accessing the Repository

The following code logs in to the repository, fetches a session, and lists the repository content:
import javax.jcr.*;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import javax.naming.NamingException;
import org.apache.jackrabbit.rmi.client.ClientRepositoryFactory;
import org.apache.jackrabbit.commons.JcrUtils;

public class HelloWorld {

public static void main(String[] args) throws ClassCastException, MalformedURLException, RemoteException, NotBoundException, LoginException, NoSuchWorkspaceException, RepositoryException, NamingException {
System.out.println("Hello World.");
//RMI Connection
Repository repository = JcrUtils.getRepository("rmi://localhost:1099/crx");
//Workspace Login
SimpleCredentials creds = new SimpleCredentials("admin", "admin".toCharArray());
Session session = null;
session = repository.login(creds, "crx.default");
//List Children
System.out.println("Workspace: " + session.getWorkspace().getName() + "\n");
listChildren( "", session.getRootNode() );
}

private static void listChildren(String indent, Node node ) throws RepositoryException {
System.out.println(indent + node.getName() );
NodeIterator ni = node.getNodes();
while(ni.hasNext()) {
listChildren(indent+" ", ni.nextNode());
}
}
}

Writing a Web Application

This example shows you how to set up the Eclipse development environment so that you can develop a Java Web Application that connects to the repository. This example uses a Web application on a Tomcat server. For other servers, the steps may vary.

Creating the Folder Structure

The Web Application framework specifies the folder structure you have to use. For a Hello World Web application, you need the following folders and files:  

  1. In the folder webapps of your server, create a new folder named helloworld. This is your Web application folder.
  2. In your Web application folder, create a folder named WEB-INF.
  3. In the WEB-INF folder, create the folders src, lib, and classes. These folders store the source files, libraries and the compiled Java classes of the Web application, respectively.
  4. In the WEB-INF folder, create an empty text file named web.xml. This file contains the Web application configuration.

  The webapps folder now looks as follows:

webapps
   ROOT
   examples
   helloworld
      WEB-INF
         src
         classes
         lib
         web.xml

Adding the Libraries

You need the following libraries in your Web application:
jcr-2.0.jar The JCR API. This API lets you access data sources that adhere to the Java Content Repository standard, such as CRX.
crx-rmi-2.0.jar The library that lets you connect to CRX using an RMI connection.
The libraries are available in the CRX installation folder, in the folder server/lib. Copy them to the folder WEB-INF/lib of your Web application folder.

Registering the Web Application

web.xml

The file webapps/helloworld/WEB-INF/web.xml configures the Web application. For the Hello World example used in this section, configure it as follows:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<display-name>Hello World</display-name>
<servlet>
<servlet-name>HelloWorld</servlet-name>
<description>My Hello World Example</description>
<servlet-class>com.myCompany.helloWorld.HelloWorld</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>

Note that if you write your own Web application, the <servlet-class> element must point to the class you use. 
After you have made these changes, and before you access the Web application for the first time, you must restart CRX.

server.xml

The file conf/server.xml lists the Web applications that run on the server. To add your Web application, add a new Context section to the existing ones, as follows:
<!-- Hello World Context -->
<Context path="/helloworld" docBase="helloworld" />

Creating the Eclipse Project

To create an Eclipse project to develop your Web application, proceed as follows:  

  1. Start Eclipse and close all open projects.
  2. In the File menu, point to New, and then click Project. The New Project window opens.
  3. Click Java Project, and then click Next.
  4. In the Project Name field, type the name of your Web project for example, Hello World Web Application.
  5. In the Contents group, click Create project from existing source. Click Browse, and then select the folder of your Web application, for example the folder webapps/helloworld. Click Next. Eclipse configures the folders and libraries automatically, and opens the Java Settings window.
  6. In the field “Default output folder”, type Hello World Web Application/WEB-INF/classes. Eclipse compiles the Java classes into this folder.
  7. Click the Source tab. Right-click the folder src, and then click Use as Source Folder.
  8. Click the Libraries tab, and then click the Add External JARs button. You need to add the Servlet library. On a Tomcat server, the library is at common/lib/servlet.jar.
  9. Click Finish to create the project.

Connecting to the Virtual Machine

By default, Java loads the Web application when it starts, and does not update the classes while the Web application runs. To make changes effective, you need to either restart the Web application, or the server.
If you want to make changes effective immediately, you need to connect with Eclipse to the Virtual Machine. Java uses the term “debug” for this, because the connection allows you to debug and modify Java code on a running Virtual Machine.

Note

Note: Some changes require that you restart the Virtual Machine. In general, you can change code in a class or method, but you cannot add methods, or change the arguments that a method accepts.

Configuring the Virtual Machine

On the Virtual Machine, you need to allow debugging and specify a debugging method. Add the following parameter to the VM options, in front of the -jar option, to allow debugging on port 7403:
-Xdebug -Xnoagent Xrunjdwp:transport=dt_socket,address=7403,server=y,suspend=n
On Windows, use the manager application for this. On UNIX, you need to modify the start script.

Configuring Eclipse

In Eclipse, configure the debug connection as follows:  

  1. In the Run menu, click Debug. The Debug window opens.
  2. In the left list, click the Remote Java Application entry, and then click New to add a new debug connection.
  3. Next to the Project field, click Browse, and select the Hello World Web Application class.
  4. If the Virtual Machine runs on your own computer, leave the Host field to localhost. If you run the Virtual Machine on another computer, type the URL of the computer.
  5. In the Port field, type the port at which the Virtual Machine is open for debugging. This in the address value of the VM option you have configured above (for example, 7403).
  6. Click Debug to start the debug connection.

Note

Note: To see if a debug connection is active, click the Debug tab in the bottom right pane of Eclipse. If the connection is active, the tab lists all threads that currently run on the Virtual Machine.

Creating the Java Class

In the Web application framework, classes are stored in unique packages, starting with the reverse URL of your company. For example, if you work at a company with the Web site www.myCompany.com, and create a Hello World project, you may store the project in the package com.myCompany.helloWorld. Proceed as follows to create the HelloWorld class for your Web application:  

  1. Right-click the Hello World Web Application project, point to New and then click Class. The New Java Class window opens.
  2. In the Package field, type com.myCompany.helloWorld
  3. In the Name field, type HelloWorld
  4. Click OK. Eclipse creates a new class and opens it in the editor.

Writing a Hello World Web Application

In the Web application framework, the main Java class extends the HttpServlet class and provides the methods init and doGet to initialize the Web application and to handle requests, respectively.
The following code returns a Hello World message when a user accesses the Web application in a browser:
package com.myCompany.helloWorld;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet{

private static final long serialVersionUID = 7817938827440690167L;

public void init() throws ServletException {
super.init();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter();
out.write("Hello World");
}

}
To test the Web application, point your browser to the folder helloworld on your server. For a default installation on your local computer, the URL is http://localhost:8080/helloworld.

Note

If you encounter problems, restart CRX to make sure that the Web application is properly registered and configured on the server.

Accessing the Repository

The following code logs in to the repository, fetches a session, and lists the repository content:
package com.myCompany.helloWorld;

import java.io.IOException;
import java.io.PrintWriter;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.jackrabbit.rmi.client.ClientRepositoryFactory;
import org.apache.jackrabbit.commons.JcrUtils;

public class HelloWorld extends HttpServlet{

private static final long serialVersionUID = 7817938827440690167L;

public void init() throws ServletException {
super.init();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
//Hello World
PrintWriter out = response.getWriter();
out.write("Hello World");
out.write("\n\n");
out.flush();
//RMI Connection
Repository repository = JcrUtils.getRepository("rmi://localhost:1099/crx");
//Workspace Login
SimpleCredentials creds = new SimpleCredentials("admin", "admin".toCharArray());
Session session = null;
try {
session = repository.login(creds, "crx.default");
} catch (Exception e) {
e.printStackTrace(out);
throw new IOException (e.toString());
}
//Workspace Information
out.write("Workspace:\n");
try {
listChildren( "", session.getRootNode(), out );
} catch (Exception e) {
e.printStackTrace(out);
throw new IOException (e.toString());
}
out.flush();
}

private void listChildren(String indent, Node node, PrintWriter out) throws RepositoryException {
out.write(indent + node.getName() + "\n");
NodeIterator ni = node.getNodes();
while(ni.hasNext()) {
listChildren(indent+" ", ni.nextNode(), out);
}
}
}

Your comments are welcome!
Did you notice a way we could improve the documentation on this page? Is something unclear or insufficiently explained? Please leave your comments below and we will make the appropriate changes. Comments that have been addressed, by improving the documentation accordingly, will then be removed.

COMMENTS

  • By Anonymous - 6:31 PM on Mar 03, 2012   Reply
    is it not necessary to logout?
    • By alvawb - 5:02 PM on Apr 24, 2012   Reply
      Could you be more specific about when you think it's necessary to log out? I'm not sure at what point in the process you think you need to log out.
    • By Anonymous - 12:11 PM on May 30, 2012   Reply
      this displays the total content of all the nodes.
      How can it be modified to get the content of one particular node
      • By aheimoz - 6:42 AM on May 31, 2012   Reply
        We'd suggest that you post the details (exactly what you're trying to achieve, what you've done so far) to our dedicated forum:
        http://forums.adobe.com/community/adep
        Hope that helps.

      ADD A COMMENT

       

      In order to post a comment, you need to sign-in.

      Note: Customers with DayCare user accounts need to create a new account for use on day.com.

      ***