Tuesday, October 11, 2016

OSGI FRAMEWORK

OSGI and Apache Sling:
OSGI:

  • Osgi is a dynamic module system for the Java that provides within which small, reusable,     standardized components  composed into an application and deployed.
  • Complete understanding of the OSGI design patterns can be seen here: http://www.computepatterns.com/osgi-design-patterns/ 

Apache Sling:

  • It is designed to expose the JCR  through an HTTP based REST API.
  • AEM's native functionality and functionality of any website built with AEM are delivered through this framework.
OSGI module system allows to building applications as a set of reloadable and strongly encapsulated services.
OSGI bundles run inside OSGI container. This container manages relations among bundles, which are JAR files that contain extra metadata indicating what services they require and which they provide.

OSGI Specifications enable:
  • Modularization by use of a development model where applications are (dynamically) composed of many different(reusable) components.
  • Components to hide their implementations from other components while communicating through services, which are objects specifically shared between components. 
OSGI Services:

http://www.knopflerfish.org/osgi_service_tutorial.html 


                                                                                                      (To be Updated...)
Citations:

http://www.aemcq5tutorials.com/tutorials/aem-osgi-configuration-implementation/
SCR Annotations:
http://felix.apache.org/documentation/subprojects/apache-felix-maven-scr-plugin/scr-annotations.html

AEM interview questions that I can think of(We will keep on updating)


  1.  What are the basic differences between Overlays and Sling Resource Merger?                             
  2.     What are the two locations where we can find the foundation components starting from                6.0?
               libs/foundation/components:  All components using jsp are available here.
               libs/wcm/foundation/components:  All components developed using sightly are here.
   
      3.     How to add a design in AEM?
              
              Creating and assigning a design(er) in AEM allows us to create a consistent and feel
               across the website and also to share the global content.
               Simple steps to create or add a design to a page is as follows:
                   *Miscadmin
                   *Tools -> Designs --> create a new page -> give title and name and click create.                                    *open page --> page properties --> Advanced --> Design field and ok.
   
       4.    Why we need to include global.jsp if we are creating a component in jsp?
               The global.jsp script which adobe provides by default declare Sling, AEM and JSTL
                taglibs to make component creation easy in AEM.

      5.     Where dialog and design dialogue data is stored?
                  Design dialog data is stored under /etc/designs folder
                  Dialogue data is stored under /content folder


      6.     How do you analyze thread dumps?
              
             JStack can be used to  get the thread dumps.
             Steps to generate the thread dumps are as follows:
             1. ps -ef | grep java <author (or) publish> is to list the java processes that are running
                 on a server.
             2. jstack <PID> >> therad.txt( this to copy the particular java process ID to  thread.txt
                  -file)run for 10 times in interval of 2 sec.
             3. Once you have thread dump you can use any thread dump analyzer tool to find long                               running thread.
                  Linux command is sudo -u user jstack <pid> >> threaddumps.log
                  Some dumpanalysis tools such as tda.
     
      7.   The basic Servlet class that we need to extend when we are trying to create a new                         Servlet?   ----  SlingAllMethodsServlet
         
      8.     In AEM, how servlet will be identified? And how it will be defined?
               In Servlet-  @properties(value = {
                                            @property( name = "sling.servlet.paths", value =  
                    {"/apps/geometrixx/components/content/common/billing/AlertServlet"}) })
     
       9. Question:

<div class="item">
<sly data-sly-test="${properties.jcr:title && properties.jcr:description}">
<h1>${properties.jcr:title}</h1>
<p>${properties.jcr:description}</p>
</sly>

</div> Write an optimized way of above code.

Ans:

<div class="item" data-sly-test="${properties.jcr:title && properties.jcr:description}">
<h1>${properties.jcr:title}</h1>
<p>${properties.jcr:description}</p>

</div>

Question: OPmized for the below
<%@include file="/libs/foundation/global.jsp"%>
<a href="<%= xssAPI.getValidHref(properties.get("link", "#")) %>" <%
String title = properties.get("jcr:title", "");
if (title.length() > 0) {
%>title="<%= xssAPI.encodeForHTMLAttr(title) %>"<%
} %>>
<%= xssAPI.encodeForHTML(properties.get("jcr:description", "")) %>
</a>

