Performance Troubleshooting

During the initial development phase of a website, not much attention is given to the performance of website i.e. how website will respond to million of requests. Performance means the time your website takes to respond to visitor’s request. But in the later stages of implementation you need to optimize the website to maximize the performance goals.In this blog, we will discuss some measures to increase the page load time so as to provide good experience to users.

Performance Optimization Methodology

Five rules that should be followed to avoid performance issues.

  1. Planning for Optimization

    A project should first be soft-launched to a limited audience in order to gather real-life experience.When the website is live, it is the time when you experience real load on your system.

  2. Simulate Reality

    After the launch of website, if there are some performance issues, it means load and performance tests did not simulate reality closely enough. “Real” means real traffic, real content size and real code.

  3.  Establish Solid Goals

    Establishing good performance goals is a tough task. It is often best to collect real life logs and benchmarks from a comparable website.

  4. Stay Relevant

    Only optimize one things at a time.If you try to do things in parallel without validating the impact of the one optimization, later it will be difficult to figure out which optimization actually helped.

  5. Agile Iteration Cycles

    Performance tuning is an iterative process that involves, measuring, analysis, optimization and validation until the goal is reached.

Page Loading Time
  1. 70% of the requests for pages should be responded to in less than 100ms.
  2. 25% of the requests for pages should get a response within 100ms-300ms.
  3. 4% of the requests for pages should get a response within 300ms-500ms.
  4. 1% of the requests for pages should get a response within 500ms-1000ms.
  5. No pages should respond slower than 1 second.
Performance Guidelines
  1. Mostly dispatcher caching inefficiency and use of queries in normal display templates leads to performance issues.
  2. JVM and OS level tuning does not impact the performance much.Therefore, it should be performed at the very end of the optimization cycle.
Performance Monitoring

To optimize the performance, you need to monitor various attributes of the instance and its behavior.

  1. Backup plan and Disaster recovery plan should be there.
  2. An error tracking system(like bugZilla, JIRA) should be available for reporting problems.
  3. File systems, Log files and Replication agents should be monitored.
  4. Regularly purge workflow instances.
INTERPRETING THE REQUEST.LOG
  1. To analyze a bigger request.log, it is recommended to use rlog.jar which allows you to sort and filter according to response times.
  2. AEM includes various helper tools located in : <cq-installation-dir>/crx-quickstart/opt/helpers
  3. One of these, rlog.jar, can be used to quickly sort request.log so that requests are displayed by duration, from longest to shortest time.
Basic Commands
  1. To open request.log in terminal : less request.log or more request.log
  2. java -jar ../opt/helopers/rlog.jar -xdev request.log | less

  • This command tells you the number of requests parsed. Requests are sorted from longest to shortest time.
  • By looking at the result, we can figure out “/cust1.cust.html?page text/html” is not cached
    because its request is coming to the server again and again.
  • “/companyservice/contact.html text/html” is a cacheable page. Even though it is cacheable, it is taking 44s.
  • Non-cacheable pages are taking a lot of time, either publisher is non-responsive or these pages are requesting something from backend server and backend server is down.

3. Now we will see how many times “/companyservice/contact.html text/html” page is rendered.

  • java -jar ../opt/helpers/rlog.jar -xdev request.log | grep “/companyservice/contact.html ” | wc -l
  • This cacheable page is rendered 122 times a day, which is a huge number. It is also impossble to invalidate cache 122 times a day.Therefore, there is some issue with caching configuration.

4. Here we are piping the result into a text file ‘demo.txt’. Now, we can sort the data by date and get to know what is actually happening on publisher.

  • java -jar ../opt/helpers/rlog.jar -xdev request.log > demo.txt
Calculating Cache Ratio

1. Cache ratio means how many requests that come to your system are handled by cache.

2. Dispatcher Cache Ratio

  • (Total Number of Requests – Number of Requests on Publisher )/ Total Number of Requests
  • Remember if you don’t have a 1:1 publisher/dispatcher pairing, you will need to add requests from all dispatchers and publishers together to get an accurate measurement

