Featured

Tuesday, 18 March 2014

How to call Servlet using ajax calling in cq5

Here is the sample ajax call to call a SlingServlet which is registered in cq.

---> Here we will get the values of below two textfields and pass to the servlet by using their 'id'.
---> After this you need to get the values in that appropriate servlet and apply your business logic.


<script>
$(document).ready(function() { 
$( ".perform" ).click(function() {
       var failure = function(err) {
             alert("Unable to retrive data "+err);
   };
 

  var val1=$('v1').val();
  var val2=$('v2').val();

    //Use JQuery AJAX request to post data to a Sling Servlet
    $.ajax({
         type: 'POST',  
         url:'/bin/imgcounter',

         data:{'value1' : val1,'value2' : val2},          //passing values to servlet
         success: function(msg){
            //Success logic here(The response from servlet)

         }
     });
    location.reload();
  });
    
});
</script>

 <form action="<%=currentPage.getPath()%>.html">
            Value1:<input type="text" id="v1"/>

            Value2:<input type="text" id="v2"/>
           <input type="submit" class="perform" value="Post to servlet!!!"/>
</form>



Thanks,

Hope it helps :) 
Thanks,
SonyCharan

Thursday, 6 March 2014

client side dialog validation in cq5

Here we will create a component which will have some basic fields. Lets say we will use two textfields and do validation on both of them.

Here the process follows,

1)Create dialog for the component as following,

<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
    jcr:primaryType="cq:Dialog"
    xtype="dialog">
    <items jcr:primaryType="cq:TabPanel">
        <items jcr:primaryType="cq:WidgetCollection">
            <validationtab
                jcr:primaryType="cq:Panel"
                title="Validation Example Tab">
                <items jcr:primaryType="cq:WidgetCollection">
                    <exampletext0
                            jcr:primaryType="cq:Widget"
                            fieldLabel="First TextField"
                            fieldDescription="First field Description"
                            name="./text0"
                            xtype="textfield"/>
                    <exampletext1
                            jcr:primaryType="cq:Widget"
                            fieldLabel="Second TextField"
                            fieldDescription="Second field Description"
                            name="./text1"
                            xtype="textfield"/>
</items> </validationtab> </items> </items> <listeners jcr:primaryType="nt:unstructured" beforesubmit="function(dialog) {return Example.checkFields(dialog);};"/> </jcr:root>
 
 
2) After creating the dialog we will create a js file to get the values from 
the dialog and make it vaid.

This js file we make include in our clientLibrary folder ,
by including such, we make it call on load.
Here we are getting the two textfield values which are in the dailog.
 
Example = function() {
        return {
        
        // Dialog field cross validation.
        checkFields : function(dialog,maxWidth,maxHeight) {
            
            var textfieldArray = dialog.findByType("textfield");
            var textfieldLength0 = textfieldArray[0].getValue().length;
            var textfieldLength1 = textfieldArray[1].getValue().length;
            
            if((textfieldLength0 > 0 && textfieldLength1 > 0) || 
               (textfieldLength0 == 0 && textfieldLength1 == 0)) {
                // Both fields have or do not have a value
                return true;
            } else {
                // Cross validation fails
                CQ.Notification.notify(CQ.I18n.getMessage("Validation Error"),
                CQ.I18n.getMessage("Both fields must be filled or left empty."));
                return false;  
            }
        }
    };
    
}();
 

Hope it helps you.
Comments are Welcome!!!!


Wednesday, 5 March 2014

How to get users members of a group in cq5

Here is the process for getting the members of a group.

As per my requirement i did this, U may change lot in this :)

<%--

  GroupUsersGettingBasedOnGroupId component.

  GroupUsersGettingBasedOnGroupId comp

--%><%
%><%@include file="/libs/foundation/global.jsp"%><%
%><%@page session="false" %>
<%@page contentType="text/html"
        pageEncoding="utf-8"
        import="com.day.text.Text,
                org.slf4j.Logger,org.slf4j.LoggerFactory,
                org.apache.jackrabbit.api.security.user.*,
                org.apache.sling.api.resource.ResourceResolver,
                javax.jcr.Session" %>
<%@taglib prefix="cq" uri="http://www.day.com/taglibs/cq/1.0" %><%
%><cq:defineObjects/>
<%!
    private final Logger log = LoggerFactory.getLogger(getClass());
