Thursday, 3 March 2016

Customize Left Navigation for Projects.html

Goal:

Add one more menu for the http://localhost:4502/projects.html



New in AEM(CQ) 6.1 is Sling Resource Merger. With resource merger you overlay the path in /apps and add only new nav items (in this case, Users)

1) Create the following folders in CRXDE Lite (http://localhost:4502/crx/de) or use the overlay creator servlet discussed here

            /apps/cq - nt:folder
            /apps/cq/core - nt:folder
            /apps/cq/core/content - sling:OrderedFolder
            /apps/cq/core/content/nav - nt:unstructured

  The structure above is an overlay of /libs/cq/core/content/nav

2) Create node /apps/cq/core/content/nav/onemkhomepage of type nt:unstructured with the following properties

             id - onemk-homepage-link
             href - /content/geometrixx-sightly/English.html
             jcr:description - Open Home Page
             jcr:title - OneMk HomePage

     All properties are self-explanatory. Property id is to uniquely identify the nav item.




Tuesday, 1 March 2016

How to Configure Stemming for AEM search

Stemming:


Decide the stemming strategy based on your use case. For mor info on strategies, please see this article.

It is highly recommend you use Porter Stemming because of its simplicity and flexibility. It usually is sufficient to yield the majority of stemming based search results.

Porter is a transforming algorithm for the English language that reduces any of the forms of a word such as "walks, walking, walked" or "teach, teaching" to their elemental roots "walk" and "teach".

Porter is based on rules and does not need a dictionary.

Go to the /oak:index/ntHierarchyNode/analyzers/default/filters path in the repository.

Create a node with these properties:
  • Name: PorterStem
  • Type: nt:unstructured
Finally, test stemming functionality by:

Typing the keyword "teach". You will get results for the term "teaching" as well.

For more info refer :



CQ User Creation Using UserManager API

Introduction:

Users:

Users will log in to AEM with their account. Each user account is unique and holds the basic account details, together with the privileges assigned.
Users are often members of Groups, which simplify the allocation of these permissions and/or privileges.

Groups:

Groups are collections of users and/or other groups; these are all called Members of a group.
Their primary purpose is to simplify the maintenance process by reducing the number of entities to be updated, as a change made to a group is applied to all members of the group. Groups often reflect:
  • a role within the application; such as someone who is allowed to surf the content, or someone who is allowed to contribute content.
  • your own organization; you may want to extend the roles to differentiate between contributors from different departments when they are restricted to different branches in the content tree.
Therefore groups tend to remain stable, whereas users come and go more frequently.
With planning and a clean structure, the use of groups can reflect your structure, giving you a clear overview and an efficient mechanism for updates.


User Creation Servlet:

Below Servlet creates user under specified paths and add them to specified group when you hit the servlet as 

http://localhost:4502/libs/cqusercreation?email=mani@gmail.com&firstName=firstName&lastName=lastName&givenName=givenName&displayName=displayName

with different parameters you can use these servlet in any async call to make a call from the component.

Servlet

package com.geometrixx.sightly.servlets;

import java.io.IOException;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.ServletException;

import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.User;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.jackrabbit.value.StringValue;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



