Sunday, February 28, 2016


Sightly means "pleasing to the sight" ,so  it means to make the website pages more attractive with minimal effort. Sightly is introduced to replace JSP & ESP from AEM 6.0 and it is a new HTML template language. Sightly plays a very important role to define the output sent to the browser by specifying HTML itself with some basic presentation and variables to be evaluated at runtime.
In this article , the below topics on Sightly are explained
  •     Features of Sightly
  •     Sightly developing tools
  •     Block Statements in Sightly

Features of Sightly
     1. Light weight - No dependencies , fast and lean
     2. Secure - Automatic contextual XSS protection and URL externalization
     3. Code-less - Enforce separation of concerns between logic and markup
     4. Powerful - Straight-forward API for logic, allowing to do virtually anything
     5. Intuitive - Clear, simple & restricted feature set

Tools & Plugins
      1. Sightly Read Eval Print Loop(REPL) - Great tool to learn Sightly which is a live code editing environment. Click here to learn more.
      2. AEM Developer tools for Eclipse - It is Eclipse plugin used to develop Sightly projects more easily. Click here to learn more.
      3. AEM Brackets Extension - It provides an easy way to edit AEM components and Client Libraries and front-end developers can easily work with minimal AEM knowledge in projects.Click here to learn more.

Block Statements in Sightly
Block plugins in Sightly are defined by data-sly-* attributes set on HTML elements. 
All HTML elements can have a closing tag or self-closing like
<tag data-sly-BLOCK></tag>                                 
<!--/* A block is simply consists in a data-sly attribute set on an element. */-->

<tag data-sly-BLOCK/>                                      
<!--/* Empty elements (without a closing tag) should have the trailing slash. */-->
Attributes can have a value such as String , expressions or boolean
<tag data-sly-BLOCK="string value"/>                       
<!--/* A block statement usually has a value passed, but not necessarily. */-->

<tag data-sly-BLOCK="${expression}"/>                      
<!--/* The passed value can be an expression as well. */-->

<tag data-sly-BLOCK="${@ ArgVal='Sightly'}"/>                   
<!--/* Or a parametric expression with arguments. */-->

<tag data-sly-BLOCKONE="value" data-sly-BLOCKTWO="value"/> 
<!--/* Several block statements can be set on a same element. */-->
All evaluated data-sly-* attributes are removed from the generated markup.

Identifiers - data-sly-Block statements
Format : <tag data-sly-Block.identifier="value"></tag>
Examples :
<div data-sly-use.navigation="com.adobe.sightlyExample.MyNavigation">${navigation.title}         </div>
<!--/* MyNavigation is a java class and assigning it to navigation identifier */-->

<div data-sly-test.isEditMode="${wcmmode.edit}">${isEditMode}</div>
<!--/* wcmmode.edit expression's result is assigned to isEditMode identifier */-->

<div data-sly-list.child="${currentPage.listChildren}">${child.properties.jcr:title}</div>
<!--/* currentPage's child page items are assigned to child identifier */-->

<div data-sly-template.nav>Hello World</div>
<div data-sly-call="${nav}"></div>

<!--/* The attribute statement uses the identifier to know to which attribute it should apply it's value: */-->
<div data-sly-attribute.title="${properties.jcr:title}"></div> <!--/* This will create a title attribute */-->

So in next articles I will explain available data-sly-Block statements in Sightly like :
    • data-sly-test                      data-sly-text                       data-sly-use 
    • data-sly-attribute              data-sly-element                 data-sly-list 
    • data-sly-repeat                  data-sly-include                 data-sly-resource 
    • data-sly-template              data-sly-call                       data-sly-unwrap

Monday, February 1, 2016

Consuming Restful Webservice in AEM


In this article , I am going to write about how to consume data from a third-party Restful Webservice in Adobe Experience Manager. I am fetching live cricket score from  Cricinfo using their XML data with the help of org.apache.http package.
Steps to consume Restful web service - 
1.Create and Setup Maven project 
2.Create and compile Java classes that performs the Restful request. 
3.Build and deploy OSGi bundle to Adobe CQ
4.Create template and component to display web service response in webpage.