3. Publisher Cache Ratio

  • Total number of cacheable page request coming to publisher
  • (Total Publisher Request – Total non-cacheable Requests) / Total Publisher Requests

4. Adobe Recommends a Cache Ratio of 90-95% for best performance.

5. The Dispatcher always requests the document directly from the AEM instance in the following cases:

  • If the HTTP method is not GET. Other common methods are POST for form data and HEAD for the HTTP header.
  • If the request URI contains a question mark “?”. This usually indicates a dynamic page, such as a search result, which does not need to be cached.
  • The file extension is missing. The web server needs the extension to determine the document type (the MIME-type).

6. Calculating Dispatcher Cache Ratio Using Access log and Request log

  • wc -l access.log(To get total number of requests to web server). Let this number be 129491.
  • java -jar ../opt/helpers/rlog.jar -xdev request.log | less(To get number of requests on publisher). Let this number be 58959.
  • Therefore, dispatcher cache ratio =(129491 – 58959) / 129491 = 54.5 %

7. Calculating Publisher Cache Ratio

  • java -jar ../opt/helpers/rlog.jar -xdev request.log | less(To get number of requests on publisher). Let this number be 58959.
  • From this we will pull out the requests which are not cacheable using :

    java -jar ../opt/helpers//rlog.jar -xdev request..log | grep -Ev “\?|login|POST” | wc – l

    Let this number be 26855.

  • Therefore, publisher cache ratio = (58959 – 26855) / 58959 = 54.5%

Thus, you can apply performance enhancing mechanisms to your website like caching the content, measuring page load time before its launch to reduce the response time of your website and thus providing a good user experience.

Thank You for enjoying this blog !

Workflow in AEM

In this blog, we will have a beginner journey on how to create a simple workflow, a launcher and custom steps involved in it.

Let us begin by understanding

WHAT ARE WORKFLOWS?

Workflow is a well defined series of steps that allows to automate activities of Experience Manager. It is divided into various steps including people (participants), procedures (process) or some tools. The flow of workflow can be either sequential or parallel when multiple procedures can run parallely to each other. In short, a workflow is similar to a flow-chart which describes the series of procedures to be executed having multiple participants to achieve a desired outcome.

There are many out of the box workflow models available for use and we can write our custom workflows which can be tailored as per the business needs of the company.

There can be plethora of use cases for writing workflows that may depend on the business needs.

For example, the process of publishing a page can be customized and tailored for inclusion of some special participants that need to approve the request for activation or send a mail after approval or rejection.

Workflow Models

Workflow Model is a container or blueprint of the workflow that combines the workflow steps and link them logically.

  • It has a start and an end node (plus an optional participant step) by default.
  • It can contain different nodes and the transitions that link them. The workflow nodes can get any input from author or can do processing via Java code or ECMA scripts.
  • Workflow payload is an important term which is considered as a resource on which workflow will perform it’s functions.

List of workflows can be seen on http://localhost:4502/libs/cq/workflow/content/console.html.

Figure 1: AEM Workflow Console

Figure 2: Tabs in Workflow Console

These are the tabs that contain the information about the workflows.

  • Models:- has workflow models having title of the workflow, version, description, and model id.
  • Instances:- lists the active instances of workflows having status (running, suspended etc.), initiator, start time, workflow model, payload associated with the workflow.
  • Archive:- contains the history of all the workflow instances. It contains the status (completed, aborted etc.),  initiator, start and end time, workflow model, payload, workflow title etc.
  • Launcher:- contains the launchers of workflow models that trigger initiation of workflows automatically on some action. It contains fields such as event type (created, deleted, modified), nodetype, globbing or path specified for action of node, condition, workflow model that needs to be triggered, description, value of enabled, exclusion list, run modes.
  • Failure:- shows failed instances of workflow on which some error occurred during execution. The issues can be fixed and workflow instances can be resumed.
Example

Let’s have a look at one of the practical examples of workflow. To create a new workflow we can add the title and the name (cannot contain spaces) of the workflow by clicking on New tab.

