Sunday, 21 December 2014

CQ/AEM node operations- add,delete,Recursively fetching the nodes



Delete a node

//Below code delete 'textRenderer' node if present under /content/projectname

private static final String TEXT_RENDERER_NODE_URL = "/content/projectname";
rendererNode = currentSession.getNode(TEXT_RENDERER_NODE_URL);
                                   
                                   
                                      if(rendererNode.hasNode("textRenderer"))
                                      {
                                          Node delNode = currentSession.getNode(TEXT_RENDERER_NODE_URL + "/textRenderer");
                                          delNode.remove();  
                                          currentSession.save();
                                      }
                               
Ensure to save the session after any node modification.

--------------Similar Posts:----------
-------------------------------------------

Add a node
//Below code adds 'textRenderer' node of type 'cq:Page' under /content/projectname

private static final String TEXT_RENDERER_NODE_URL = "/content/projectname";

Node fileNode = rendererNode.addNode("textRenderer", "cq:Page");
fileNode.addMixin("rep:AccessControllable");
currentSession.save();
                                   
                                   
                                    =======================================
                                   
Recursively fetching the nodes under CQ node

Below code recursively iterates over a root node and populate the node attributes.

// Node- the root node to be iterated
// Session - current session
 public static void visitRecursively(Node node, Session currentSession) {
                       
                                       
                    try{
                           
                       
                    // get all child nodes
                          NodeIterator list = node.getNodes();
                                
                          while(list.hasNext())   {
                          
                  // get child node
                            
                          Node childNode = list.nextNode();
                          // Verify child node for cqPage type
                          if((childNode.hasProperty("jcr:primaryType")) && (childNode.getProperty("jcr:primaryType").getValue().getString()).equals("cq:Page") ){
                           
                            Node jcrNode = childNode.getNode("jcr:content");
                             
                            // Iterate some of the page properties
                            String articleTitle="";String jcrDesc="";String jcrTitle="";String keywords="";
                            if(jcrNode.hasProperty("articleTitle")){
                               
                                articleTitle = jcrNode.getProperty("articleTitle").getString();
                                log.info("articleTitle--->"+articleTitle);
                            }
                            if(jcrNode.hasProperty("jcr:description")){
                               
                                jcrDesc = jcrNode.getProperty("jcr:description").getString();
                                log.info("jcr:description--->"+jcrDesc);
                            }
                            if(jcrNode.hasProperty("jcr:title")){
                               
                                jcrTitle = jcrNode.getProperty("jcr:title").getString();
                                log.info("jcr:title--->"+jcrTitle);
                            }
                            if(jcrNode.hasProperty("keywords")){
                               
                                keywords = jcrNode.getProperty("keywords").getString();
                                log.info("keywords--->"+keywords);
                            }
                            
                            String pagePropertiesString = "articleTitle--->"+articleTitle + "jcr:description--->"+jcrDesc+"jcr:title--->"+jcrTitle + "keywords--->"+keywords ;
                       
                       
                          log.info("Page Properties :---> Node "+ childNode.getName()+ "Properties : " + pagePropertiesString );
                         
                       
                          }
                            
                          visitRecursively(childNode,currentSession);
                          }
                          }
                          catch (RepositoryException rpe){
                              log.info("Exception in recursive listing:");
                          }
                                
                }

Creating file in CQ/AEM

Create a new file under jcr node

Some cases we need to create a text or xml file under jcr nodes in CQ. In below code we are creating a text file with current jcr node name under specified location

-------Similar Posts---------------
Mapping of requests in AEM
Interact With AEM
Run Modes
AEM
Apache Sling in AEM
-------------------------------------