@Component(immediate = true, description="User Creation")
@Service(value = javax.servlet.Servlet.class)
@Properties(value={
@Property(name="sling.servlet.extensions",value={"html","json"}),
@Property(name="sling.servlet.methods",value={"GET","POST"}),
@Property(name="sling.servlet.paths",value={"/libs/cqusercreation"})
})
public class CQUserCreationServlet extends SlingAllMethodsServlet {
private static final Logger Log = LoggerFactory
.getLogger(CQUserCreationServlet.class);
protected void doGet(final SlingHttpServletRequest req,
            final SlingHttpServletResponse resp) throws ServletException, IOException {
Log.debug("doGet");
        doPost(req, resp);
    }
protected void doPost(final SlingHttpServletRequest req,
            final SlingHttpServletResponse resp) throws ServletException, IOException {
Log.debug("doPost");
createNewCqUser(req,resp);
}
public void createNewCqUser(SlingHttpServletRequest req,
SlingHttpServletResponse resp) {
// TODO Auto-generated method stub
Log.debug("createNewCqUser");
Map<String, String> userProperties = new HashMap<String, String>();
String userEmailId = req.getParameter("email");
final String loginId= userEmailId;
String firstName = req.getParameter("firstName");
String lastName = req.getParameter("lastName");
String givenName = req.getParameter("givenName");
String displayName = req.getParameter("displayName");
userProperties.put("profile/email", userEmailId);
userProperties.put("profile/firstName", firstName);
userProperties.put("profile/lastName", lastName);
userProperties.put("profile/givenName", givenName);
userProperties.put("profile/displayName", displayName);
Log.debug("Map {}",userProperties );
Session session = req.getResourceResolver().adaptTo(Session.class);
Group userGroup;
Principal principal;
User newUser;
try {
UserManager userManager = ((JackrabbitSession) session)
.getUserManager();
Log.debug("userManager {}",userManager );
userGroup = (Group) userManager
.getAuthorizableByPath("/home/groups/e/everyone");
principal = new Principal() {
public String getName() {
return loginId;
}
};
newUser = userManager.createUser(loginId, "123456", principal,
"/home/users/geometrixx");
Log.debug("newUser {}",newUser );
if (null != newUser) {
updateAndInsertUserDetails(newUser, userProperties);
userGroup.addMember(newUser);
}
session.save();
}catch(Exception e){
}
}
public void updateAndInsertUserDetails(User user, Map<String, String> map)
throws RepositoryException {
for (Map.Entry<String, String> entry : map.entrySet()) {
setUserStringProperty(user, entry.getKey(), entry.getValue());
}
}
public void setUserStringProperty(User user, String property, String value) {
try {
if (isNotBlank(value)) {
user.setProperty(property, new StringValue(value));
}
} catch (RepositoryException e) {
}
}
public boolean isNotBlank(String value) {
return StringUtils.isNotBlank(value);
}
}


UserManager API Link:

Sunday, 28 February 2016

Sling Scheduler

What is a Scheduler?

Apache Sling Scheduler enables you to easily schedule jobs within your application. Jobs can be executed at a specific time, regularly at a given period or at the time given by a cron expression by leveraging the Sling scheduler service.

Scheduling in CQ uses the open source Quartz library, part Sling Commons:‘org.apache.sling.commons.scheduler.Scheduler’. It is used to execute jobs at predefined times either periodically or at a set time. It is based on the Quartz scheduling library and can therefore make use of its syntax for defining the execution times of jobs, making it possible to precisely indicate times .

Simple Scheduler which calls Rest API:

Below scheduler writes data into JSON file which is under var folder for every 5 minutes.

package com.geometrixx.sightly.Schedulers;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.HashMap;

import javax.jcr.Binary;
import javax.jcr.Node;
import javax.jcr.Session;
import javax.jcr.ValueFactory;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.commons.json.JSONObject;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.apache.sling.commons.scheduler.Scheduler;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@Component( metatype=true, immediate = true, label = "Gaurdian API Scheduler" )
@Properties({
@Property(label = "Scheduler Label", name = "scheduler.label", value = "News Scheduler"),
@Property(label = "Scheduler Name", name = "scheduler.name", value = "News Scheduler"),
@Property(label = "Article/Event xml Scheduler Expression", name = "gaurdian.scheduler.expression", value = "0 0 * * * ?")
})
public class GuardianAPIScheduler {

Logger  log = LoggerFactory.getLogger(this.getClass());

@Reference
    private Scheduler scheduler;

@Reference
private ResourceResolverFactory resourceResolverFactory;

protected void activate( ComponentContext ctx ) throws Exception {
final Runnable newsJob = new Runnable() {
            public void run() {
            try{
               log.debug("Executing My API Scheduler");
               GuardianAPIScheduler guardianAPIScheduler = new GuardianAPIScheduler();
               guardianAPIScheduler.generateJsonFile();
            }catch(Exception e){
            log.error("Error while getting data from Api");
            }
            }
        };
        try {        
        final String eventSchedulerExp = PropertiesUtil.toString(ctx.getProperties().get("gaurdian.scheduler.expression"), "0 0 * * * ?");
            this.scheduler.addJob("news-job", newsJob, new HashMap<String, Serializable>(), eventSchedulerExp, false);
            
        } catch (Exception e) {
        newsJob.run();
        }
}

protected void generateJsonFile() throws Exception{
// TODO Auto-generated method stub
HttpClient httpClient = new HttpClient();
        GetMethod post = new GetMethod("http://content.guardianapis.com/search?q=debates&api-key=test");
        int statusCode = httpClient.executeMethod(post);
        log.debug("Status Code {}",statusCode);
        String responseBody = post.getResponseBodyAsString();
        InputStream inputStream = new ByteArrayInputStream( responseBody.getBytes() );
        ResourceResolver resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(null);
        Session session = resourceResolver.adaptTo(Session.class);
        ValueFactory valueFactory = session.getValueFactory();
Binary contentValue = valueFactory.createBinary( inputStream );
Node varNode = JcrUtils.getOrAddNode(session.getRootNode(), "var", "sling:Folder");
Node reportNode = JcrUtils.getOrAddNode( varNode, "newsapi", "sling:Folder" );
Node reportFile = JcrUtils.getOrAddNode( reportNode, "newsapi.json" , "nt:file" );
Node jcrContentNode = JcrUtils.getOrAddNode( reportFile, "jcr:content", "nt:resource" );
jcrContentNode.setProperty( "jcr:mimeType", "application/json" );
jcrContentNode.setProperty( "jcr:data", contentValue );
log.debug("Reponse from API writing done {}",responseBody);
session.save();
}

}
  