Ans:    


<a href="${properties.link|| '#'}“
title="${properties.jcr:title}">
${properties.jcr:description}
</a>



Questions: Questions: Do you know what is the prime type that we use when setting up the configurations?


Ans: sling:OsgiConfig


Questions:   Lets take a scenario, where we have 5pages with  each with different layouts and asked you to adive their team on how many templates that they have to configure..!? what would be your suggestion?

Ans: make the template multifunctional

Questions: Basic building blocks of the bundle?

   Ans: components:   Implementation of Events, Schedulers, Servlets, Models
,           Services:   Interface: Runnable, Servlet, EventHandling, JobConsumer 




Questions:A CQ5 instance hosts multiple websites in different content branches. How is it possible to map a domain to a specific content branch to support multi-domain hosting scenarios?

Ans: These nodes have to be created in the default workspace of the repository via the CRX Content Explorer, required nodetypes in brackets:
1
2
3
4
5
6
7
/etc
   /map                       (sling:Folder)
      /http                   (sling:OrderedFolder)
         /www_geometrixx_fr   (sling:Mapping)
         /www.geometrixx.fr   (sling:Mapping)
         /www_geometrixx_de   (sling:Mapping)
         /www.geometrixx.de   (sling:Mapping)

Questions:  Should you use <cq:include> or <sling:include>?

Ans: When developing AEM components, Adobe recommends that you use <cq:include>.

<cq:include> allows you to directly include script files by their name when using the script attribute. This takes component and resource type inheritance into account, and is often simpler than strict adherence to Sling's script resolution using selectors and extensions.



      
     


Friday, December 11, 2015

How to capture the RollOutPage as event in aem

When we are using Live copy based on the Blueprint in aem. This is one of the scenario, where we will come across the RollOut event in AEM.

          If we made any change to Blue print copy and want to reflect the changes to Live-copy as well, then we have to use Rollout page from the Sidekick. Then the changes will get reflected under Live-copy.  

         So, the changes are reflected and captured under jcr:content of the live copy. Here if we want to capture the RollOutPage event in aem using the java, we can use following code as reference.

Note: The following code is just for reference. 

package com.adobe.training.core.impl;
import javax.jcr.Property;
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.jcr.api.SlingRepository;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component
public class TitlePropertyListner implements EventListener {
    
    private final Logger log = LoggerFactory.getLogger(TitlePropertyListner.class);
    
    @Reference
    private SlingRepository repository;
    
    private Session session;
    private ObservationManager observationManager;
    
    protected void activate(ComponentContext context) throws Exception
    {
        session = repository.loginAdministrative(null);
        observationManager = session.getWorkspace().getObservationManager();
        observationManager.addEventListener(this, Event.PROPERTY_CHANGED, "/", true, null, null, true);
        log.info("********************************************** added JCR event listner");
    }
    protected void deactivate(ComponentContext context)
    {
        try{
            if(observationManager !=null)
            {
                observationManager.removeEventListener(this);
                log.info("************************************************************ removed JCR event listner");
            }
        }
        catch(RepositoryException e)
        {
            log.error("***************************************************************** error removing JCR event listner", e);  
        }
    }
    

    @Override
    public void onEvent(EventIterator it) {
        while (it.hasNext()) {
            Event event = it.nextEvent();
            try {
             log.info("********new property event: {}", event.getPath());
                Property changedProperty = session.getProperty(event.getPath());
                if (changedProperty.getName().equalsIgnoreCase("cq:lastRolledout")) {
                    log.info("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^LastRolledout Time: {}", changedProperty.getValue());
                    session.save();
                    
                }
            }
            catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }   
        
    }

}

Sunday, November 15, 2015

Key words that I can think of

Responsive.
Jcr Connectors
Sightly
ExtJs
AngularJs
Granite
Foundation
Log4j
slf4j
Dialog conversion


When Migrating from Adobe CQ 5.6 to AEM 6.1

What are the things to be Considered?
--> All the API's that have changed
-->What are the things that got deprecated
-->What are the workaround for upgrading to Java 1.8(It depends on particular scenario)
-->What are JQuery upgrading issues.


Will keep on updating points.

Saturday, October 24, 2015

Basic commands and stuff to remember when working on AEM projects

Commands to do maven build to install the stuff from code to AEM instances:

mvn clean install -PautoInstallPackage -Daem.host=localhost -Daem.port=4502 -Dvault.password=admin

mvn clean install -PautoInstallBundle -Daem.host=localhost -Daem.port=4502 -Dvault.password=admin

Note: Port number is depending on what port you are running AEM instance. In the above commands, I gave 4502 as some example.

Command to open the AEM instance in debug mode:


java -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=30303 -XX:+HeapDumpOnOutOfMemoryError -XX:MaxPermSize=512M -Xmx1024m -jar cq-author-p4502.jar -p 4502 -verbose -nofork

Note: The above marked one in the red is port number on which debug instance runs.
       
In Eclipse, open the debug mode and under Run select debug configurations and from there select Remote Java Application --> right click --> New --> give port number same as above marked in the red.

Command to start the AEM Author instance:

java -Xmx1024m -jar cq-author-4502.jar

Note: Xmx means  maximum allocation of the RAM for the aem service

java -Xms1024m -jar cq-author-4502.jar

note: Xms means  Minimum allocation of the RAM for  the arm service

Using JAX-RS AND JERSY to write RESTFUL services in OSGI(APACHE FELIX, AEM)

https://chanchal.wordpress.com/2015/01/11/using-jax-rs-and-jersey-to-write-restful-services-in-osgi-apache-felix-adobe-cq5aem/

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

Link Checker Transformer  and it's role in validating the page links:
Link checker Transformer can be used to disable or enable the external links validation on the content pages. It is up to us to decide on which one we have to choose from options like Disable entire Link checker transformer, mark entire links are valid or skip the validation of the link.

To Disable the entire Link Checker Transformer:
Go to http://localhost:4502/system/console/configMgr  and search for Day CQ Link Checker Transformer and in that select the Disable Checking option.

For certain Domain we can disable the link by adding overriding pattern:
For Example Link Check Override patterns: if we add ^hello/, then any external link starting with System will not be checked. You can add additional pattern to it.

How to make sure some links are always valid or always skip?
We can use x-cq-linkchecker="valid" parameter in anchor tags to make always make that particular link as valid or
x-cq-linkchecker="skip" parameter in anchor tags to make always make that particular link as skip, since it even didn't check the links.
Useful links for Link checking:
http://tostring.me/206/how-to-disable-adobe-cq-link-checker/

AEM CHEAT SHEET:
https://github.com/paulrohrbeck/aem-links/blob/master/cheatsheet.md

HOW TO CHECK THE USAGE OF THE COMPONENT IN THE WEBSITE?
1. In local instance or any AEM environment go 
    to http://localhost:6502/libs/cq/search/content/querydebug.html
2. Start building the query something like this:
    path=/content/<Specific site>
    property=sling:resourceType
    property.value=<project-name>/components/content/text
            Note: we can skip /app and directly give the path of component as stated above.
3. Hit search

   
   





Will keep on Adding the points.






Monday, October 5, 2015

How to Create and Update the Content Package in AEM using Java?

How to Create  and Update the Content Package in AEM using Java?

The scenario is after authoring of the page, content implementer tries to activate, deactivate and update the page.

When Content Implementer activate the page then we have  to check for any existing content package  with in a session. If no Content Package exists, then a new Content package has to be created and add the respective page path as filter path into the Content Package.

When Content Implementer deactivate the page, then page path(filter path) has to be removed from the Content package.

When page is updated by the Content Implementer, then package has to be re-built gain.

Note: In every case Content Package has to be rebuilt, after every Operation.

The Code is as follows: ( This  Code is just for the reference. There  may some tweaks needs to be done. This article is created, just to give an understanding).





package com.sample.priceless.cms.utilities.servlets;

import java.io.IOException;
import java.util.List;

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

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.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.day.jcr.vault.fs.api.PathFilterSet;
import com.day.jcr.vault.fs.api.ProgressTrackerListener;
import com.day.jcr.vault.fs.config.DefaultWorkspaceFilter;
import com.day.jcr.vault.packaging.JcrPackage;
import com.day.jcr.vault.packaging.JcrPackageDefinition;
import com.day.jcr.vault.packaging.JcrPackageManager;
import com.day.jcr.vault.packaging.PackagingService;
import com.day.jcr.vault.util.DefaultProgressListener;

@Component(immediate = true)
@Service(Servlet.class)
@Properties({ @Property(name = "service.description", value = "Create Package Servlet"), @Property(name = "service.vendor", value = "Priceless"),
@Property(name = "sling.servlet.paths", value = "/bin/cps" ),
@Property(name = "sling.servlet.methods", value = "GET") })
public class CreatePackageServlet extends SlingSafeMethodsServlet {

    /**
*
*/
private static final long serialVersionUID = 1L;

private final Logger mLogger = LoggerFactory.getLogger(this.getClass());

    private Session session;

    @Reference
    private ResourceResolverFactory resolverFactory;

    public CreatePackageServlet() {
    }

    @Override
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException
    {
        try {
            String packageGroup = "my_packages";
            String packageName = "abc123";
            String version = "1.0";
            StringBuffer packagePathBuffer = new StringBuffer();
            packagePathBuffer.append("/etc/packages/");
            packagePathBuffer.append(packageGroup);
            packagePathBuffer.append("/");
            packagePathBuffer.append(packageName);
            packagePathBuffer.append("-");
            packagePathBuffer.append(version);
            packagePathBuffer.append(".zip");

            String packagePath  = packagePathBuffer.toString();

           
            ResourceResolver resourceResolver = resolverFactory.getAdministrativeResourceResolver(null);
            session = resourceResolver.adaptTo(Session.class);
           
            JcrPackageManager packageManager =  (JcrPackageManager) PackagingService.getPackageManager(session);
            JcrPackage jcrPackage = null;
            DefaultWorkspaceFilter filter = null;
           
            if(request.getParameter("requestId").equalsIgnoreCase("activate")){
            if(session.itemExists(packagePath)) {
            jcrPackage =  packageManager.open(session.getNode(packagePath));
            }

            if (jcrPackage == null) {
                jcrPackage = packageManager.create(packageGroup, packageName, version);
                }
                filter = new DefaultWorkspaceFilter();
               
                filter.add(new PathFilterSet("/content/geometrixx-outdoors/en/men/coats/edmonton-winter"));
               
                filter.add(new PathFilterSet("/content/geometrixx-outdoors/en/men/pants/fulani-nomad"));
               
                filter.add(new PathFilterSet("/content/geometrixx-outdoors/en/men/shirts/ashanti-nomad"));

            } else if (request.getParameter("requestId").equalsIgnoreCase("deactivate")){
            if(session.itemExists(packagePath)) {
            jcrPackage = packageManager.open(session.getNode(packagePath));
                DefaultWorkspaceFilter defaultWorkspaceFilter = (DefaultWorkspaceFilter) jcrPackage.getDefinition().getMetaInf().getFilter();
               
                List<PathFilterSet> filterSets = defaultWorkspaceFilter.getFilterSets();
                int index = -1;
                for(int i = 0; i < filterSets.size() ; i++) {
                if(filterSets.get(i).getRoot().equals("/content/geometrixx-outdoors/en/men/shirts/ashanti-nomad")) {
                index = i;
                break;
                }
                }
               
                if(index != -1) {
                filterSets.remove(index);
                }
               
                filter = new DefaultWorkspaceFilter();
                for(PathFilterSet filterSet : filterSets) {
                filter.add(filterSet);
                }
            } else {
            mLogger.info("Packag doesnot exist::" + packagePath);
            }
           
            }
           
           
            JcrPackageDefinition definition = jcrPackage.getDefinition();
            mLogger.info("JcrPackage"+jcrPackage.toString());
            boolean autoSave = true;
            definition.setFilter(filter, autoSave);
            mLogger.info("filter was set");
            ProgressTrackerListener listener = new DefaultProgressListener();
            packageManager.assemble(jcrPackage, listener);
            mLogger.info("jcrPackage manager is assembeld ---------------------done");
           
            session.save();
            session.logout();
           
            response.getWriter().print("Package created. Check your package manager console with name " + packageName);
        }catch (Exception e){
        e.printStackTrace();
        }
    }
}