Create and Setup Maven Project

By performing below steps we can create an Adobe CQ archetype project
   i.Open cmd prompt and go to working project folder
  ii.Execute Maven script to create project folders

mvn archetype:generate -DarchetypeRepository=http://repo.adobe.com/nexus/content/groups/public/ -DarchetypeGroupId=com.day.jcr.vault -DarchetypeArtifactId=multimodule-content-package-archetype -DarchetypeVersion=1.0.2 -DgroupId=my-group-id -DartifactId=myproject -Dversion=1.0-SNAPSHOT -Dpackage=com.mycompany.myproject -DappsFolderName=myproject -DartifactName="My Project" -DcqVersion="5.6.1" -DpackageGroup="My Company"

mvn eclipse:eclipse
iii.After executing this script , we can import this project into Eclipse.

Create and Compile required Java files
Add the following Java files to the com.mycompany.myproject package:
  • A Java interface named Cricketscore.
  • A Java class named CricketscoreImpl that extends the Cricketscore interface under impl folder.

Cricketscore.java
package com.mycompany.myproject;
 
public interface Cricketscore {
     
    //Returns array data that represents the live score updates
 public String[] getLivescore();
   
}

CricketscoreImpl.java

In this development article , we used the Apache HttpClient library which simplifies handling HTTP request.

We can retrieve and send data via the HttpClient class.An instance of this class can be created with new DefaultHttpClient().The HttpClient uses a HttpUriRequest to send and receive data.Important subclass of HttpUriRequest are HttpGet and HttpPost. By using HttpGet, we are getting response from http://static.cricinfo.com/rss/livescores.xml

We can get the response of the HttpClient as an InputStream. So below lines of code used to get response from service and by using BufferedReader & InputStreamReader we are processing that response to get XML data as String.

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet getRequest = new HttpGet("http://static.cricinfo.com/rss/livescores.xml");
            getRequest.addHeader("accept", "application/xml");
            HttpResponse response = httpClient.execute(getRequest);
            if (response.getStatusLine().getStatusCode() != 200) {
                            throw new RuntimeException("Failed : HTTP error code : "
                                    + response.getStatusLine().getStatusCode());
            }
            BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
            String score;
            String xmldata="" ;
            while ((score= br.readLine()) != null) {
                    xmldata= myJSON + score;
                }
            httpClient.getConnectionManager().shutdown();

Then by using XML parser (javax.xml.parsers & org.xml.sax.InputSource) , we are going to parse response data and extract required node items . Store these data in String array then return it to Client viewer.


             DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
             DocumentBuilder db = dbf.newDocumentBuilder();
             InputSource is = new InputSource();
             is.setCharacterStream(new StringReader(xmldata));
             Document doc = db.parse(is);
             NodeList nodes = doc.getElementsByTagName("item");
             String[] titles = new String[nodes.getLength()];
                // iterate the nodes
             for (int i = 0; i < nodes.getLength(); i++) {
                   Element element = (Element) nodes.item(i);
                   NodeList name = element.getElementsByTagName("title");
                   Element titlexml = (Element) name.item(0);
                   title =getCharacterDataFromElement(titlexml);
                   titles[i]=title;
             }
             return titles;
Here is the all lines of code for CricketscoreImpl.java

package com.mycompany.myproject;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;
import javax.xml.parsers.*;
import org.xml.sax.InputSource;
import org.w3c.dom.*;
import java.io.*;
import java.util.*;
 
//This is a component so it can provide or consume services
@Component  
    
@Service
 