%>

<%
 java.util.Iterator<Authorizable> users, groups ;
Object obj = null; User user = null;String id = null;int i=0;
String groupName="everyone";

    UserManager userManager = resourceResolver.adaptTo(UserManager.class);

try{
    final Group groupd = (Group) userManager.getAuthorizable(groupName);
     %><font color="orange"><%=groupd%><br/><%
  users = groupd.getMembers();

           while(users.hasNext()){
                            obj = users.next();
                                    if(!(obj instanceof User)){
                                         continue;
                                     }

                            user = (User)obj;
                            id = user.getID();
                           if(id.contains("@")){
                                       i++;
                             %><br/>User <%=i%>:<%=id%><%
                           }
           }
}catch(Exception e){
%><br/>Group "<%=groupName%>" Not Found<br/><%
}
%></font>
 

Thursday, 27 February 2014

How to send email notifications template in cq5

The process involves three steps.

We can send email template by using the workflow also. But this is the process without using the workflow.
For this,

1) We need to interact with the form, for the values which are required to pass to the mail template.
2)Sending the values to the servlet by using Ajax call
3)Interact with the servlet and inject values into mail template using the appropriate methods.



Here is the code for send an email template.

package com.test.mailtemp;

/*
*Author SONYC
*
*/
import java.util.HashMap;
import java.util.Map;
import java.io.*;
import java.util.ArrayList;
import javax.jcr.Node;
import javax.jcr.Session;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.servlet.ServletException;
import javax.servlet.Servlet;
import com.day.cq.commons.mail.MailTemplate;
import com.day.cq.mailer.MessageGateway;
import com.day.cq.mailer.MessageGatewayService;
import org.apache.commons.lang.text.StrLookup;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.felix.scr.annotations.*;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.jcr.api.SlingRepository;
import org.apache.sling.api.servlets.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings({"deprecation", "serial"})
@Component
@Service(Servlet.class)
@Properties(value = {
    @Property(name = "sling.servlet.paths", value = "/bin/emaitempcall.html")
})
public class mailtemp extends SlingAllMethodsServlet{ 
   
    private static final Logger log = LoggerFactory.getLogger(mailtemp.class);    
    ArrayList<InternetAddress> emailRecipients = new ArrayList<InternetAddress>();  
    @Reference
    private MessageGatewayService messageGatewayService;   
    @Reference
    private MessageGateway<HtmlEmail> messageGateway;   
    @Reference
    private ResourceResolverFactory serviceRef;

    private ResourceResolver resResolve = null;   
    String param1,param2=null;   
    private Session session;  

   
    @Reference
    public SlingRepository repository;
   
    @Override
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException,IOException {       
        init(request, response);
    }
   
    @Override
    protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException,IOException {       
        init(request, response);
    }
   
    @SuppressWarnings("static-access")
    private void init(SlingHttpServletRequest request, SlingHttpServletResponse response ){    
     
            //Additional code here regaring the value updation in repository/any functionality
     mailCall(param1, param2);         
    }   
    public void mailCall(String param1, String param2){      
        try{
        session = repository.loginAdministrative(null);
        Resource templateRsrc;
        HtmlEmail email = new HtmlEmail();
        String msg = "Hello, Our testing has completed here you got the mail !!!";

        Map<String, String> mailTokens = new HashMap<String, String>();
        mailTokens.put("subject", "Testing the mail template");
        mailTokens.put("param1", param1);
        mailTokens.put("param2", param2);
        mailTokens.put("thanks", "Thanks");
        mailTokens.put("author", "SONY C.");       
        mailTokens.put("message",msg);  
         
            templateRsrc = serviceRef.getAdministrativeResourceResolver(null).getResource("/etc/workflow/email");
            templateRsrc = templateRsrc.getChild("templatestructure.html");
            final MailTemplate mailTemplate = MailTemplate.create(templateRsrc.getPath(), session);
            String recipientName = "sonycharan004@gmail.com";
            String sendTo = "sonycharan004@gmail.com";
            String recName = "Sony C";
        
            mailTokens.put("contactName", "Dear "+recipientName);

            emailRecipients.add(new InternetAddress(sendTo) );
            email = mailTemplate.getEmail(StrLookup.mapLookup(mailTokens),HtmlEmail.class);
            email.setTo( emailRecipients );
        
            messageGateway = this.messageGatewayService.getGateway(HtmlEmail.class);
            messageGateway.send(email);
        
        }
        catch (AddressException e) {           
            e.printStackTrace();
        }catch (MessagingException e) {          
            e.printStackTrace();        
        } catch (EmailException e) {         
            e.printStackTrace();
        }
        catch(Exception e)  {
            e.printStackTrace();         
        }finally{
        session.logout();
        }
    }
   
}





