Monday, September 25, 2017

Read User details from AEM CRX repository


Using a query debug URL listing out the users and their groups names in a JSON format.

Query Builder Debugger tool link:
--------------------------------------------
http://localhost:4502/libs/cq/search/content/querydebug.html

query in tool:
-----------------
p.hits=selective
p.limit=-1
p.properties=rep:authorizableId rep:externalId
path=/home/users
type=rep:User
p.properties=jcr:path

User List with group name:
----------------------------------
users list in aem:-
http://localhost:4502/bin/querybuilder.json?property=jcr:primaryType&property.value=rep:User

groups list in aem:-
http://localhost:4502/bin/querybuilder.json?property=jcr:primaryType&property.value=rep:Group

Output will be based on params
http://localhost:4502/bin/querybuilder.json?property=jcr:primaryType&property.value=rep:User





Other related links:-
http://experience-aem.blogspot.com/2013/09/cq-users-groups-crx-rmi-sample.html
https://stackoverflow.com/questions/41774616/can-i-retrieve-the-users-list-and-along-with-their-group-names

Note:-
All users in LDAP are not imported into AEM/CRX.

Thursday, September 21, 2017

Read AEM DAM Asset rendition details on repository

Below is the AEM standalone application code to read dam asset rendition details from a AEM CRX repository


import java.io.File;
import java.io.PrintStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import javax.jcr.AccessDeniedException;
import javax.jcr.InvalidItemStateException;
import javax.jcr.ItemExistsException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.ReferentialIntegrityException;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.lock.LockException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NoSuchNodeTypeException;
import javax.jcr.version.VersionException;
import javax.servlet.http.HttpServlet;

import org.apache.felix.scr.annotations.Reference;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.log4j.Logger;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;

/**
 * Read DAM Asset information from AEM with in a complete folder structure
 * @author Sailaxman R
 *
 */
public class readDamAssetRenditions{
private static Logger LOG = Logger.getLogger(readDamAssetRenditions.class);
/**
* AEM SERVER DETAILS
*/
private static final String WORKSPACE     ="crx.default";
private static final String LOGIN_USRNAME ="admin";
private static final String LOGIN_PASWRD   ="admin";
private static final String SERVER_URL ="http://localhost:4502/crx/server";
/**
* DAM HIERARCHY - /content/dam/en, /content/dam/ca
*/
private static final String DAM_NODE_PATH     ="/content/dam/en";
/**
* NODE PROPERTIES
*/
private static final String IS_FOLDER   ="sling:OrderedFolder";
private static final String IS_ASSET   ="dam:Asset";
private static final String REPLICATION_STATUS ="cq:lastReplicationAction";
private static final String JCR_PRIMARYTYPE   ="jcr:primaryType";
private static final String JCR_LASTMODIFIEDDATE   ="jcr:lastModified";
private static final String JCR_CONTENT_SLASH ="/jcr:content";
private static final String ASSET_METADATA     ="/metadata";
private static final String ACTIVE_NODE     ="Activate";
private static final String DEACTIVE_NODE     ="Deactivate";
private static final String DAM_ASSET_SIZE     ="dam:size";
private static final String DAM_ASSET_RENDITIONS   ="/renditions";
/**
* JOB START & END TIME
*/
private static DateTimeFormatter dtformater = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
private static int ACT_COUNT =0;
private static int DEACT_COUNT =0;
public static List<Node> basefolderNodeLst = null;
private static float TOTAL_FILE_SIZE = 0;

@Reference
private static ResourceResolverFactory resourceResolverFactory;
private static ResourceResolver resResolver = null;
/**
*
* @param args
* @throws AccessDeniedException
* @throws ItemExistsException
* @throws ReferentialIntegrityException
* @throws ConstraintViolationException
* @throws InvalidItemStateException
* @throws VersionException
* @throws LockException
* @throws NoSuchNodeTypeException
* @throws RepositoryException
*/
public static void main(String[] args) throws AccessDeniedException,ItemExistsException, ReferentialIntegrityException,
ConstraintViolationException, InvalidItemStateException,VersionException, LockException, NoSuchNodeTypeException,
RepositoryException {
Node parentNode;
Session session = null;
long jobStartTime = System.currentTimeMillis();
basefolderNodeLst = new ArrayList<Node>();
try {
System.out.println("######   CONNECTING AEM SERVER    ######");
Repository repository = JcrUtils.getRepository(SERVER_URL);
session = repository.login(new SimpleCredentials(LOGIN_USRNAME, LOGIN_PASWRD.toCharArray()), WORKSPACE);
System.out.println("###### AEM CONNECTION SUCCESSFULL ######");
System.out.println("###### USER_ID connected : " + session.getUserID());
System.out.println("###### SESSION.GETREPOSITORY():"+session.getRepository());

parentNode = session.getNode(DAM_NODE_PATH);
if (parentNode.hasNodes()){
System.out.println("###### TRAVERSING PATH : "+DAM_NODE_PATH);
System.out.println("** Parent Node is: "+parentNode.getName()+"--- it has child nodes ***");
}
basefolderNodeLst.add(parentNode);

System.out.println("###### JOB STARTED ON :"+dtformater.format(LocalDateTime.now())); //2016/11/16 12:08:43
/**
* Traverse base folder nodes and folders under it
*/
getNodeHierarchyData(basefolderNodeLst,session);

basefolderNodeLst = null;
} catch (Exception exe) {
LOG.error("Exception while connecting AEMLogin :" + exe.getMessage());
}
long jobEndTime = System.currentTimeMillis();
System.out.println("###### JOB ENDED AT :"+dtformater.format(LocalDateTime.now()));
System.out.println("###### TOTAL TIME TAKEN FOR EXECUTION : " + (jobEndTime - jobStartTime) / 1000 + " SECONDS");
System.out.println("########################## FINISH #############################");
}

public static void getNodeHierarchyData(List<Node> folderNdList,Session session){
String nodeType =null;
NodeIterator nodeItr =null;
NodeIterator renditionNodeItr =null;

List<Node> currfolderNdsList = new ArrayList<Node>();
try{
for(int j=0;j<folderNdList.size();j++){
Node currentNode =folderNdList.get(j);
nodeItr = currentNode.getNodes();
while(nodeItr.hasNext()){
Node sbNode  =nodeItr.nextNode();
nodeType = sbNode.getProperty(JCR_PRIMARYTYPE).getString();

if(nodeType.equalsIgnoreCase(IS_FOLDER)){
/**
 * consolidate list of nodes which are folders
 * under base folder
 */
currfolderNdsList.add(sbNode);
}

if(nodeType.equalsIgnoreCase(IS_ASSET)){
//System.out.println(sbNode.getName()+" ---> is an ASSET");
String assetStr =sbNode.getPath()+JCR_CONTENT_SLASH + ASSET_METADATA;
Node assetNode = session.getNode(assetStr);
if(assetNode.hasProperty(DAM_ASSET_SIZE)){
long damAssetSize = assetNode.getProperty(DAM_ASSET_SIZE).getLong();
float fileSize = damAssetSize / 1024 ;
TOTAL_FILE_SIZE = TOTAL_FILE_SIZE + fileSize;
}
String renditionsStr =sbNode.getPath()+JCR_CONTENT_SLASH + DAM_ASSET_RENDITIONS;
Node renditionNode = session.getNode(renditionsStr);
renditionNodeItr = renditionNode.getNodes();
while(renditionNodeItr.hasNext()){
Node rendNode  =renditionNodeItr.nextNode();
String rendName = rendNode.getName();
System.out.println("RenditionName : "+rendName);
/**
* Read rendition details code here ,mean value on renditions
  */

}
}
}
/**
* if current folder has folders then traverse those, else stop job.
*/
if(currfolderNdsList.size() >0){
getNodeHierarchyData(currfolderNdsList,session);
}else{
return;
}
}catch (Exception exe) {
LOG.error("*** Exception while processing the node ***"+exe.getMessage());
}
}
}

AEM code to read dam content asset details from a CRX repository

Below is the AEM standalone application code to read dam content asset details from a AEM CRX repository

import java.io.File;
import java.io.PrintStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import javax.jcr.AccessDeniedException;
import javax.jcr.InvalidItemStateException;
import javax.jcr.ItemExistsException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.ReferentialIntegrityException;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.lock.LockException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NoSuchNodeTypeException;
import javax.jcr.version.VersionException;
import javax.servlet.http.HttpServlet;

import org.apache.felix.scr.annotations.Reference;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.log4j.Logger;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;

/**
 * Read DAM Asset information from AEM with in a complete folder structure
 * @author Sailaxman R
 *
 */
public class readDamAssetsInfo{
private static Logger LOG = Logger.getLogger(readDamAssetsInfo.class);
/**
* AEM SERVER DETAILS
*/
private static final String WORKSPACE     ="crx.default";
private static final String LOGIN_USRNAME ="admin";
private static final String LOGIN_PASWRD   ="admin";
private static final String SERVER_URL ="http://localhost:4502/crx/server";
/**
* DAM HIERARCHY - /content/dam/en, /content/dam/ca
*/
private static final String DAM_NODE_PATH     ="/content/dam/en";
/**
* NODE PROPERTIES
*/
private static final String IS_FOLDER   ="sling:OrderedFolder";
private static final String IS_ASSET   ="dam:Asset";
private static final String REPLICATION_STATUS ="cq:lastReplicationAction";
private static final String JCR_PRIMARYTYPE   ="jcr:primaryType";
private static final String JCR_LASTMODIFIEDDATE="jcr:lastModified";
private static final String JCR_CONTENT_SLASH ="/jcr:content";
private static final String ASSET_METADATA     ="/metadata";
private static final String ACTIVE_NODE     ="Activate";
private static final String DEACTIVE_NODE     ="Deactivate";
private static final String DAM_ASSET_SIZE     ="dam:size";
/**
* JOB START & END TIME
*/
private static DateTimeFormatter dtformater = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
private static int ACT_COUNT =0;
private static int DEACT_COUNT =0;
public static List<Node> basefolderNodeLst = null;
private static float TOTAL_FILE_SIZE = 0;

@Reference
private static ResourceResolverFactory resourceResolverFactory;
private static ResourceResolver resResolver = null;
/**
*
* @param args
* @throws AccessDeniedException
* @throws ItemExistsException
* @throws ReferentialIntegrityException
* @throws ConstraintViolationException
* @throws InvalidItemStateException
* @throws VersionException
* @throws LockException
* @throws NoSuchNodeTypeException
* @throws RepositoryException
*/
public static void main(String[] args) throws AccessDeniedException,ItemExistsException, ReferentialIntegrityException,
ConstraintViolationException, InvalidItemStateException,VersionException, LockException, NoSuchNodeTypeException,
RepositoryException {
Node parentNode;
Session session = null;
long jobStartTime = System.currentTimeMillis();
basefolderNodeLst = new ArrayList<Node>();
try {
System.out.println("######   CONNECTING AEM SERVER    ######");
Repository repository = JcrUtils.getRepository(SERVER_URL);
session = repository.login(new SimpleCredentials(LOGIN_USRNAME, LOGIN_PASWRD.toCharArray()), WORKSPACE);
System.out.println("###### AEM CONNECTION SUCCESSFULL ######");
System.out.println("###### USER_ID connected : " + session.getUserID());
System.out.println("###### SESSION.GETREPOSITORY():"+session.getRepository());

parentNode = session.getNode(DAM_NODE_PATH);
if (parentNode.hasNodes()){
System.out.println("###### TRAVERSING PATH : "+DAM_NODE_PATH);
System.out.println("** Parent Node is: "+parentNode.getName()+"--- it has child nodes ***");
}
basefolderNodeLst.add(parentNode);

System.out.println("###### JOB STARTED ON :"+dtformater.format(LocalDateTime.now())); //Date & time format to be : 2016/11/16 12:08:43
/**
* Traverse base folder nodes and folders under it
*/
getNodeHierarchyData(basefolderNodeLst,session);

basefolderNodeLst = null;
LOG.info("###### Total ASSETS SIZE in KB  ###### : "+TOTAL_FILE_SIZE);
LOG.info("###### Total ASSETS SIZE in MB  ###### : "+(TOTAL_FILE_SIZE/1024));
TOTAL_FILE_SIZE = 0;

} catch (Exception exe) {
LOG.error("Exception while connecting AEMLogin :" + exe.getMessage());
}
long jobEndTime = System.currentTimeMillis();
System.out.println("###### JOB ENDED AT :"+dtformater.format(LocalDateTime.now()));
System.out.println("###### TOTAL TIME TAKEN FOR EXECUTION : " + (jobEndTime - jobStartTime) / 1000 + " SECONDS");
System.out.println("########################## FINISH #############################");
}

public static void getNodeHierarchyData(List<Node> folderNdList,Session session){
String nodeType =null;
NodeIterator nodeItr =null;

List<Node> currfolderNdsList = new ArrayList<Node>();
try{
for(int j=0;j<folderNdList.size();j++){
Node currentNode =folderNdList.get(j);
nodeItr = currentNode.getNodes();
while(nodeItr.hasNext()){
Node sbNode  =nodeItr.nextNode();
nodeType = sbNode.getProperty(JCR_PRIMARYTYPE).getString();
System.out.println("Current NodePath :"+sbNode.getPath());

if(nodeType.equalsIgnoreCase(IS_FOLDER)){
/**
 * consolidate list of nodes which are folders
 * under base folder
 */
System.out.println(sbNode.getName()+" ---> is a FOLDER");
currfolderNdsList.add(sbNode);
}

if(nodeType.equalsIgnoreCase(IS_ASSET)){
System.out.println(sbNode.getName()+" ---> is an ASSET");
String assetStr =sbNode.getPath()+JCR_CONTENT_SLASH+ASSET_METADATA;
Node assetNode = session.getNode(assetStr);
if(assetNode.hasProperty(DAM_ASSET_SIZE)){
long damAssetSize = assetNode.getProperty(DAM_ASSET_SIZE).getLong();
float fileSize = damAssetSize / 1024 ;
TOTAL_FILE_SIZE = TOTAL_FILE_SIZE + fileSize;
System.out.println("DAM_ASSET_SIZE :"+fileSize+" KB");
}

/* if(assetNode.hasProperty(JCR_LASTMODIFIEDDATE)){
String jcrCreatedDate = assetNode.getProperty(JCR_LASTMODIFIEDDATE).getString();
System.out.println("JCRLastModifiedDate :"+jcrCreatedDate);
}
if(!assetNode.hasProperty(JCR_LASTMODIFIEDDATE)){
System.out.println("NO JCRLastModifiedDate for the Asset:");
}*/

/* if(assetNode.hasNode(assetStr) && assetNode.hasProperty(REPLICATION_STATUS)){
String replicationStatus = assetNode.getProperty(REPLICATION_STATUS).getString();
System.out.println("ReplicationStatus :"+replicationStatus);
if(replicationStatus!=null && replicationStatus.equalsIgnoreCase(ACTIVE_NODE)){
ACT_COUNT = ACT_COUNT+1;
}
if(replicationStatus!=null && replicationStatus.equalsIgnoreCase(DEACTIVE_NODE)){
DEACT_COUNT = DEACT_COUNT+1;
}
}*/
}
}
System.out.println("*** TRAVERSING OF NODE **** : "+currentNode.getName()+" ***COMPLETE***");
System.out.println("=================================================================================");
}
/**
* if current folder has folders then traverse those, else stop job.
*/
if(currfolderNdsList.size() >0){
getNodeHierarchyData(currfolderNdsList,session);
}else{
return;
}
}catch (Exception exe) {
LOG.error("*** Exception while processing the node ***"+exe.getMessage());
}
}
}

AEM code to read content page details from CRX repository

Below is the AEM standalone application code to read page content details from a AEM CRX repository

import java.io.File;
import java.io.PrintStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import javax.jcr.AccessDeniedException;
import javax.jcr.InvalidItemStateException;
import javax.jcr.ItemExistsException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.ReferentialIntegrityException;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.lock.LockException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NoSuchNodeTypeException;
import javax.jcr.version.VersionException;

import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.log4j.Logger;

/**
 * Read Pages information from AEM with in a hierarchy path
 * @author Sailaxman R
 *
 */
public class readPageContentsInfo{

private static Logger LOG = Logger.getLogger(readPageContentsInfo.class);
/**
* AEM SERVER DETAILS
*/
private static final String WORKSPACE     ="crx.default";
private static final String LOGIN_USRNAME   ="admin";
private static final String LOGIN_PASWRD     ="admin";
private static final String SERVER_URL ="http://localhost:4502/crx/server";
/**
* CONTENT HIERARCHY - /content/en, /content/ca
*/
private static final String CONTENT_NODE_PATH    ="/content/ca";
/**
* NODE PROPERTIES
*/
private static final String IS_PAGE   ="cq:Page";
private static final String IS_PAGE_CONTENT   ="cq:PageContent";
private static final String JCR_PRIMARYTYPE   ="jcr:primaryType";
private static final String JCR_LANGUAGE   ="jcr:language";
private static final String CQ_TEMPLATE   ="cq:template";
/**
* JOB START & END TIME
*/
private static DateTimeFormatter dtformater = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
public static List<Node> pageWithChildsLst = null;
private static long PAGE_COUNT = 0;
/**
*
* @param args
* @throws AccessDeniedException
* @throws ItemExistsException
* @throws ReferentialIntegrityException
* @throws ConstraintViolationException
* @throws InvalidItemStateException
* @throws VersionException
* @throws LockException
* @throws NoSuchNodeTypeException
* @throws RepositoryException
*/
public static void main(String[] args) throws AccessDeniedException,ItemExistsException, ReferentialIntegrityException,
ConstraintViolationException, InvalidItemStateException,VersionException, LockException, NoSuchNodeTypeException,
RepositoryException {
Node parentNode;
Session session = null;
long jobStartTime = System.currentTimeMillis();
pageWithChildsLst = new ArrayList<Node>();
try {
System.out.println("######   CONNECTING AEM SERVER    ######");
Repository repository = JcrUtils.getRepository(SERVER_URL);
session = repository.login(new SimpleCredentials(LOGIN_USRNAME, LOGIN_PASWRD.toCharArray()), WORKSPACE);
//session = slingRequest.getResourceResolver().adaptTo(Session.class);

System.out.println("###### AEM CONNECTION SUCCESSFULL ######");
System.out.println("###### USER_ID connected  : " + session.getUserID());
System.out.println("###### SESSION.GETREPOSITORY():"+session.getRepository());

parentNode = session.getNode(CONTENT_NODE_PATH);
if (parentNode.hasNodes()){
System.out.println("###### TRAVERSING PAGE_PATH : "+CONTENT_NODE_PATH);
pageWithChildsLst.add(parentNode);
}

System.out.println("###### JOB STARTED ON :"+dtformater.format(LocalDateTime.now())); // Date & Time Format : 2016/01/12:08:16 43
/**
* Traverse base nodes under it for child pages
*/
getNodeHierarchyData(pageWithChildsLst,session);

pageWithChildsLst = null;
System.out.println("TOTAL PAGES COUNT IS :"+PAGE_COUNT);
PAGE_COUNT = 0;
} catch (Exception exe) {
LOG.error("Exception while connecting AEMLogin :" + exe.getMessage());
}
long jobEndTime = System.currentTimeMillis();
System.out.println("###### JOB ENDED AT :"+dtformater.format(LocalDateTime.now()));
System.out.println("###### TOTAL TIME TAKEN FOR EXECUTION : " + (jobEndTime - jobStartTime) / 1000 + " SECONDS");
System.out.println("########################## FINISH #############################");
}

public static void getNodeHierarchyData(List<Node> parentPageNdList,Session session){
String nodeType =null;
NodeIterator nodeItr =null;
List<Node> currfolderNdsList = new ArrayList<Node>();
try{
for(int j=0;j<parentPageNdList.size();j++){
Node currentNode =parentPageNdList.get(j);
nodeItr = currentNode.getNodes();
System.out.println(" PagePath  :"+currentNode.getPath());
PAGE_COUNT = PAGE_COUNT +  1;
while(nodeItr.hasNext()){
Node sbNode  =nodeItr.nextNode();
nodeType = sbNode.getProperty(JCR_PRIMARYTYPE).getString();

if(nodeType.equalsIgnoreCase(IS_PAGE) || nodeType.equalsIgnoreCase(IS_PAGE_CONTENT)){
 if(nodeType.equalsIgnoreCase(IS_PAGE)){
/**
 * consolidating list of parent pages which have childs
 */
currfolderNdsList.add(sbNode);
 }

if(nodeType.equalsIgnoreCase(IS_PAGE_CONTENT)){
Node pageNode = session.getNode(sbNode.getPath());
if(pageNode.hasProperty(JCR_LANGUAGE) && pageNode.hasProperty(CQ_TEMPLATE)){
  }
}
   }
} // while loop end
}
/**
* if current page has sub-child pages then traverse those pages also, else terminate job.
*/
if(currfolderNdsList.size() >0){
getNodeHierarchyData(currfolderNdsList,session);
}else{
return;
}
}catch (Exception exe) {
LOG.error("*** Exception while processing the node ***"+exe.getMessage());
}
}
}

Connecting AEM server using standalone program code for CRX repository details

import java.io.File;
import java.io.PrintStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import javax.jcr.AccessDeniedException;
import javax.jcr.InvalidItemStateException;
import javax.jcr.ItemExistsException;
import javax.jcr.ReferentialIntegrityException;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.lock.LockException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NoSuchNodeTypeException;
import javax.jcr.version.VersionException;

import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.log4j.Logger;

/**
 * Connecting AEM server using below code
 * @author Sailaxman R
 *
 */
public class connectAEMServer{

private static Logger LOG = Logger.getLogger(connectAEMServer.class);
/**
* AEM SERVER DETAILS
*/
private static final String WORKSPACE     ="crx.default";
private static final String LOGIN_USRNAME ="admin";
private static final String LOGIN_PASWRD   ="admin";
private static final String SERVER_URL ="http://localhost:4502/crx/server";

System.out.println("######   CONNECTING AEM SERVER    ######");
Repository repository = JcrUtils.getRepository(SERVER_URL);
session = repository.login(new SimpleCredentials(LOGIN_USRNAME, LOGIN_PASWRD.toCharArray()), WORKSPACE);

System.out.println("###### AEM CONNECTION SUCCESSFULL ######");
System.out.println("###### USER_ID connected  : " + session.getUserID());
System.out.println("###### SESSION.GETREPOSITORY():"+session.getRepository());


}