Figure 3: Create a new Workflow Model

Thereafter, we can edit the workflow created to customize it. This is the by default view of the workflow wherein there is a start and an end node with a default participant step.

Figure 4: By default view of workflow

We can view the logical layout of the workflow in the console whereas to see the node structure stored for the workflow we can see /etc/workflow/models/sample_workflow.

Figure 5: Node structure of workflow in CRX

It contains metadata about the workflow stored in JCR. We can notice flow and model nodes. It has the nodes between start and end node present in the workflow. The model node has all the steps added in the workflow marked as nodes alongwith the transitions they have between them. We can see the metadata of node 6 in the snapshot since it is a process step having title as Publish Page.

We can see the running instance of the workflow under /etc/workflow/instance path in CRX.

Figure 6: Nodes in trigger workflow instance

This is an example of trigger workflow having data (metadata and payload of which workflow instance is working upon), history, metadata of a particular step and work Items associated with the workflow.

Workflow Nodes

There are many workflow nodes that can be dragged and dropped such as Participant step, process step, and split, or split, dialog participant step, form participant step, container step, goto step etc.

  1. PARTICIPANT STEP: In this step the user can give
  • Title and description and select a user or a group.
  • The email option will send an email in the inbox of the user/group.

  

Figure 7: Participant Step

  1. PROCESS STEP: In this step
  • Common tab can contain title and description of the process step.
  • There are timeout settings too in which we can set the timeout limit of the workflow after which the timeout handler will start it’s execution.
  • In the process tab we select the process from the dropdown (We can add our own process in the list using java).
  • We have to check the option of Handler Advance so as to allow the workflow process step to proceed to the next step after performing it’s task.
  • There is another field named as Arguments in which we can pass the arguments to the process step for function and task.

   

Figure 8: Process Step

Now, to add our own process in the list we have to make a workflow process and register it as a service in java and can add the logical code that will execute on this process step.

This code snippet shows the basic skeleton of a workflow process that it required for process step.

@Component will register our Java class as a component with the properties that enables it immediately and helps it get the metadata provided by the execute method of WorkflowProcess class.

@Service will register our Java class as a service to be used in the Workflow process.

@Properties will add certain properties such as process.label which will show our class in the process list of the process step. The value of this property will be shown in the drop down list.

The Java class should implement WorkflowProcess interface and give definition to execute method. This method provides three arguments namely WorkItem, WorkflowSession, MetaDataMap.

  • WorkItem defines the currently started java process. It contains the data of the workflow and can be fetched using this argument such as Id, workflow, workflow data etc. We can access the workflow object using this. We can get payload of the data using a method of workItem.
  • WorkflowSession controls the workflow by providing methods that can deploy, complete, create, start, stop, resume, suspend, retrieve, complete workflow models, instances or user/groups. We can start another workflow using workflow session of current workflow.
  • MetadataMap is a Map<String, Object> of properties that are entered in the dialog of the process step. We can fetch the list of the arguments from metadata map.

There can be many other types of steps that can be configured within the workflow and can be tailored using java code, scripts, parameters etc. to provide the desired functionality.

  1. An OR SPLIT can be used to introduce branching in the workflow with which only one branch of the workflow can be activated (conditional) based on the script which is mentioned in the dialog.
  • The user can give either the path of the script or can write ECMA script in the given tab.
  • The Common tab has an option to select the number of branches required in the OR Split.

Figure 9: OR Split (marked with green)

 

Figure 10: ECMA script written for branch 1 (set as default route).