II)As mentioned above we need to create a mai template in the path "/etc/workflow/email"  and under this create a file named "templatestructure.html"



Template Structure would be----

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title>Tempate Demo</title>
</head>
<body topmargin="0" bottommargin="0">

Dear  ${contactName},

Sub: ${subject},
${message}.
And your text will be  ${param1}, ${param2}.
Thanks for Using my blog!!! For further updates please be in touch with <a href="http://sonycharan.blogspot.in/">Sonycharan blogspot</a>.

Thanks,
${author}.

<p style="margin:10px 10px 10px 0; padding:0px; line-height:20px;"><font style="font-family:Arial;color:#fefeff;font-size:11px;">
© 2013 SonyBlog. All rights reserved.</font></p> 
</body>
</html>



Hope it helps :)
Thanks,
SonyCharan

Thursday, 13 February 2014

How to get node properties in jsp in cq5

Here is the procedure to get node properties in a jsp in cq5


<%@page session="false"%>
<%@ page import="java.util.Locale,
java.util.ResourceBundle,
javax.jcr.NodeIterator,
javax.jcr.Session,
javax.jcr.Node, javax.jcr.Value, javax.jcr.NodeIterator,
com.day.cq.commons.jcr.*" %>
<%@include file="/libs/foundation/global.jsp" %>

<%
javax.jcr.Session ses = resourceResolver.adaptTo(Session.class);
        //If you want to save anything to the node this session object (ses)is required.
String nodePath="/content/****";
Resource resources = slingRequest.getResourceResolver().getResource(nodePath);
         //Creating Node object using adaptTo mehtod.
Node rootNode = resources.adaptTo(Node.class);

*****Here is the node "rootnode", and now we can explore subnodes by using the root node and their propeties.

Comments are most welcome!!!
Thanks,
SonyCharan

Wednesday, 25 December 2013

Repository inconsistency issue in cq5



---------------------------------Unable to read Bundle ......-------------------------

If you are facing some problem related to this, then here is the solution.
----> This is because of abnormal closing of the instance or corrupted the indexes. Reindexing required for your instance.Some times because of failed to access the repository.
----> Building the indexes means it will fetch the data from the data tar file in the repository.

For this we need to delete the index files from the cq root folder..

Here specifying the folder paths, but make sure take backup of repository--<br/>
--The total process may takes hours of time depends on the repository size..But be ready to face downtime.

\author\crx-quickstart\repository\repository---delete index folder
\author\crx-quickstart\repository\tarJournal---delete all index_*.tar
\author\crx-quickstart\repository\version------delete all index_*.tar
\author\crx-quickstart\repository\workspaces\crx.default---delete index folder and delete all index_*.tar

Now Start your instance through the server.bat file
You will notice that the Multi-indexing will start........Each and every information will be available in logs.
After that please run these steps for better performance..

1)Tar optimization
2)Tar Index-merge
3)Data-store garbage collection

<br/>I tested and succeded with the cq 5.4 version..<br/>
Hope it useful..Please Dont try directly with production server..

Hope it helps :)
Thanks,
SonyCharan

Tuesday, 10 July 2012

How to get Repository access in cq5

@Reference private SlingRepository repository;
@SuppressWarnings("deprecation")
@Reference
private JcrResourceResolverFactory resolverFactory;

private ResourceResolver resolver;
private Session session;

session = repository.loginAdministrative(null);
resolver = this.resolverFactory.getResourceResolver(session);

From here you will get the root node whichever you wants---
rootNodePath="/content/dam";
Node rootNode = session.getNode(rootNodePath);

From this rootNode you can trace all the sub nodes...


Hope it helps :)
Thanks,
SonyCharan