This site contains the documentation that is relevant to older WSO2 product versions and offerings.
For the latest WSO2 documentation, visit https://wso2.com/documentation/.

Usages of JCR API

This page provides some samples which illustrate how to use WSO2 Governance Registry through JCR layer. Before directly going in to samples of using the JCR API, let's first take a look at how to make the connection with a remote Registry instance and access the JCR Registry Repository.

A user can simply login to a repository by passing some credentials. Then the repository returns a JCR session instance with a persistent workspace.

First of all, you have to set up a client to access and use the JCR API. In the Governance Registry distribution, you will find a sample jcr-client inside GREG_HOME/modules/samples.

The following steps will illustrate how to set up and run your client.

Pre-requirements

1. Before getting the sample to work, you have to run ant from GREG_HOME/bin. This copies all of the necessary libraries to their respective locations

2. Start the WSO2 Governance Registry by running the respective script (wso2server.sh or wso2server.bat) from GREG_HOME/bin.

Steps for running this sample

1. Execute the ant command (ant run) from the sample directory.

2. Run the SampleJCRRegistryClient.java which contains a main method and login to the Registry and see how we can access registry through JCR layer.

3. Login to the repository and get a session instance.

Session session = null;
 String username = "admin";
 String password = "admin";
 String serverURL = "https://localhost:9443/registry";
 Map<String,String> map = new HashMap<String,String>();
 map.put("registryURL",serverURL);
 map.put("userName",username);
 map.put("password",password);
 map.put("org.wso2.registry.jcr", "greg");
 try {
 RegistryRepositoryFactory rf = new RegistryRepositoryFactory();
 Repository repository = rf.getRepository(map);
 Credentials credentials = new SimpleCredentials("admin", new String("admin").toCharArray());
 session = repository.login(credentials);  // Returns a session instance
 Workspace workspace = session.getWorkspace(); // Can acquire the persistent workspace from the session instance
 } catch (RepositoryException e){
 // Handle the caught exception
 }

For all the following samples, we use the session instance which was acquired when during repository login as shown before.



Sample 1 - Basic JCR operations, adding and removing nodes

This sample shows how to add a node and remove any item (a node or a property) by using the session instance (acquired after repository login as shown above).

try {
Node rootNode = session.getRootNode().addNode("testroot"); // We can define a root

Node node1 = rootNode.addNode("node1"); // Directly add a node inside testroot

Node node2 = rootNode.addNode("node2", "mix:simpleVersionable") // Add a node by specifying its node type

// Removing an item from the current session. So if you want to remove a property, you can provide the absolute path of the property

session.removeItem(node1.getPath());

} catch(RepositoryException e) {
 // Handle the exception
}

Sample 2 - How to register a node type in JCR

This sample shows how we can register a node type in JCR. Each node in a workspace tree has a node type that defines the child nodes and properties it may (or must) have. There are two categories of node types, primary and mixin. Every node has a primary node type assigned to it upon creation (Node.addNode in the JCR API).

In addition, a mixin node type may be added to a node later in its lifecycle (Node.addMixin). The following code block shows how we can simply register our own custom JCR node type and use it later (for more information please refer to JCR API description or the spec).

try {
// Here you can acquire a node type manager from the workspace

NodeTypeManager ntm = session.getWorkspace().getNodeTypeManager();

// Create a node type template fro which you can define your attributes for that particular node type
NodeTypeTemplate ntTemplate = ntm.createNodeTypeTemplate();
// Setting the node type name
ntTemplate.setName("nt:myFavourites");
// Registering the node type
ntm.registerNodeType(ntTemplate, true);

} catch(RepositoryException e) {
 // Handle the exception
}

Sample 3 - Adding various types of properties to nodes and getting those nodes

Here, in this sample, we can see how to save our various types of resources inside JCR properties.

You can save many types of data inside properties such as String, int, Calendar, InputStream, boolean, long, double, javax.jcr.Value, etc.

Also you can directly acquire those types of properties by giving the exact absolute path (if you access it through a session), or you can simply ask the property by name directly from a particular node.