public class CricketscoreImpl implements Cricketscore {
 protected final Logger log = LoggerFactory.getLogger(this.getClass());
    @Override
    public String[] getLivescore() {
        // TODO Auto-generated method stub
         
        try
        {
        
         String title = "";
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet getRequest = new HttpGet("http://static.cricinfo.com/rss/livescores.xml");
            getRequest.addHeader("accept", "application/xml");
            HttpResponse response = httpClient.execute(getRequest);
            if (response.getStatusLine().getStatusCode() != 200) {
              throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String myXMLdata = "";
            String output;
            while ((output = br.readLine()) != null) {
             myXMLdata = myXMLdata + output;
            }
            httpClient.getConnectionManager().shutdown();
                        
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(myXMLdata));
            Document doc = db.parse(is);
            NodeList nodes = doc.getElementsByTagName("item");
            String[] titles = new String[nodes.getLength()];
            for (int i = 0; i < nodes.getLength(); i++)
            {
              Element element = (Element)nodes.item(i);
              NodeList name = element.getElementsByTagName("title");
              Element line = (Element)name.item(0);
              title = getCharacterDataFromElement(line);
              titles[i] = title;
            }
            return titles;
        }
        catch (Exception e)
        {
            e.printStackTrace() ; 
        }
        return null;
    }
    public static String getCharacterDataFromElement(Element e) {
        Node child = e.getFirstChild();
        if (child instanceof CharacterData) {
           CharacterData cd = (CharacterData) child;
           return cd.getData();
        }
        return "";
      }
  }


Next we need to add the Apache HttpComponents dependency in Maven POM file located at bundle folder in created project. So add below lines in POM.xml before end of  
</dependencies>.

<dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.1.1</version>
    </dependency>

Build and deploy the OSGi bundle using Maven 

Follow below steps to build the OSGi component,