We can write different condition for branch 2 or can upload a script.

  1. AND SPLIT wherein all the branches go parallely and we can execute tasks for multiple processing.
  2. A CONTAINER STEP can allow another workflow to be executed as a child of the current workflow.This workflow is a sub workflow that can be instantiated. Another way of performing the same action is via Java code where we can start a workflow using workflowSession.
    This code snippet gets the model of the child workflow that needs to be invoked. Thereafter, the data of the workflow is created which is used to start the workflow in the current session.
  3. GOTO STEP traverses between the steps in the workflow based on the result of the ECMA script. It can be used to implement the use case of looping in the workflow process.
  4. DIALOG PARTICIPANT STEP is a special scenario of participant step where the user/group needs to give some information that is to be used in the workflow.
    • The additional step in this step is to provide a path of the dialog. We have to make that dialog in CRX  (/etc/workflows/dialog) and provide the path of that dialog to receive the input from the selected user/group.
    • The structure of the dialog should be cq:dialog type. This data can be stored in the form of payload (when we set the value of the property as ./jcr:content/nodename) which can be overwritten in subsequent uses of this dialog.
    • The data can also be stored with the work item (when the value is node name) metadata and is persisted with subsequent use of dialog.
Workflow Launchers

Workflow launchers can be used to trigger the workflow based on some event that can be specified in the launcher. We can add a launcher under the Launcher tab.

Figure 11: Creation of Launcher for Workflow

  • Event type:- can be either created, modified or deleted i.e. the action on which the launcher will trigger the workflow mentioned.
  • Nodetype:- is for the type of the node on which the launcher will apply to start the workflow.
  • Path:- specifies the path on which this action will be applied to during the workflow initiation i.e. on the which the launcher of the workflow will be applied to.
  • Condition tab:- determines the condition to be applied when the workflow is launched. This is optional in case a user wants to start the launcher based on a specific condition only.
  • Workflow:- Launcher needs to be associated with a workflow model so that it can be determined that what will be triggered with the help of this launcher.
  • Description:- can be set and activate should be enabled to enable the launch of the workflow launcher.
  • Exclude:- list is a comma separated list of JCR events or items to be ignored via workflow triggering.
  • Run modes:- in this dialog is to specify the server on which this will be applied to (author, publish, author & publish).

Hope you understood the basics of workflow and try to implement this in one of the use cases you experience.

We can explore workflows in detail in the future blogs.

Thanks for reading.

Happy Coding.

AEM Forms

Overview

AEM has provided AEM Forms tool in AEM 6 that simplify creation and management of complicated forms and form fragments. This tool ease the creation of interactive adaptive forms and authoring is similar to authoring components in pages. AEM forms uses “Lazy loading” i.e. components are loaded only when they are required so forms will be loaded faster.

It gives variety of features:

  • Pre-filling of forms
  • Theme development console
  • Inbuilt complex submit actions like PDF generation of HTML form
  • Rule editor
  • E-sign
  • File attachment
  • Scribble signature
  • Form fragment
  • Emailing the form data to an applicant on successful submission
  • You can easily write your custom submit action if needed.
  • and much more.
Steps to create an adaptive form:
i. Go to touch UI main console and select forms. 

ii. Select Forms and Documents

iii. Now create a new adaptive form by clicking the create button on top right corner. 

iv. Now select a theme , you can use by default theme or you can make your own theme and use it. For the time being let’s select tabbed enrollment.

v. Now provide basic information about the form you want to make.

vi. Now create and open it.

vii. Your basic form will look like this , let’s understand it’s components.

 

  1. We can divide our form in sections/tabs so that unrelated fields or the different sections of forms and be separated. We can add or remove these sections and we can rename these section by simply clicking on it and change its property in sidekick.
  2. These are the default fields we can change its field label , input type field , Placeholder, Regex in the property field in the sidekick.
  3. We can add more fields in the form by dragging those from parsys.
  4. We can configure logo of the form by simply clicking on the logo icon and edit it . we can select an image from DAM or we can upload it from our file system.we can also edit the logo title by simply clicking it and editing it.
  5. Form title can also be configured and if we want we can also exclude it to come in the final report which will be sent after submit.
  6. This is help content, we can provide this with each field, it is of 2 types short and long.We can provide this while providing properties to field below the patterns section.
  7. These are the basic buttons, we can modify their backend and frontend like any other form component.

viii. Now you can add any no. of fields in any section and make your AEM form.

List of available form components

 

 

Rule Editor

There are so many situations when we want certain rules to be applied to forms in the fields like in the drop down if India is selected in one list then other list must show states of India and in case of USA states of USA’s states must display, or when user enter pincode then name of city automatically comes in next field or you want to perform certain calculations.

AEM Forms provide very easy console for these rules here one can set up rules without writing single word of code.

  1. To make or apply a rule select the section on which you want to apply the rule and select the rule editor symbol(hammer and plate).
  2. Select the section from sidekick in the left.
  3. Select create (plus + icon on top).
  4. Select the type of operation you want to perform viz. When, Show, Hide, Enable , Set value, validate etc.
  5. Set the desired operation eg.

Form Fragment

A form designer is used to create common segments which will be used generic for all the forms like name and address, family details, income details, and so on. These reusable, generic and standalone segments are called adaptive form fragments and are widely used to design forms in AEM.

How to create form fragment
  1. Select create adaptive form fragment from form console
  2. Fill the basic details like name and description.
  3. Open it.
  4. A blank page with a parsys will appear now drop the required components and make your form fragment.
  5. All of your progress will be auto saved so just perform your task and go back.
Using the emulator:

While making the forms we can see how it will look in different breakpoints(i.e. Screen sizes)

This feature is available at top of the form.

We can select device and  change its  orientation very easily with few mouse click.

  1. This shows list of various android and ios phones and tablets.
  2. This button changes orientation of device.

Other than reference themes and fragments there are many ways Adobe Experience Manager Forms makes form creation and usage easy, quick. Consistent throughout multiple channels.

Is a Misconfigured “Page Not Found” Jeopardizing Your Website?

Since Zap Technology Solutions released its free Security Scanner (http://scan.zapts.com) there have been a lot of folks scanning their websites.  However, a few scans reported that sites were more vulnerable than they actually were.  Something wrong with the scanner?  No.  It is due to a simple misconfiguration of the website’s AEM/CQ5-based “Page Not Found” response.  You see, the standard HTTP response code for a successfully served page is 200 (OK).  However, typically a “Page Not Found” page has a response code of 404 (Page Not Found).

Read more

Website, WCMS, and Network Security

With the most recent news about Sony’s hacking (just the latest in what seems like weekly headlines of hacking), I wonder how do other companies address security? I know that Utility companies and government agencies are required by regulations to be more stringent about security, but what about other organizations?

Read more

AEM Conferences – Why YOU Should Attend…

As the president of Zap Technology Solutions, I’ve been fortunate enough to be able to attend Adobe CQ5/AEM-related conferences for the past 3 years.  The two conferences that I never miss are the Adobe Summit put on by Adobe and the Evolve Community Summit put on by 3|Share.  I love both of these conferences for different reasons.

The Adobe Summit is a great big production and has thousands of people in attendance.  The key notes are amazing.  The insight into future innovations is inspiring.  The vendors on hand and all in the same place are fabulous.  The amount of information available is endless.  The Summit Bash and the after parties are a lot of fun too.  In 2016, Adobe Summit will be moving from Salt Lake City to Las Vegas.  Just another reason to attend.

The Evolve Community Summit is entering its 3rd year.  It’s moved from November to August in 2015.  This conference has a much stronger technical base to it.  It’s less about the digital marketing and more about the technology.  We spend less time talking about features and more time talking about how to solve real-world problems.  There’s a little more honesty at this conference in that people recognize that working with AEM is not all rainbows and unicorns and aren’t afraid to say so (even the Adobe folks in attendance.)  There’s more honesty about some of the short-comings and how to work around them.  Some of the brightest technical leaders in the AEM space attend this conference.

In addition to the knowledge and sessions which are provided as part of the each of these conferences, there’s also an opportunity to add even more learning to your time at the conference.  You can take Adobe certified classes and take Adobe Certification Exams.  If you were planning to take some training and/or get certified, this is a great way to both attend a great conference as well as get the training/certification that you need.

Let me know if you’ll be attending either of these conferences and we might be able to meet up.

Jason Meyer

President, Zap Technology Solutions

AEM Dispatcher Setup for Linux

Installing dispatcher for AEM in Apache Web-server in Linux may get little tricky, as documentation provided by Adobe on Installation of Dispatcher in Linux is not sufficient, and if we take it in analogy and try doing same way we do in Windows, then we face some issues locating the appropriate files.

Prerequisites for Dispatcher Setup
  • Apache 2.2 web-server – In Ubuntu 12.0 and higher, Apache 2.2 web-server is pre-installed, but in case it is not there, you can find the installation instructions here.
  • Dispatcher Module – Appropriate dispatcher module can be downloaded from Adobe Package Share.
Installation Instructions
  1. Considering Apache web-server is already setup in system, go ahead and extract dispatcher module using following command:
  2. Once you have extracted the files, now you have to move the appropriate files to their respective apt path.
  3. Move “dispatcher-apache2.x-4.1.x.so” to “/usr/lib/apache2/modules”. There you will find all the modules already being loaded by apache 2 webserver.
  4. Adobe recommends to give a soft name to your dispatcher module, but you don’t need it as once setup is done, you will be hardly using it again.
  5. Now go ahead and create a folder conf under “/etc/apache2/”, and move “dispatcher.any” file under this folder. Make sure that you don’t move your dispatcher.any file to ‘conf.d’ folder which is already present.
  6. Now is the time to edit and map module file that you added and map the dispatcher.any file. Go ahead and edit apache2.conf file present under “etc/apache2/”.
  7. Scroll to the end, put some nice comments about you adding some new configs, and add following:
  8. Also add the following config to the end of apache2.conf file, which loads the dispatcher in web-server.
    Comments given above are self explanatory but, you can still go and edit configs if needed as per following descriptions:

    • DispatcherConfig: Location and name of the configuration file (Can be given as an absolute or relative path)
    • DispatcherLog: Location and name of the log file (Can be given as an absolute or relative path)
    • DispatcherLogLevel: Log level for the log file
    • DispatcherNoServerHeader: Whether to use the Apache or CQ server header
    • DispatcherDeclineRoot: Defines whether to decline requests to the root “/”
    • DispatcherUseProcessedURL: Defines whether to use the original request URL or to use one already processed by other handlers (ie: mod_rewrite)
      • Note: This is essential for rewriting incoming links (stripping away the ‘content/{site_name}’)
    • DispatcherPassError: Defines whether CQ or Apache will handle HTTP 40x error codes
    • SetHandler (Apache parameter): Forces all matching files to be processed by a handler
  9. Make sure, that path that is provided for load module, matches with the path where you placed your dispatcher module. Also match the name and version of dispatcher module, and change the config as required.
  10. Now configure dispatcher.any file. Edit /renders section in dispatcher.any.
    By default you may find port set to 8000 or 8080, change it to 80.
    Give whatever soft-name you want to give to your cache folder in place of “cqcache”
  11. Restart the apache server to let webserver take effect. You can restart apache server by using following command:
  12. Once server is restarted and you get [OK] message, go and check /var/log/apache2/dispatcher.log file. If it says dispatcher initialized with correct cache path, it means dispatcher is successfully setup and ready to be used.

Now you just need to configure your CQ replication agent, and point dispatcher flush agents to correct port.

I tested this today itself i.e. 14th Oct 2013 on Ubuntu 13 64 bit debian based OS. It worked like wonder for me. Please post your comments and queries if you have any issues with it, and also if there are better ways to do it. Cheeeerz.

Dynamic Options values in AEM dialog dropdown Using $PATH

In this post, I will explain a real project use-case, where I need to populate a Dropdown in my component dialog with dynamic values, but the condition are-

1. These values can only be fetched from the current resource or current page object.
2. Another condition is that this dropdown must be auto-populated when the dialog opened.

For example,  The drop down values can be the list of all parent pages of the page where this component was dropped.

Q1). How will you go for it?

You will think about ajax call because the dropdown can be filled with dynamic values using options property.

Q2). Yes, you are right then, what will you call from the options property?

Sling Servlet

If your answer is Sling Servlet then, I have some questions for you-

Q1). How will you get the current resource  or current page object in that servlet?
Q2). If you  are trying to pass the path of current resource then How will you do that?

OK, I think you are well understood what am I trying to say. How to get current resource or current page object into the called Sling Servlet.

Maybe you can do it using some other approach but in this post I will explain, How I complete this task?

In place of servlet I have created a JSP file under same component node with some selector (For ex. options.json). For Ex. My component structure is-

Now, I have set some properties on my drop-down dialog node. These properties are shown in figure-

3

Here you will notice that, I have used $PATH, this will return the path of the component wherever it is dropped. Then I used Sling Script Resolution Principle to call my options.json.jsp file.

For writing this blog, I had created dummy data but in actual, I had created a Sling Service and from one of it’s methods, I was getting the JSON values.

Here, you should follow standard coding practices and should remove these scriptlets from JSP file to some java file. But the key point is that this JSP must return the values in JSON format. If you are using Sightly then same code will work or if you want to use HTML in place of JSP then it will work perfectly fine.

I am also sharing the Git repository link where you can find demo examples for these properties.
Git repository link is –

https://bitbucket.org/accunitysoft/accunity-blog-snippets

Happy Coding..!!

Ankur Chauhan
Tech Lead

 

Maven Dependencies Version Issue in AEM

In this post, I will explain package version issues for AEM package dependencies. Here is the scenario where I got this issue:

Issue Description

In one of my project, I had to create a tool for AEM that supports AEM5.6.1 and AEM6.x versions. For some dependencies, these AEM version instances (CQ5.6.1, AEM6.0, AEM6.1, and AEM6.2) needed to use different version of dependencies.

If I used an older version of these dependencies then my bundle did not work in AEM6.2 and remains in installed state. If I used the higher version of these dependencies then my code was not working for the older versions of AEM (CQ5.6.1, AEM6.0, AEM6.1).

Underlying Reason

Versions available for these package dependencies in OSGi container are not same as required by my bundle.
For example, lets take the case of cq-commons dependency.
AEM6.2 supports 5.9.22 version of cq-commons dependency.
AEM6.1 supports 5.8.32 version of cq-commons dependency.
AEM6.0 supports 5.7.12 version of cq-commons dependency.
AEM5.6.1 supports 5.6.4 version of cq-commons dependency.

Because of these different versions some of my java packages (com.day.commons.jcr) were not getting resolved.

Solution

Here are the list of steps, I followed, to resolve this issue.

Step 1

I have chosen the lowest version of available dependency i.e. 5.6.4 and added a dependency entry in the parent pom.xml file.

Step 2

I defined a property in <properties> section in my parent pom.xml file as mentioned below.
Note: – you can use whatever tag name you want but to make it readable I used this name.

Step 3

I have updated my <maven-bundle-plugin> as shown below-
Here I have used <DynamicImport-Package> tag. Now I have built my project for different AEM versions and it works fine for me in all AEM versions.

Here is the list of questions that may come in your mind:

Q1). What exactly <DynamicImport-Package> tag do?

It will add an entry in MANIFEST.MF file for the packages you mentioned in <bundle.dynamicImport.package> tag. MANIFEST.MF file entry is-

Q2). How bundle start working after using the <DynamicImport-Package> tag?

For answering this question-
First, we need to know about, How OSGi container works?
So, When you deploy your bundle into AEM OSGi container then first OSGi container checks that the available Java Packages versions are compatible with the versions of packages listed in Import-Package tag of your bundle MANIFEST.MF file. If version of Import-Package is not present then you will get an error as written below-

But if you defined these packages in <DynamicImport-Package> tag then OSGi container will not perform the versions checking for these packages and provides the available package definitions to your bundle at runtime.
i.e. using <DynamicImport-Package> is a kind of hack that short-circuits OSGi version checking process.

Note:- It is not recommended to use <DynamicImport-Package> with OSGi container.

Q3). Could we add multiple entries in <bundle.dynamicImport.package> tag?

Yes, you can add multiple packages using comma( “,”) delimiter. for ex.