private static final String TEXT_RENDERER_NODE_URL = "/content/projectname";
 try {

                                // writing to file in temp location
                                FileOutputStream fop = null;
                                File file = null;
                                File testFile = null;
                                StreamResult result = new StreamResult(new StringWriter());
                                try {

                                    Path filePath = Files.createTempFile("Test" , ".txt");
                                    file = filePath.toFile();
                                    fop = new FileOutputStream(file);
                                    // get the content in bytes
                                   
                                    byte[] contentInBytes = pagePropertiesString.getBytes();
                                    fop.write(contentInBytes);
                                    fop.flush();
                                    fop.close();
                                    testFile = file;
                                } catch (IOException ioExc) {
                                    log.error(
                                            "TestFile :: IOException: ",
                                            ioExc);
                                } finally {
                                    try {
                                        if (fop != null) {
                                            fop.close();
                                        }
                                    } catch (IOException ioExc) {
                                        log.error(
                                                "TestFile :: IOException while closing output stream :",
                                                ioExc);
                                    }
                                }
                                }catch (Exception exc) {
                                    log.error("TestFile Creation Failed :: Exception: " , exc);
                                }
                               
                               
                         //Create file under jcr node
                       
                          try{
                              FileInputStream fileInputStream = new FileInputStream(testFile);
                           
                            ValueFactory valueFactory = currentSession.getValueFactory();            
                            Binary contentValue;
                            contentValue = valueFactory.createBinary(fileInputStream);
                            Node textRendererNode = currentSession.getNode(TEXT_RENDERER_NODE_URL + "/textRenderer");
                            //We are creating a new text file based on current jcr node name after converting to lower case, '' to _
                            Node fileNode = textRendererNode.addNode(jcrTitle.replace(' ', '-').toLowerCase()+".txt", "nt:file");
                            Node actualNode = (childNode.getParent()).addNode(jcrTitle+".txt", "nt:file");
                            actualNode.addMixin("mix:referenceable");
                            fileNode.addMixin("mix:referenceable");
                            Node resNode = fileNode.addNode("jcr:content", "nt:resource");
                            resNode.setProperty("jcr:data", contentValue);
                            Calendar lastModified = Calendar.getInstance();
                            lastModified.setTimeInMillis(lastModified.getTimeInMillis());
                            resNode.setProperty("jcr:lastModified", lastModified);
                            currentSession.save();
                          }catch(RepositoryException rpe){
                            log.error("Exception in Text Renderer :"+rpe.getMessage());
                        } catch (FileNotFoundException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }  catch (Exception exc) {
                            // TODO Auto-generated catch block
                            exc.printStackTrace();
                        }

AEM/CQ Node change observer


Node Change Observer Code:
Some times we may have to observe changes in nodes.

Below code helps to observe any change in jcr nodes(Changes can be addition, deletion or modification). This helps us to observe and node for modification and process some tasks.

/** Class which observes an event at /jcr:system implementation
    *
    *
    */
  
    public class NodeObserver implements EventListener{
      
    private Logger log = LoggerFactory.getLogger(getClass());
      
        @Reference
        private SlingRepository repository;
      
        private Session session;
        private ObservationManager observationManager;
             
      
        protected void activate(ComponentContext context)  throws Exception {
            session = repository.loginAdministrative(null);
           // Listen for changes to our orders
            if (repository.getDescriptor(Repository.OPTION_OBSERVATION_SUPPORTED).equals("true")) {
                observationManager = session.getWorkspace().getObservationManager();
                //We are putting types of nodes to be observed under below string array: sample in next line
               // final String[] types = { "nt:unstructured","rep:system","rep:versionStorage","nt:frozenNode" };
               //I am just observing nt:unstructured, bcz that is my requirement
                final String[] types = { "nt:unstructured" };
                //I am observing changes under /jcr:system nodes
                final String path = "/jcr:system";
                observationManager.addEventListener(this, Event.NODE_ADDED, path, true, null, types, false);
                log.error("Observing node changes to {} nodes under {}", Arrays.asList(types), path);
            }
          
        }

        protected void deactivate(ComponentContext componentContext) throws RepositoryException {
  
            if (observationManager != null) {
                observationManager.removeEventListener(this);
            }
            if (session != null) {
                session.logout();
                session = null;
  
            }
        }
      

        public void onEvent(EventIterator itr) {
                      
            try {
                while (itr.hasNext()){
                  Node versionNode = null;
                
                  String eventPath = (itr.nextEvent()).getPath();
                  log.info("something has been added : {}", eventPath);
                
                  Node jcrContentNode = session.getNode(eventPath);
                
                  Node jcrParentNode =jcrContentNode.getParent();
                  //process nodes after checking conditions
                  if(eventPath.endsWith("jcr:content") && (null!= jcrParentNode) ){
                                  
                
                  String metaDataNodePath = eventPath + "/metadata";
                  Node metaDataNode = session.getNode(metaDataNodePath);
                  log.info("metaDataNode Created" + metaDataNode);
                
                  }
                //  break;

                }
               } catch(RepositoryException e){
               log.error("Error while processing events",e);
              }
          
        }
-------Similar Posts---------------
Mapping of requests in AEM
Interact With AEM
Run Modes
AEM
Apache Sling in AEM
-------------------------------------