i.Navigate to pom.xml located folder , then hold ctrl + shift then right-click to open cmd prompt from that folder
ii. Execute the maven command : mvn clean install
iii.After successful build, we can find OSGi bundle at (project folder)\bundle\target
iv.To deploy this bundle, open Apache Felix Console (http://server:port/system/console/bundles  )
v. In bundles tab, browse and install the created bundle under (project folder)\bundle\target
vi.After installing, reload and check bundle status must be Active. 

To display the webservice response , we need to follow below steps 

Open  (http://server:port/system/console/bundles  ) and create project as per below structure 

Create a template and Component

To display the component in page we need template, so first we will create a template  ,
1. Right-click the template folder within your application and select  Create -> Create Template and sling:resourceType to below created component path
2. Enter required information to create basic component and name the component as livescore 
3. Open livescore.jsp and paste below code to display Live Create Score

<@include file="/libs/foundation/global.jsp">
<cq:includeclientlib categories="jquerysamples"></cq:includeclientlib>
<html>
   <head>
         <!-- Below script used to reload page
            <script>
            $(document).ready(function(){
               setInterval(function(){cache_clear()},60000);
            });
            function cache_clear()
            {
              window.location.reload(true);
            }
         </script> -->

         <style>
            #page-wrap {
               width: 800px;
               margin: 0 auto;
               border: 3px solid #73AD21;
               padding: 10px;
               background-image:
                  linear-gradient(
                     to right, 
                     #0896A8,
                     #0896A8 15%,
                     #0896A8 15%,
                     #82C8D1 50%,
                     #82C8D1 50%
                  );
             }
         </style>
         <%
            com.mycompany.myproject.Cricketscore cs = sling.getService(com.mycompany.myproject.Cricketscore.class);
            String[] xmldata= cs.getLivescore() ; 
            request.setAttribute("xmldata", xmldata);
         %>
         <body>
           <div id="page-wrap">
              <h3>
Live Cricket Score Feed from CRICINFO</h3>
<hr />
              <c:foreach items="${xmldata}" var="xmldatascore">
                     <c:if test="${not empty xmldatascore}">
                        <strong><c:out value="${xmldatascore}"></c:out></strong><hr />
                     </c:if>
              </c:foreach>
           </div>
</body>
    </head>
</html>


In above code, i have added jquery to refresh the page for every 60 secs so include jquerysample Client libraries 

Create the web page to display Live Cricket Score from Cricinfo that based on the above created template.




Thursday, January 14, 2016

Integrate Google-Map API library with Adobe CQ



Nowadays most of the websites have "Find our store" section to provide easy way to locate branches near user. So, I decided to write an article on integrating Google-Map API in an Adobe CQ5 application.

This is a simple article on Google-Map API and about accessing store data from JSON. I have used JSON that has sample latitude & longitude details to mark in Map.

Steps:
1.    AEM application folder structure creation.
2.    Create a template on which the render component is based.
3.    Create a render component that uses the Google Map API.
4.    Create resource folder to place store location data JSON.
5.    Create a site that contains a page to display the map.

Create a project with the below folder structure.



Sample data from JSON file placed under resource folder - 'branch.json'.



Create a template and Google-Map component

To display the component in page we need template, so first we will create a template  ,
1. Right-click the template folder within your application and select  Create -> Create Template
2. Enter required information to create basic component and name the component as googlemap
    By using component dialog, we are getting width and height of the google map from author. This can be later modified to include more properties according to business requirements.


3. Open the googlemap.jsp located at
              :/apps/(application)/components/ googlemap/googlemap.jsp.
4. Declare google map api library in a js file in clientlibs and include it in googlemap.jsp  . Since this is a simple example I have just included it in the component jsp itself.





The above html code contains input elements to fetch zipcode and miles from the user. We have a div with id "googleMap" where we will be displaying the google map. Note that the width and height of the google map is fetched as CQ5 properties





Above jquery code gets data from JSON file, identify the stores which are nearest to user’s location and then mark these stores on the map. You can read more about using google map api here. When the page loads, the user's location is displayed, and when the user submits zipcode and miles, the nearest store location is shown on the map.




Saturday, December 19, 2015

Hide/Show parsys issue in Accordion/Tab Component


Whenever we have Accordion/Tab component in author mode, placeholder in each tab would not be aligned properly as the tabs are not active. So it confuses the author and difficult to edit the content inside each tab.

To set the visibility of the parent wrapper DIV of each parsys, setting it as hidden is not a solution. If we do so it only hides exact DIV, but other parsys artifacts would still be improperly aligned.

Therefore, we need to hide each CQ parsys artifacts when these are not active.

Use the below JavaScript spinet to fix this issue.

Steps:

1.       In Accordion.jsp ,  pass parsys path to JS function by
<div class="panel">
   <div class="panel-heading" role="tab" id="heading${i}">
          Tab Title
   </div>
   <div id="faq${i}" class="panel-collapse collapse ${in}" role="tabpanel" aria-labelledby="heading${i}" data-component-id="<%= currentNode.getPath() %>/accord${i}">
     <div class="panel-body">
<cq:include path="accord${i}" resourceType="foundation/components/parsys"/>               </div>
</div>


2.  In JS script, hide all parsys when page loads

<script>
      $(window).load(function(){
var elems = $('.panel-collapse.collapse:not(.in)');        $.each(elems,function(){
            var classNames = $(this).attr('class');
            var component = $(this).attr('data-component-id'); //Parsys Path
            var parsysComp = CQ.WCM.getEditable(component);
            if (parsysComp)
            {
                parsysComp.hide();
            }
        });
    });

Above JS function, hides all parsys when page loads so all the parsys would disappear except for the active tab which has CSS class "in".

3.  Hides the parsys when tabs are not active.

    $('#accordion').on('hide.bs.collapse', function (e) {
        var component = $(e.target).attr('data-component-id');
        var parsysComp = CQ.WCM.getEditable(component);
        if (parsysComp)
        {
            parsysComp.hide();
        }

    });
4. Shows the parsys when tabs are active.

    $('#accordion').on('show.bs.collapse', function (e) {
        var component = $(e.target).attr('data-component-id');
        var parsysComp = CQ.WCM.getEditable(component);
        if (parsysComp)
        {
            parsysComp.show();
        }
    });
</script>

Final Screen: