Access JCR programatically
package com.aem.assets;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.Repository;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.Value;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import org.apache.jackrabbit.commons.JcrUtils;
public class ExtractMetadata {
public static void main(String[] args) throws Exception {
// Create a connection to the CQ repository running on local host
Repository 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
Node root = session.getRootNode();
// Obtain the query manager for the session ...
QueryManager queryManager = session.getWorkspace().getQueryManager();
//readAssetMetadata(root, "/content/dam/demo", queryManager);
//readPageData(root, "/content/we-retail/language-masters/en/about-us", queryManager);
//insertNode(root, "apps", "folder");
//deleteNode(root, "apps/folder");
//readProperties(root, "content/dam/demo/dog.jpg");
//addProperties(root, "apps/folder");
//readProperty(root, "apps/folder");
//readChildNodes(root, "content/dam/demo/");
//readFileData("c:/temp/samplefile2.html");
//readStylesData(root, "/apps/wknd", queryManager);
//readcomponentsData(root, "/apps/aem65", queryManager);
}
private static void readAssetMetadata(Node root, String nodePath, QueryManager queryManager) {
try {
String title = "dc:title", description = "dc:description", tags="cq:tags", jcrTitle= "jcr:title", jcrDesc = "jcr:description";
int flag;
//Create a object of BufferedWriter class and defining file path
BufferedWriter writer = new BufferedWriter(new FileWriter("c:/temp/AssetMetadata.csv"));
// Using AEM Query Manager API to query Nodes
String sqlStatement = "SELECT * FROM [nt:base] AS s WHERE ISDESCENDANTNODE([" + nodePath + "])";
Query query = queryManager.createQuery(sqlStatement, "JCR-SQL2");
// Execute the query and get the results ...
QueryResult result = query.execute();
// Iterate over the nodes in the results ...
NodeIterator nodeIter = result.getNodes();
writer.append("absTargetPath" + "," + "relSrcPath" + "," + "dc:title {{ String : multi }}" + "," + "dc:description {{ String : multi }}" + "," + "cq:tags {{ String : multi }}");
writer.newLine();
while (nodeIter.hasNext()) {
flag=1;
Node node1 = nodeIter.nextNode();
NodeIterator iter1 = node1.getNodes();
while (iter1.hasNext()) {
Node nextNode = iter1.nextNode();
String absPath = nextNode.getPath();
String modifiedPath = absPath.substring(1);
int index=absPath.lastIndexOf('/');
String targetPath = absPath.substring(0,index-12);
String sourcePath = targetPath.substring(targetPath.lastIndexOf("/") + 1);
// Code to read node properties
if (root.hasNode(modifiedPath)) {
Node node = root.getNode(modifiedPath);
PropertyIterator iter = node.getProperties();
while (iter.hasNext()) {
Property nextProp = iter.nextProperty();
String propertyName = nextProp.getName();
if(propertyName.equals(title) || propertyName.equals(jcrTitle) || propertyName.equals(jcrDesc) || propertyName.equals(description) || propertyName.equals(tags)) {
Property property = node.getProperty(propertyName);
if(flag == 1) {
writer.append(targetPath+","+"Assets/"+sourcePath+",");
flag=0;
}
if (!property.isMultiple()) {
String propertyValue = node.getProperty(propertyName).getString();
writer.append(propertyValue + ",");
} else {
Value[] value = nextProp.getValues();
for (int i = 0; i < value.length; i++) {
writer.append(value[i].getString() + ",");
}
}
}
} writer.newLine();
} else {
System.out.println("Warning! Can't READ properties as path doesn't exists");
}
}
}
System.out.println("csv file with assets metadata created successfully");
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void readPageData(Node root, String nodePath, QueryManager queryManager) {
try {
String fileReference = "fileReference", pageTitle = "jcr:title", panelTitle = "cq:panelTitle", elementNames = "elementNames", text = "text", description = "jcr:description", tags = "cq:tags";
//Create a object of BufferedWriter class and defining file path
BufferedWriter writer = new BufferedWriter(new FileWriter("c:/temp/siteProperties.csv"));
// Using AEM Query Manager API to query Nodes
String sqlStatement = "SELECT * FROM [nt:base] AS s WHERE ISDESCENDANTNODE([" + nodePath + "])";
Query query = queryManager.createQuery(sqlStatement, "JCR-SQL2");
// Execute the query and get the results ...
QueryResult result = query.execute();
// Iterate over the nodes in the results ...
NodeIterator nodeIter = result.getNodes();
while (nodeIter.hasNext()) {
Node node1 = nodeIter.nextNode();
NodeIterator iter1 = node1.getNodes();
while (iter1.hasNext()) {
Node nextNode = iter1.nextNode();
String absPath = nextNode.getPath();
String modifiedPath = absPath.substring(1);
String checkIfpagePath = modifiedPath.substring(modifiedPath.lastIndexOf("/")+1);
if(checkIfpagePath.equals("jcr:content")) {
writer.newLine();
writer.append(absPath);
writer.newLine();
writer.newLine();
}
// Code to read node properties
if (root.hasNode(modifiedPath)) {
Node node = root.getNode(modifiedPath);
PropertyIterator iter = node.getProperties();
while (iter.hasNext()) {
Property nextProp = iter.nextProperty();
String propertyName = nextProp.getName();
if (propertyName.equals(fileReference) || propertyName.equals(pageTitle) || propertyName.equals(panelTitle) || propertyName.equals(elementNames) || propertyName.equals(text) || propertyName.equals(description) || propertyName.equals(tags)){
writer.append(propertyName + ",");
Property property = node.getProperty(propertyName);
if (!property.isMultiple()) {
String propertyValue = node.getProperty(propertyName).getString();
if (propertyName.equals(fileReference)) {
String imgUrl = "http://localhost:4502" + propertyValue;
writer.append(imgUrl + ",");
writer.newLine();
} else {
writer.append(propertyValue + ",");
writer.newLine();
}
} else {
Value[] value = nextProp.getValues();
for (int i = 0; i < value.length; i++) {
writer.append(value[i].getString() + ",");
}
writer.newLine();
}
}
}
} else {
System.out.println("Warning! Can't READ properties as path doesn't exists");
}
}
}
System.out.print("Site content successfully extracted");
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void insertNode(Node root, String existingNodePath, String newNodeName) {
try {
if (root.hasNode(existingNodePath)) {
if (root.hasNode(existingNodePath + "/" + newNodeName)) {
System.out.println("Warning! Can't ADD new node as node with same name already exists");
} else {
Node node = root.getNode(existingNodePath);
node.addNode(newNodeName);
System.out.println("New Node Inserted as " + existingNodePath + "/" + newNodeName);
}
} else {
System.out.println("Warning! Can't ADD new node as node doesn't exists");
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void deleteNode(Node root, String deleteNodePath) {
try {
if (root.hasNode(deleteNodePath)) {
Node node = root.getNode(deleteNodePath);
node.remove();
System.out.println("Node " + deleteNodePath + " removed");
} else {
System.out.println("Warning! Can't DELETE as node doesn't exists");
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void readProperties(Node root, String nodePath) {
try {
if (root.hasNode(nodePath)) {
Node node = root.getNode(nodePath);
PropertyIterator iter = node.getProperties();
while (iter.hasNext()) {
Property nextProp = iter.nextProperty();
String propertyName = nextProp.getName();
System.out.print(propertyName + " : ");
Property property = node.getProperty(propertyName);
if (!property.isMultiple()) {
String propertyValue = node.getProperty(propertyName).getString();
System.out.println(propertyValue);
} else {
Value[] value = property.getValues();
int len = value.length;
for (int i = 0; i < len; i++)
System.out.println(value[i].getString());
}
}
} else {
System.out.println("Warning! Can't READ properties as path doesn't exists");
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void addProperties(Node root, String addPropNodePath) {
try {
if (root.hasNode(addPropNodePath)) {
Node node = root.getNode(addPropNodePath);
node.setProperty("jcr:data", 6269);
node.setProperty("jcr:mimeType", "image/png");
System.out.println("Properties added for node: " + addPropNodePath);
} else {
System.out.println("Warning! Can't ADD Properties as node doesn't exists");
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void readProperty(Node root, String readPropNodePath) {
try {
if (root.hasNode(readPropNodePath)) {
Node node = root.getNode(readPropNodePath);
System.out.println("jcr:created:::" + node.getProperty("jcr:created").getString());
} else {
System.out.println("Warning! Can't READ Properties as node doesn't exists");
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void readChildNodes(Node root, String nodePath) {
try {
if (root.hasNode(nodePath)) {
Node node = root.getNode(nodePath);
NodeIterator iter = node.getNodes();
while (iter.hasNext()) {
Node nextNode = iter.nextNode();
String absPath = nextNode.getPath();
System.out.println(absPath);
}
} else {
System.out.println("Warning! Can't READ child nodes as path doesn't exists");
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void checkResSupertype(Node root, String filePath, QueryManager queryManager) {
Node savedRootValue = root;
try {
String resSuperType = "sling:resourceSuperType";
PropertyIterator filePropIter;
String modifiedFilePath = filePath.substring(1);
if (root.hasNode(modifiedFilePath)) {
Node FilePathnode = root.getNode(modifiedFilePath);
filePropIter = FilePathnode.getProperties();
while (filePropIter.hasNext()) {
Property nextProp = filePropIter.nextProperty();
String propertyName = nextProp.getName();
if (propertyName.equals(resSuperType)) {
String propertyValue = FilePathnode.getProperty(propertyName).getString();
System.out.println(propertyValue);
String modifiedvalue = "/apps/" + propertyValue;
// read styles for component
readStylesData(savedRootValue, modifiedvalue, queryManager);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void readFileData(String fileName) throws IOException {
int ch;
FileReader fr = null;
try {
fr = new FileReader(fileName);
} catch (FileNotFoundException fe) {
System.out.println("File not found");
}
while ((ch = fr.read()) != -1)
System.out.print((char) ch);
fr.close();
}
// Reads clientLibs folder from CRX and store in css and js file at given path
private static void readStylesData(Node root, String filePath, QueryManager queryManager) {
try {
String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
// Creating a object of FileWriter class and defining file path
FileWriter cssFileWriter = new FileWriter("c:/temp/" + fileName + ".css");
FileWriter jsFileWriter = new FileWriter("c:/temp/" + fileName + ".js");
String sqlStatement = "SELECT * FROM [nt:base] AS s WHERE ISDESCENDANTNODE([" + filePath + "])";
Query query = queryManager.createQuery(sqlStatement, "JCR-SQL2");
// Execute the query and get the results ...
QueryResult result = query.execute();
// Iterate over the nodes in the results ...
NodeIterator nodeIter = result.getNodes();
String dataNode = "jcr:data";
while (nodeIter.hasNext()) {
Node node = nodeIter.nextNode();
NodeIterator iter = node.getNodes();
PropertyIterator propIter;
while (iter.hasNext()) {
Node nextNode = iter.nextNode();
String absPath = nextNode.getPath();
String modifiedPath = absPath.substring(1);
// Code to read node properties
if (root.hasNode(modifiedPath)) {
if (modifiedPath.contains(".css") || modifiedPath.contains(".less")) {
Node node1 = root.getNode(modifiedPath);
propIter = node1.getProperties();
while (propIter.hasNext()) {
Property nextProp = propIter.nextProperty();
String propertyName = nextProp.getName();
if (propertyName.equals(dataNode)) {
String propertyValue = node1.getProperty(propertyName).getString();
cssFileWriter.append(propertyValue);
// System.out.println(propertyValue);
}
}
}
if (modifiedPath.contains(".js")) {
Node node1 = root.getNode(modifiedPath);
propIter = node1.getProperties();
while (propIter.hasNext()) {
Property nextProp = propIter.nextProperty();
String propertyName = nextProp.getName();
if (propertyName.equals(dataNode)) {
String propertyValue = node1.getProperty(propertyName).getString();
jsFileWriter.append(propertyValue);
// System.out.println(propertyValue);
}
}
}
} else {
System.out.println("Warning! Can't READ properties as path doesn't exists");
}
}
}
cssFileWriter.close();
jsFileWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void readcomponentsData(Node root, String filePath, QueryManager queryManager) {
try {
String sqlStatement = "SELECT * FROM [nt:base] AS s WHERE ISDESCENDANTNODE([" + filePath + "])";
Query query = queryManager.createQuery(sqlStatement, "JCR-SQL2");
// Creating a object of FileWriter class and defining file path
FileWriter FileWriter = new FileWriter("c:/temp/comp.txt");
// Execute the query and get the results ...
QueryResult result = query.execute();
// Iterate over the nodes in the results ...
NodeIterator nodeIter = result.getNodes();
String resSuperType = "sling:resourceSuperType";
String primType = "jcr:primaryType";
int j = 1;
while (nodeIter.hasNext()) {
Node node = nodeIter.nextNode();
NodeIterator iter = node.getNodes();
PropertyIterator propIter;
while (iter.hasNext()) {
Node nextNode = iter.nextNode();
String absPath = nextNode.getPath();
String modifiedPath = absPath.substring(1);
// Code to read node properties
if (root.hasNode(modifiedPath)) {
Node node1 = root.getNode(modifiedPath);
propIter = node1.getProperties();
while (propIter.hasNext()) {
Property nextProp = propIter.nextProperty();
String propertyName = nextProp.getName();
if (propertyName.equals(primType)) {
String propertyValue = node1.getProperty(propertyName).getString();
if (propertyValue.equals("cq:Component")) {
j++;
}
} else if (propertyName.equals(resSuperType)) {
String propertyValue = "/apps/" + node1.getProperty(propertyName).getString();
System.out.println(propertyValue);
readStylesData(root, propertyValue, queryManager);
}
}
} else {
System.out.println("Warning! Can't READ properties as path doesn't exists");
}
}
}
System.out.println("Total components" + j);
FileWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}