try {
// For a given node, we can set a property. In this case, a simple string property
Node homeFolder = session.getRootNode().addNode("homeFolder","nt:folder");
homeFolder.setProperty("stringProp1","value1");

// Also, we can set properties other than Strings. Following shows how to set a Calendar property

       Calendar cal = Calendar.getInstance();
       cal.setTimeInMillis(System.currentTimeMillis());
       Property prop2 =  session.getRootNode().getNode("homeFolder").setProperty("calendarProp", cal);

// You can call a "get" on a node to access these properties

Calendar calen1 = ((Node) session.getItem("/homeFolder")).getProperty("calendarProp").getDate();

} catch(RepositoryException e) {
 // Handle the exception
}

Sample 4 - Using ValueFactory to add several values to a property at once

This sample shows how to use ValueFactory when you have to store a set of values which may bound to a particular context. In such a case, you can set all those values under unique property name. Also, JCR provides the facility to iterate all the values directly at once.

try {
ValueFactory vf = session.getValueFactory();
 Value[] values = new Value[3];

       for (int i = 0; i < values.length; i++)  {   // Creates an array of Value instances
           values[i] = vf.createValue("Value" + i);
       }

session.getRootNode().getNode("homeFolder").setProperty("propValues", values);

// Also, you can simply do a "get" directly to iterate all these property values at once

PropertyIterator propItr = ((Node) session.getItem(homeFolder.getPath())).getProperties();


} catch(RepositoryException e) {
 // Handle the exception
}

Sample 5 - Using JCR versioning concept

In JCR, versioning is only valid for the nodes with the type ix:simpleVersionable. Here, we still support simple visioning in JCR.

try {
       VersionManager versionMgr = session.getWorkspace().getVersionManager();

       Node vn1 = rootNode.addNode("node3", "mix:simpleVersionable").addNode("node4", "mix:simpleVersionable");


       vn1.setProperty("prop1", "value1");

       Version v1 = versionMgr.checkin(rootNode.getPath() + "/node3/node4");  // Get a version before changing the value of "prop1".


  vn1.setProperty("prop1", "value2");

// We can ask a node to restore it to a particular version
  vn1.restore(v1, true);

// Following are two other ways of restoring to a version based on your occasion

// 1. We can ask version manager to restore a particular node

  // versionMgr.restore(vn1.getPath(),v1,true);

// 2. We can also add a label to a version and restore it by the label name, which seems pretty handy as follows

//  VersionHistory vh = versionMgr.getVersionHistory(vn1.getPath());
   //  vh.addVersionLabel(v1.getName(), "myFirstChange", true);
   //  versionMgr.restoreByLabel(vn1.getPath(), "myFirstChange", true);


} catch(RepositoryException e) {
 // Handle the exception
}

Sample 6 - Using JCR QOM (Query Object Model) for querying repository content

This shows a simple way of querying repository content in JCR. Here, other than typical SQL kind of querying, JCR also provides a Query Object Model (QOM) to deal with repository content. This is a very simple, user friendly and less complex way of dealing with our repository as this is an object model. So everything related to querying is handled by a QueryManager which can be acquired through the workspace.

try {
       QueryManager qm = workspace.getQueryManager();
       QueryObjectModelFactory qf = qm.getQOMFactory();

       String nodeName1 = "nodeName1";
       String nodeName2 = "nodeName2";

       String testNodeType = "nt:myFavourites";

       String propertyName1 = "property1";
       String propertyName2 = "property2";

       Node n1 = rootNode.addNode(nodeName1, testNodeType);
       n1.setProperty(propertyName1, "foo");
       Node n2 = rootNode.addNode(nodeName2, testNodeType);

       n2.setProperty(propertyName2, "bar");
       session.save();

// To create a query, we need to specify a selector, a source and constraints such as “and”, “or”,  “descendentNode”, etc.

       QueryObjectModel qom = qf.createQuery(
               qf.selector("nt:myFavourites", "s"),
               qf.and(
                       qf.descendantNode("s", root_node.getPath()),
                       qf.or(
                               qf.propertyExistence("s", propertyName1),
                               qf.propertyExistence("s", propertyName2)
                       )
               ),
               null,
               null
       );

       QueryResult result = qom.execute();
// This result contains all nodes queried from the above query

} catch(RepositoryException e) {
 // Handle the exception
}