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,---> 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 :)
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,
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"/>
<exampletext1jcr: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>
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,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 :)
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
<%@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
Subscribe to:
Posts (Atom)