Checking the scheduler status and other info can done under this path

http://localhost:4502/system/console/status-slingscheduler

Reference for Cron Expression:
http://www.docjar.com/docs/api/org/quartz/CronTrigger.html

Tuesday, 23 February 2016

Custom Event Listener In AEM

Introduction

You can develop a custom event handler for Adobe Experience Manager (AEM)

Listerner Class:

package com.geometrixx.sightly.Listeners;

import java.util.Arrays;

import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.observation.Event;
import javax.jcr.observation.EventIterator;
import javax.jcr.observation.EventListener;
import javax.jcr.observation.ObservationManager;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.day.cq.tagging.JcrTagManagerFactory;
import com.day.cq.tagging.Tag;
import com.day.cq.tagging.TagManager;



@Component
public class TagListener implements EventListener {

private final Logger LOGGER = LoggerFactory
.getLogger(TagListener.class);
private BundleContext bundleContext;
@Reference
    private ResourceResolverFactory resolverFactory;
private static final String NAMESPACE = "/etc/tags/mysample";
@Reference
    JcrTagManagerFactory tmf;
private Session session;
private ObservationManager observationManager;
public void run() {
LOGGER.info("Running...");
    }
protected void activate(ComponentContext ctx) {
        this.bundleContext = ctx.getBundleContext();
          
        try
        {
                     
            //Invoke the adaptTo method to create a Session 
             ResourceResolver resourceResolver = resolverFactory.getAdministrativeResourceResolver(null);
             session = resourceResolver.adaptTo(Session.class);
               
            // Setup the event handler to respond to a new claim under content/claim.... 
                
             
                 observationManager = session.getWorkspace().getObservationManager();
                final String[] types = { "cq:Page","nt:unstructured"};
                final String path = "/content"; // define the path
                observationManager.addEventListener(this, Event.NODE_ADDED, path, true,
        null, null, true);
                LOGGER.info("Observing property changes to {} nodes under {}", Arrays.asList(types), path);
                          
         }
        catch(Exception e)
        {
            LOGGER.error("unable to register session",e);
              
         }
        }
protected void deactivate(ComponentContext componentContext) throws RepositoryException {
        
        if(observationManager != null) {
            observationManager.removeEventListener(this);
        }
        if (session != null) {
            session.logout();
            session = null;
          }
    }
@Override
public void onEvent(EventIterator it) {
// TODO Auto-generated method stub
LOGGER.info("IN ONEVENT!");
        
        
        try {
            while (it.hasNext()) {
               //Custom Logic Goes Here.
  
                
            }
        }catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        }
 
}
    
}


Above class is sample Event Listener Class customize the business logic in OnEvent method which is overridden 

To get more info on Events properties please refer the documentation
https://www.day.com/maven/jsr170/javadocs/jcr-2.0/javax/jcr/observation/Event.html

To get adobe article on Event Listener refer the article

https://helpx.adobe.com/experience-manager/using/tagmanager.html

Article also describes more information about TagManager Class and to use it.

Thursday, 11 February 2016

Ajax Call in Sightly component

How to make an ajax call in sightly component ???

Steps:

Follow the below steps to make an ajax call to a servlet in sightly.

1.Create a sightly component(Lets say it is component.html)
2.Create a file with name js.html under the component.
3.Write the required ajax method to invoke the servlet.
4.Include js.html in component.html

Code:

Component.html:

Here is the ajax html file included

<div data-sly-include="js.html"></div>

Js.html:

<script>
function invokeajaxCall() {
    $.ajax({
             type: 'GET',    
             url:'/libs/migration',
             success: function(msg){
alert('Method Success');
             }
         });
    }
    $(window).load(function() {

        invokeajaxCall();
    });
</script>

Component Structure: