Monday, July 17, 2017

AEM 6.3 Forms

AEM 6.3 Forms

In following post you'll find all the details you required for AEM 6.3 forms.

There are three form types  

- HTML forms
- PDF forms
- Adaptive forms

Forms support following features 
  • Dynamic layout
  • Form field validation
  • Context-sensitive Help
  • Scripting and XML data handling
  • Accessibility design and checking
  • Ability to save forms on the server-side
  • Support for file attachments
  • Integration with HTML Workspace for Data Capture
Forms allow offline data collection. The data can be collected offline and synchronized when the device is online. Forms Workspace is mobile application that is used for this.

Thursday, May 11, 2017

AEM 6 Advanced Interview Questions Part 4 (Asked in TCS)

AEM 6 Advanced Interview Quesitons Part 4 (Asked in TCS)

Here in this post "AEM 6 Advanced Interview Questions Part 4 (Asked in TCS)" I will be reiterating the questions asked in TCS interview.


1. Explain the entire process of replication with respect to the data flow.
A :
  • the author requests that certain content be published (activated); this can be initiated by a manual request, or by automatic triggers which have been preconfigured.
  • the request is passed to the appropriate default replication agent; an environment can have several default agents which will always be selected for such actions. These agent use buildContent method to build the content for replication. This method uses session for the read and write from the content repository. Also the replication agent has method replicate that take replication content, type and options are arguments. In case this method fails to replicate the content, they are stored in replication queue. A prceprocessor is used before the replication, which performs the actions like creating versions of the pages before replication. It also checks the permissions. A replicationContentFilter is used for filtering out contents before the replication. i.e. to check if a child of a page should be replicated or not. This filter uses replication filter chain.
  • the replication agent "packages" the content and places it in the replication queue.
  • in the Websites tab the colored status indicator is set for the individual pages.
  • the content is lifted from the queue and transported to the publish environment using the configured protocol; usually this is HTTP.
  • a servlet in the publish environment receives the request and publishes the received content; the default servlet is http://localhost:4503/bin/receive.
  • multiple author and publish environments can be configured.
  • Features such as comments and forms, allow users to enter information on a publish instance. For this a type of replication is needed to return this information to the author environment, from where it is redistributed to other publish environments. However, due to security considerations, any traffic from the publish to the author environment must be strictly controlled.
  • This is known as reverse replication and functions using an agent in the publish environment which references the author environment. This agent places the input into an outbox. This outbox is matched with replication listeners in the author environment. The listeners (PollingTransportHandler) poll the outboxes to collect any input made and then distribute it as necessary. This ensures that the author environment controls all traffic.

2. Explain serialization types in detail. And how they're handled.
A :
Defualt : For the default replication as explained above.
Dispatcher Flusher : For the dispatcher cache flush.
Binary less : To make the publish instance point to the same author datastore in order to reduce the storage cost and time taken to activate the pages. To use binary less, change the data store to filedatasote in repository.xml and then point all the instances to the same filedatastore on the network.
Static Content Builder : For the file system view of repository

3. How to get the properties in activate method.
A :
PropertiesUtil.toStringArray(componentContext.getProperties().get(name),type);

4. Explain the difference between workflow launcher and sling event listener and observation manager with respect to their performance.
A :
- Workflow launcher is used at AEM level : This is an ideal way of listening the events. They are cluster aware and are at AEM level. This is well documented and is useful when there are more customized non admin users.

- Event Listener (Handler) is used at Sling level : these are application level events. These events must have topic registered to them. Here the event can be sent by EventAdmin either synchronously or asynchronously. postEvent for async and sendEvent API for sync. An event handler can listen to such events as well as replication events. Events get black listed in case the specified time in EventAdmin is atained before the event is handled by the event handler. Also it should be noted that the handler is called for each and every event. There can be event filter used to avoid the same this will ensure event admin will check the filter parameter before calling the event handler.

- Observation manager is used at JCR level : This is done at the lowest level i.e. node level. Like node added, property added etc. A live session is required for this one to listen to repository. These listeners are not cluster aware, each time a change is made in nodes, the code will execute n times as per the no of clusters.

There are two more ways :

- Scheduled events
- Post to repository


5. TarMK vs MongoMK. Which one to prefer when?
A : MongoMK provides better scalability and TarMK provides better performance. Based on the number of author instances required one can make choice of MongoMK or TarMK. i.e. when there's requirement of more than one author instance, MongoMK is the answer. If there are huge number of page updates in a day, TarMK is the right choice. Also the choice of underlying database depends upon the number of concurrent users, number of assets, number of page edits, number of searches per day. In case of publish instance, the selection of MongoMK or TarMK should be based on the fact if there's any user generated contents or not. So if the site requires users generated contents go for MongoMK.


6. Explain content builder and it's methods.
A: A ContentBuilder assembles data for the replication. It contains two variations of create method and getTitle and getName method. The content builder is registered with the name property.

7. Global objects

8. What is the usage of SlingSafeMethodsServlet?
A:
  • Read only
  • Doesn't support post put delete
  • Supports get, head, trace, options
9. What is the usage of SlingAllMethodsServlet?
A:
  • Used for data modifying servlets
  • Supports all methods inclusing post, put and delete


10. What is Tar farm?

11. What is fragment in OSGI bundles?
A : Fragments are used to customize and osgi bundle. They are dependent upon the host bundle and they use the same classloader as host bundle.

12. What is bundle context and what is component context?
A :

13. How are the big size images being replicated on publish?
A : Use binary less replication. This will mean the same data is shared to used on author and publisher instances and no copies will be created. Binary less ensures only meta data are copied and shared amongst the instances. TarMK should be the choice since binary less is used here.

14. Your system architecture in terms of author publisher servers.
A : Please prepare this answer according to your system.

15. How is the load balancing done on publishers with different dispatchers?
A : refer https://cqdump.wordpress.com/2015/01/12/connecting-dispatchers-and-publishers/

16. If there are multiple instances of a service implementations, which one will be picked up? The one that is used recently or the one that is older.
A : service with highest service ranking will be picked up. If there are more than one service implementation with the same service ranking then the lowest service id will be picked up. Also if you have specific requirement of service being used. There should be a service type defined as propery and the same should be called usin

16. Why sling?
A : Sling is a web application frame work based on RESTful API which provides the easy development of content centric system.

17. Why JCR?
A : Sling uses JCR repository like jackrabbit or in case of AEM it is CRX.

18. Why OSGI?
A :
  • Defines architecture for the moduler applications
  • Dynamic discovery of service and contract
  • Allows dynamic loading, unloading and configuration of the controls of the bundle

19. Why Sling API is preferred over JCR?
A : Higher level APIs like Sling API provides easy way of accessing the data. It is more readable, maintainable and productive. This reduces the boilerplate code. Exceptions are handled elegantly. They have more useful and new features included.

20. What is new in AEM 6.4?

21. How are the Replication Queues maintained in case of system failure?

A : The replication queue is stored in /var/replication/data and are retrieved from this location in case of system failure.

Also AEM uses a proprietary binary format for replication called Durbo. Durbo includes the necessary checksumming to ensure that replicated content is not corrupted during transport.

22. Managing repository growth.

A first of all, the root cause of the repository growth has to be identified. Following steps can be taken for the same.

1.
Configure a logger - org.apache.jackrabbit.oak.jcr.operations.writes at traces log level in  http://aemhost:port/system/console/slinglog

2. Run the disk usage report at - http://host:port/etc/reports/diskusage.html

3. Perform following

CPU Profiling, capturing thread dumps, Analysing AEM thread dump


23. Tell about some of the Sling API you've used.

ResourceResolver
ValueMap
Resource
ResourceWrapper

24. Why OAK?

25. Why do we need component and why do we need service?

26. Explain Query API in detail in java.

27. Explain how the permissions are evaluated on a node/page with internal logic.

28. How is micro kernel different from persistence manager?

29. Indexing in AEM.

Monday, May 1, 2017

AEM 6 Campaign and Segments Interview Questions

AEM 6 Campaign and Segments Interview Questions

What is campaign?

Collection of individual Experiences

What is brand?

Brand is collection of campaigns.

What is experiences?

Focused content form various experiences those define personalized pages or touchpoints to the users. following are the types of experiences.


  • Teasers : Teasers are used to steer the specific visitor focus to their interest pages. Teasers are used for collecting user information like short registration forms. They are active only for short time or until the other teaser takes place.
  • News letters : Are used for encouraging the users to visit your website using the data generated in leads.
  • Test & Targets : provides one intuitive interface to design and execute tests and target the right audience using contents all using a single application.


What is touchpoint?

Connection point between the audience and the campaign.

What is leads?

Leads are the details of the users/audiences along with their communication means those are collected through the forms via campaigns.

What is lists?

Lists are the groups of leads/audiences divided according to the specific characteristics.

What is segment?

Segments are the definitions of the targeted audiences for a campaign based on the details relating a customer/user and their interests or activities through site those are collected on the basis of their profiles/inputs.

What is strategies?

A strategy is the criteria that is used for identifying a teaser to be resolved on a page. There are three strategies.

  • Random
  • First 
  • Click stream score : This is based on tags. 
What is landing page?

End point for the marketing outreach. They define the task that should be fulfilled by the visitor to consider the success of landing page.

What are the components of landing page?
  • Textbox
  • Title
  • Click to Action components - click through link and graphical link

What are the components of CTA lead form?
  • About
  • Address
  • Date of birth
  • Email id
  • First name
  • Last name
  • Gender

What are the steps for creating a lead form?
  • create importer page
  • prepare the html for importing
  • import the design package

What are target offers?

Segmentation terminology and their meanings.

  • Visitor
  • User
  • Trait
  • Segment
  • Behavioral traits
  • Demographic traits
  • Derived traits
  • Subsegment
  • Campaign
  • Teaser page
  • Teaser paragraph









Tuesday, April 25, 2017

AEM 6 QueryBuilder API in brief

AEM 6 QueryBuilder API in brief

Base Path :

http://host:port/bin/querybuilder.json

The query parameters are added after this path in order to search for specific results.

Parameters can be :

path
The path in content repository where you want to search for the results

p.limit(=number)
To limit the parameters. Setting p.limit=-1 will give all the possible results.

p.guessTotal(=true/false or number)
This parameter should be used with large number of result set. When set to true, the query builder returns the appropriate results on the basis of the value of p.offset and p.limit. 
the actual total number of results might not be visible to the user but the minimum number of results will be visible as total number which is the value of this parameter if it is set as number.

type(=cq type of the node like cq:File, nt:unstructured)
Node type of the crx node

nodename(=anystring)
Name of the node. This can accept wild card value like *.jar

orderby(=pathToNodeOrProperty)
This parameter can take node as well as propery to order the results. i.e.
orderby=@jcr:content/cq:lastModified

You can also provide the sorting order like
orderby.sort=desc/asc 

By default it is ascending order

fulltext(=anystring)
To perform a full text search in name, title and path

tagid=(IdOfTheTag)
To search for the pages with specific tag. Also, this can have filter on property as follows.
tagid.property=jcr:content/cq:tags
By default tagid.property will be cq:tags

tag=(titleOfTag)
To search on the basis of tag name

Searching at Multiple Paths
You can add multiple paths as follows
group.1_path=/content/abc
group.a_path=/content/xyz

By default the value of operator here will be add. This can be changed by setting the value of p.or=true which will make sure the search result is present in 1_path or 2_path

property(=nameOfProperty)
Search is performed on the basis of give property. If the property is existing the page, it will be added in the search results.
Additionally you can also provide the value of property as filter i.e.
property.value(=valueOfProperty)


Searching on Multiple Properties
You can search on multiple properties and values as follows. This will have and operation applied.
1_property=nameOfProperty1
1_property.value=valueOfProperty1
2_property=nameOfProperty2
2_property.value=valueOfProperty2


Also you can have multiple values to the property. Which will have or operation applied.
property=nameOfProperty
property.1_value=value1OfProperty
property.2_value=value2OfProperty

p.hits(=full/selective) 
The value full will mean all the properties of the searched pages will be returned and the value selective mean only the selected properties will be shown. i.e.
p.hits=selective
p.properties=jcr:path , jcr:title (Note the speace before and after comma )

p.nodepath(=number)
The number of level upto which the search should be performed. Considering path as the 0 level.

Debugging the query
For query debugging following link can be accessed from your instance of AEM

http://<host>:<port>/libs/cq/search/content/querydebug.html







Monday, April 24, 2017

AEM 6 Advanced Interview Questions Part 3

AEM 6 Advanced Interview Questions Part 3


1. What will be your approach to implement a website that is compatible to desktop, mobiles and tablets?
A:
  • Make your website responsive
  • Create your pages in HTML 5, so that they can be easily adapted by any devices. i.e. <!DCOTYPE html> should be the first line of your page.
  • Use Media queries
  • Add devices list for simulation in side kick by adding jsp - /libs/wcm/mobile/components/simulator/simulator.jsp
  • Register your page components for simulation. In config node add an entry for MobileEmulatorProvider. Set a property mobile:resourceTypes and add the pages as multistring values.
  • Implement adaptive images

2. Explain FileVault.
A : FileVault is the tool developed by adobe to map your file system content with crx. It is same as source control system which provides check-in check-out features.

3.Explain QueryBuilder API.


4. What is link-checker in AEM?
A : A link checker is provided with AEM. It checks all the content pages and prepares the list of valid and invalid links. It also makes invalid links on site on all the content pages. Link checker can be accessed using tools menu. One can disable the link checker pragmatically by loading the LinkCheckerSettings object and setting the value of ignoreExternals as follows.

if(isPublish) {
LinkCheckerSettings s = LinkCheckerSettings.fromRequest(slingRequest);
s.setIgnoreExternals(true);
}

Link checker transformer can be set using configMgr to configure link checker.


5. How static image rendering works in AEM?
A : AEM provides an image component that can be used to render the images. Using this component author can configure the image file source and the other parameters. When the jsp/html page is acessed, the image servlet creates an img tag to insert the image. This tag renders the image as per the value of src which is actually file source with a unique selector.

Adaptive image rendering servlet is used for setting the image resolution according to the device size. The JSP in this component adds div elements to provide the different resolution and renditions of the image as per device screen size.

6.  Explain some of the xtypes and their corresponding CQ types.
A :
textfield -> TextField
pathfield -> PathField
spinner -> Spinner
spacer -> Spacer
tabpanel -> TabPanel
dialog -> Dialog
datefield -> DateField
datepicker -> DatePicker
checkbox -> CheckBox
checkboxgroup -> CheckBoxGroup
radio -> Radio
radiogroup -> RadioGroup
multifield -> MultiField

7. What are the developer tools provided by AEM?
A :
FlieVault
Dialog editor
Translator
Site Importer
CRXDE
Package Manager

8. Externalizer in AEM.
A : Externalizer allows to create absolute urls. One can create links based on the server instance line authorLink, publishLink, externalLink, absoluteLink. Externalizer can be configured in configMgr


Monday, April 17, 2017

AEM 6 Sightly

AEM 6 Sightly



Notes :
  • Sightly pages are written in HTL which is HTML template language. 
  • HTL is made simple so that it is easy to use by web developers as well as backend developers.
  • HTL makes use of HTML5
  • HTL pages are compiled as java serlvets and it is evaluated at server side. 
  • HTL is capable of applying proper context to the data which means it is more secure than JSP.
  • HTL can include a jsp file 
  • HTL block statements can not be defined inside script, style or html comments.
  • Context aware escaping that saves from cross site scripting attacks.
  • Javascript USE api is evaluated by serverside javascript engine.
  • HTL removes empty elements automatically
Block Statements :
  • data-sly-use
  • data-sly-unwrap
  • data-sly-call
  • data-sly-template
  • data-sly-text
  • data-slty-attribute
  • data-sly-test
  • data-sly-list
  • data-sly-resource
  • data-sly-include
Expressions :
  • ${name}
  • ${currentPage.title} or ${currentPage["title"]} or ${currentPage['title']}
  • ${true} or {false}
  • ${45}
  • ${"test"}
  • ${[1,2,3,4]}
  • ${array[1]}
  • ${!true}
  • ${ a > b}
  • ${a && b}
  • ${a || b }
  • ${ a < b ? a : b }
  • ${a == b}
  • ${a != b}
  • ${a @ test='test'}
  • $ {['a','b'] @ join=", "}





Sunday, April 16, 2017

AEM 6 Advanced Interview Questions Part 2

AEM 6 Advanced Interview Questions Part 2


1. What is the role of persistence manager, data store, journal and indexes?
A: Persistence manager is used for storing the data in the repository. By Default AEM uses Tar persistence manager, which uses Linux's standard type of archive files - Tar. 
A data store is used for storing large contents. When the data is too big, it is not directly stored in persistence manger's storage but instead stored in data store and only the reference to this data is stored in persistence manager.
Journal helps in maintaining the data consistency and helps in system recovery from crashes. This also helps in synchronizing the cluster data.
Indexes are used for fast lookups of data for search and other function.

2. How to implement etc/mapping?
A : Inside /etc create a sling:Folder with the name map
Inside this folder create a sling:Folder with the name http
Inside this folder define sling:mapping node with the properties sling:match and sling:internalRedirect. Here sling:match is the request that is to be matched with respect to the actual website and sling:internalRedirect suggests the sling where the request should be redirected in AEM (say inside /content) or sling:redirect that suggests the sling where the request should be redirected outside the AEM.
These properties use regex to match with the url paths.

3. Explain design_dialog.
A : A design_dialog is used for the configuration of components on design level i.e. the site level. A design_dialog can be defined as cq:dialog just under the component node and can be accessed in design mode. A design dialog can have similar configurations as a dialog.

4. What is personalization?
A : Personalization provides the users with contents tailor made for them. There are three main components of it.
  • Users 
  • Content
  • Personalization rules
AEM provides a built in targeting engine that presents the personalized contents to the users.

5. How would you pass parameters to sling model from Sightly?
A: Following is the example how this can be done.

in Sightly template

<div data-sly-use.model3="${'org.example.models.Model3' @ colour='red', path=resource.path}">
${model3.shine}
</div>

In sling model class

@Inject
private String colour;

@Inject
private String path;


6. How would you design a global header and footer? Can you explain the same with the example of SDI?

7. How to configure WebDav and advantage of it?
A : You can configure WebDav using this link - 

The advantages of using WebDav is that the drive folder structure is mapped to AEM and you can upload larger DAM assets easily.

8. Why sling models are preferred on WCM Use API?
A : Following are the advantages of using sling models.
  • Easy to inject parameters
  • Easy to extend from other sling models
  • Simple set up for unit testing.
9. How do you transfer group permissions from one environment to another?

10. Purpose of servlet engine? Explain the same with respect to AEM 6.
A : Prior to AEM 6 the CQ5 used CQSE which is CQ Servlet engine. Which is replaced by Eclipse Jetty in AEM 6 version.
A servlet engine is used for handling servlet life cycle. Jetty can be configured in configMgr at org.apache.felix.http. AEM can also run on other application servers. For which you have to create a war file. You can configure the run mode of the war file in web.xml file.You can deploy publish and author instances both on the same application server.

11. Explain policy=ConfigurationPolicy.REQUIRE in @component.
A: ConfigurationPolicy defines the component's configuration policy. There are three values - OPTIONAL, REQUIRE and IGNORE. Here, REQUIRE means the configuration should be available in config node that is used for configuring run mode configuration.

12. What is ACL and ACEs?
A: ACL is access control list. It is implementation of AbstractAccessControlList which implements JCR's JackrabbitAccessControlList.The default implementation is nodeACL and principalACL.

ACE is access control entry. Which is implementation of AbstractAccessControlEntry. It contains restrictions and principals.

An ACE can be defined for a page in crxde lite environment under local access control policy. There are three types of access control policies here. Applicable access control policy, local access control policy and effective access control policy which can be of the current node or inherited from the parent.

There are priviledges like jcr:read, jcr:write, jcr:all,jcr: replicate,jcr:readAccessControl, jcr:modifyAccessControl, jcr:addChildNodes etc. And these priviledges are granted to the user/groups.

13. How to enforce UPDATE startup mode in AEM?
A: There are following ways of doing it.
  • By changing the jar file with higher version and starting the instance. This will start the UPDATE startup mode.
  • While starting the instance using java argument -Dorg.apache.sling.launchpad.startupmode=update

14. What is the difference between Tar Persistence manager and RDMS persistence manager?
A :
  • Tar PM is designed specifically for JCR repository.
  • Tar files are easy to backup.
  • Tar is platform independent format.
  • It can be accessed via standard zip tools like winzip.
  • It is based on key-value pair structure.
15. What is ACS? name and explain some of the features provided by it.
A: ACS is a bootstrap project with common AEM functionality and a set of components and AEM development toolkit.

  • It provides Dispatcher Flusher UI which can be used for flushing the cache manually.
  • Provides commons utils like CookieUtils, PathInfoUtil, OsgiUtil etc.
  • Also provide convenient way of exporting users in csv files.
16. How to implement a servlet in AEM?
A : A sling servlet can be registered as Sling service using @SlingServlet annotation. Which has properties like resourceType, name, description, selectors, extensions, methods. A servlet can have either resourceType of path. The path has to be starting with /bin which restricts the servlet to be used in publish instance. The servlet extends SlingSafeMethodsServlet or SlingAllMethodServlet however, it is not mendatory. SlingAllMethodServlet should be preferred when the data modification is intended.
This servlet can be called using jquery on the dialog box in order to retrive appropriate values in the dialog box and also can be used for inserting data input from forms.

17. Maven plugin for build AEM project.
A: maven-bundle-plugin

18. How is sling model mapped to sighlty page?
A : The java class that is declared as sling model should have the annotation @model with the value of adaptables which can be anything like resource or request.
This model class then can be initialized in the sightly page using <div data-sly-use.name="packagepath.class">... </div>

19. List down sling model annotations.
A :

  • Model 
  • Inject
  • Optional
  • Default
  • Named
  • Via
  • Source
  • PostConstruct
  • Self
  • SlingObject
  • ResourcePath
  • OsgiService
  • ValuesMapValue
  • RequestAttribute
20. What is script-bindings?
A : Script binding is the object which has all the variables and their values that is used for execution of the script.

21. Explain sightly templates.
A : Sightly templates are the functions or reusable html code that can be called with different values of parameters.
e.g.

 Non-parameterized template

<div data-sly-template.one>
some html code
</div>

<div data-sly-call="${one}">

Parameterized template

<div data-sly-template.paramTemp={@ a, b, c}>
 <a href="a" alt="b">c </a>
</div>

<div data-sly-call={paramTemp @  a="test.com", b="test", c="click here"}>
</div>

22.How to find maven dependency?
A: http://<host>:<port>/system/console/depfinder

23. How to see sling etc mappings?
A:http://<host>:<port>/system/console/jcrresolver

24. How to access sling model class in JSP?
<c:set var="class" value="<%=resource.adaptTo(class.class)%>">
or
<sling:adaptTo var="class" adaptable="${resource}"adaptTo="packagepath.class" >





All about cq:editConfig

All about cq:editConfig


cq:editConfig is the node with the type cq:editConfig and name cq:editConfig that is defined under the component node. There are different configuration/properties those can be configured with cq:editConfig in order to render the dialog in required way. 

  • cq:layout specifies how the component is edited in classic UI. The possible values are rollover, editbar, auto.
  • cq:dialogMode specifies how the dialog is opened in classic UI. The possible values are floating, rollover and auto.
  • cq:emptyText specifies the text to be displayed when the component is empty.
  • cq:inherit specifies if the values should be inherited from the parent in case they are missing. This can be true or false. 
  • cq:actions specifies the comma separated list of actions those can be performed on the component. This also allow a user to set the label of dialog. These actions are - insert, edit, delete, - , text:value, copymove. All of these should be configued as string array.
cq:editConfig has following child nodes those define the extra behavior configuration for the component. All of these are of the type nt:unstructured except cq:inplaceEditing and cq:listeners which has the type cq:inplaceEditingConfig and cq:editListnersConfig respectively.
  • cq:dropTargets specifies the list of drop targets from the asset finder that can be draged. It should have the child node of cq:dropTargetConfig which has properties - accept, groups and propertyName defined. 
  • cq:actionsConfigs specifies the custom actions that can be defined and listed in cq:actions property of cq:editConfig. For each custom action there should be a new node created under this of type nt:unstructured. This node should have properties like handler and text that defines the action to be performed. handler property can have the ExtJs function.
  • cq:formParameters defines the addtional parameters those are added to the dialog.
  • cq:inplaceEditing defines the inplace editing for the component. The properties those can be configured for this are - active, configPath and editorType. Where in editorType can be text, plaintext, title, begins.
  • cq:listeners specifies the actions those should be taken when the component is changed. The events those are captured by listeners are - beforedelete, beforeedit, beforecopy, beforemove, beforeinsert, beforechildinsert, afterdelete, afteredit, aftercopy, aftermove, afterinsert, afterchildinsert.

AEM 6 Dispatcher Configuration Simplified

AEM 6 Dispatcher configuration


There are two main usage of dispatcher.

1. Load balancing
2. Cache management


Following are the main AEM 6 dispatcher configurations required for cache management that one must have in mind while configuring dispatcher.any file. 

First thing is /name which specifies the name of configuration. Once can select whichever name makes most sense according to the environment in which this is configured.

After /name there should be /farms defined. All the other dispatcher related configurations go inside this one as follows.

/farms
 {
   /website 
     {  
     /clientheaders
       {
       }
     /virtualhosts
       {
       }
     /sessionmanagement 
       {
       }
     /renders
       {
       }
     /filter
       {
       }
     /vanity-urls
       {
       }
     /cache
       {
       /rules
         {
         }
       /invalidate
         {
         }
       }
     /statistics
       {
       /categories
         {
         }
       }
     /stickyConnectionsFor
     /health_check
       {
       }
     /retryDelay
     /numberOfRetries
     /unavailablePenalty
     /failover
     }
}
  • Here /website can be any label like /mysite /abcxyz. This just defines the block of configuration that will be applied on a site.
  • Inside /clientheaders one can define the pages headers those should be allowed to be accessed.
  • Inside /virtualhosts one can define for which all virtual hosts the dispatcher can render the pages.
  • Inside /sessionmanagement has sub sections like /directory which specifies where the session management details should be stored. /encode that defines how to encode the details. /header is the cookie/header that contains the authorization details and /timeout that specifies the session timeout.
  • /renders specifies which ip/host and port should be used for rendering the pages. i.e. publish ip/host and port number. There can be multiple entries defined here.
  • /filter specifies which kind of requests/pages should be filtered for rendering. This also uses details like /url, /protocol, /method, /extension, /path, /selectors, /suffix as more configuration options.
  • /vanity_urls can be configured to allow access to vanity urls. Here /file specifies the file where dispatcher keeps the list of vanity urls.
  • /cache is the main configuration that has information on how the cache will be handled by dispatcher. It has 11 subsections. /docroot, /statfile, /statfileslevel, /rules, /invalidate, /allowAuthorized, /serverStaleOnError, /invalidateHandlers, /allowClients, /ignoreURLParams, /headers. 
    • /docroot specifies where the cache files will be stored. 
    • /statfile specifies the name of stat file to be used. 
    • /statfileslevel spefies the level of content hierarchy until which the statfile should be created. /rules specifies which files should be cached. 
    • /invalidate specifies which files should be eligible for the automatic invalidation. 
    • /allowAuthorized specifies if pages authorization headers should be cached. 
    • /serverStaleOnError says if the dispatcher should return stale pages when the server returns error.
    •  /invalidateHandlers allows to configure script that can be used when dispatcher invalidation is called.
    • /allowClients specifies which clients are allowed to flush the cache.
    • /ignoreUrlParams specifies which url parameters should be ignored which caching the pages. 
    • /headers allows you to define pages with which all headers should be cached by dispatcher.
  • /statistics allows you to define categories to be used for rendering the pages along with their statistics created by dispatcher. This allows only first 8 categories to be considered by dispatcher while rendering the pages from categories. Categories can be anything from html pages to scripts.
  • /stickyConnectionsFor is used to define for which pages sticky connections should be used. Sticky connections are the connections those require the requests to be served by the same publish instance for the same user. For example customer accounts page.
  • /health_check specifies the page that should be accessed while a 500 error occurs. If the specifies page also returns 500 error, then the configurable time penalty is applied before retrying.
  • /retryDelay specifies the time in seconds before there is retry for the server access.
  • /numberOfRetries number of retry performed by dispatcher for the renders.
  • /unavailablePenalty specifies the time delay before a retry is attempted by dispatcher.
  • /failOver this enables the dispatcher to divert the request to another server in case the number of retries fails for one.


Saturday, April 15, 2017

AEM 6 Advanced Interview Questions Part 1

AEM 6 Advanced Interview Questions Part 3


Here, I will try to list down some of the advanced AEM interview questions I have come across. Please correct my answers if required in the comments and I will do the changes accordingly.

1. Difference between service and component
A :
Service :
  • A service is an OSGI component that can be looked up from other OSGI components.
  • Any java object is eligible to be a service
  • All the services in OSGI are components
  • Services are maintained in service registry from which they can be looked up
Component :
  • A component is a java object whose life cycle is handled by the OSGI container.
  • Any java object is eligible to be a component
  • A component is not necessarily an OSGI service, however, to make it callable by other components it has to be declared as service.
2. How a class is made available to OSGI container?
A : By providing @component at the top of the class declaration

3. Do you always need @service and @component annotations for a class in OSGI?
A : No, a component may not be declared as an OSGI service. However, there is a requirement to consume/look up for the component in another component it has to be declared as @component.

4. How to debug a situation where a component is not configurable on ConfigMgr?
A : Following steps should be taken in order to ensure component is configurable

  • The attribute-value metadata=true of @component annotation is responsible to making the component configurable on ConfigMgr. That should be verified first.
  • If the component is using @reference to other service, they should be available to the component and should have been initialized
  • There should be configurable properties associated with the component using - @property or @properties 
5. What is the difference between Live Copy and Language Copy?
A : A Live Copy is the copy of blueprint/source with its live relation with the blueprint/source which means the changes in live copy and source are tracked. Source can be attached or detached or reattached or sync to the Live Copy. While a Language Copy is a static copy of some or all the pages of the source.

6. How Live Copy is connected to blueprint?
A : Using Rollout configuration the Live Copy can be configured to be updated automatically when a update in blueprint occurs.

7. MSM configuration.
Please refer - https://docs.adobe.com/docs/en/aem/6-0/administer/sites/multi-site-manager/msm-blueprints.html

8. How to configure run modes?
A : Run modes are configured in following ways.
  • Provide the run mode as name of AEM jar file e.g. cq6_publish_p4503.jar. Where publish is the run mode.
  • Provide property - sling.run.modes in sling.properties file
  • Provide run mode with java argument for example -Dsling.run.modes=publish
  • Provide -r <run mode> which starting the jar file using batch file
9. How is the configuration of AEM instance done according to run modes?
A : You can define a config (nt:folder) node inside your project folder - /apps/projectA and define configuration of a service/component by creating a node sling:OsgiConfig under it having the full qualifying name like org.apache.sling.jcr.resource.internal.JcrResourceResolverFactoryImpl. The configuration should be provided as the property of this node.



When you specify the run mode along with config separated by a dot, it becomes the configuration of a specific run mode and is used when that particular run mode is initialized. For example config.author will define configurations for author run mode.




10. What is the advantages of using Sightly?
A : Following are the advantages of using Sightly over JSP.
  • Easy and no requirement of knowing JAVA to use Sightly.
  • Protection against cross scripting.
  • Uses sightly context to output data in correct format.
  • Clear separation of client side and back end logic. No scriptlets.
  • Strong connection to Sling.
  • Has two ways of handling backend logic. WCM Use Java API and WCM Use Javascript API.
11. What is HTML (display) context in Sightly?
A : The display context of a content refers to its location where it is used in the page. HTL is capable of identifying the context of the output except in case of CSS and JS where in if required explicit context can be passed. This context is used to prevent XSS security problem. XSS is cross site scripting attack on the website, in which attacker can inject the custom script and attack the site. HTL gives protection from this by introducing display context. HTL is capable of identifying the context in link, text and title properties. There are several display contexts those can be used when required. Which are listed below.
  • text
  • html
  • attribute
  • uri
  • number
  • scriptToken
  • scriptString
  • scriptComment
  • styleToken
  •  styleString
  • styleComment
  • unsafe
  • attributeName
  • elementName
12. Why designs are different from clientlibs and why should clientlibs be defined outside designs?
A : Designs contain the details of site level configurations of the components along with it it can contain the clientlibs. However, when a clientlibs are configured in designs, it will be combined into one main.js/main.css and will be loaded each time a page is called. However, there are cases when not all the scripts/css are needed to be loaded on page as they are not used by the components. In such cases, the clientlibs can be defined along with the component and imported according to the requirement on the page. This will ensure only those client libs are called which are required by the page/components on the page and they are easy to maintain due to their clear separation according to the page.

13. What does clientlibs contain and what is embed, dependencies and categories?
A: Clientlibs contain js.txt, css.txt and the sources of javascript and css.
  • Categories specify the clientslibs required by the page
  • Dependencies specify the clientlibs those are required to run the clientlibs defined in categories and it means there will be an extra call made to load these clientlibs.
  • Embed specifies aggregating the clientlibs along with the defined in categories, this means they will be attached to the main clientlibs.

14. Difference between CRX2.0 and OAK (CRX3.0).
A:
  • CRX2.0 is the implementation of Jackrabbit while OAK is the implementation of Jackrabbit OAK
  • Since CRX2.0 is implementation of Jackrabbit, it uses JCR completely, while OAK uses JCR just as facades.
  • CRX2.0 has persistence manager (PM) which writes data as blob however, OAK has microkernel which writes data as per underlying DB.
  • CRX2.0 uses Lucene while OAK uses Solr.
  • CRX2.0 doesn't support clustering (i.e. distributed database across the servers) while OAK uses MongoDB like database which use clustering.


15. Difference between CQ5.6 and AEM6.1?
A:
  • Since AEM6.0 the touch UI is introduced which was not there in CQ5.6
  • AEM6.1 uses OAK which 5.6 uses CRX2.0 which is adobe's implementation of JCR.
  • Since AEM6.0 sightly is introduced as new markup language to facilitate the front end developers with page definitions which reduces the requirement of having developers with knowledge of java.
  • CQSE servlet engine has been replaced by Eclipse Jetty 

16. Do you always require @activate and @deactivate?
A : No. They indicate the methods required for pre or post processing of the components/services.

17. How do you use a service in a component?
A : The simplest way is to use @reference annotation and use the name of the service.
If the service needs to be used inside a jsp, you can use following syntax of code in scriptlet.

com.adobe.cq.KeyService keyService = sling.getService(com.adobe.cq.KeyService.class);

18. Explain dispatcher configurations (especially /filter)
A : Please refer - Dispatcher Configurations

19. Explain @reference annotation.
A: This annotation is used for injecting an OSGI service in OSGI component/service. Following are the different attributes used along with the annotation.

name : in case name of the service is different from the declared variable reference
interfaceName : interface name for the service.
policy : It can be one of ReferencePolicy.STATIC or ReferencePolicy.DYNAMIC. Where in dynamic means, if the reference service goes off, it is bound to the calling component/service when it is on again dynamically without the requirement of resetting the calling component/service. By default this value is always static, which means the calling component/service will not be up until the reference is resolved.
target : to select the referenced service.
strategy : one of event or lookup. This value defines how the reference will be resolved.

20. How sling does resource resolution?
A : There are three basic steps.

  • URL decomposition : The URL is decomposed in protocol, path, extension, selector, suffix and parameters.
  • ResourceType identification : Using the path sling decided at which location in content repository the page resource should be looked for. From there, the sling:resouceType of the page is extracted. In case sling:resouceType is not available, sling:superResourceType is looked for. Once the resourceType is determined say /apps/project/components/pages/componentA, the script is located inside the component definition in apps folder.
  • Script resolution : Here the priorities to the scripts are given as per the name, extension, method and type, which is as follows.
    • selector + extension + jsp/html
    • selector + jsp/html
    • extension + jsp
    • node name + jsp/html
    • method + jsp/html first GET/HEAD and then POST, DELETE etc. These names has to be in capitals.
21. Why a webservice consumer in AEM should be implemented at server side instead of client side?
A : One should be evaluating the output of webservice in order to decide if the consumer should be implemented at service side or client side. For example a webservice giving response in JSON can be better be consumed on the client side while a webservice giving response in XML format can be better consumed on the server side. Also, while implementing the consumer client side, one should consider the size of the response returned by the webservice. Large sized responses should be handled by the server side consumer.

22. Analytics integration.
A : Please refer - SiteCatalyst

23. Sling Dynamic Includes in AEM.
A : This is a separate project created to handle the situation when there is a page with most of the static components and a dynamic component. This enables the dispatcher to cache the static components of the page and load the dynamic components from the publish instance. This is done using a servlet filter that intercepts the request of a component with given resourceType.

Implementation and configuration details can be found at - SDI

24. How to provide different configuration of the same service dynamically?
A : This is done by adding configurationFactory=true as one of the attributes in @component annotation as given in following example.

@component(label = "test component", immediate = true, enabled = true,
metatype = true,
description = "Testing configuration factory",
policy = ConfigurationPolicy.REQUIRE, configurationFactory = true)

This will allow multiple configuration of the component/service by providing + sign at right side on the configMgr.

25. Why an out of the box component should not be altered?
A: The out of the box components are prone to change when a new service pack is installed or when a version upgrade is done or when a new update is provided to the AEM. This will remove the existing configurations done in the component in libs folder. The other reason is the component might have been used inside another project/component which may bring inconsistent behavior in the component that is using the altered component.

26. How to create an overlay component?
A :An overlay component is created by copy pasting the component from \libs to \apps with exact path of the component and doing required changes.

27. How to create an overriden component?
A : A component can be overriden by creating a new component and providing sling:resourseSuperType property.

28. How to create a custom event handler?
A : Define a class that extends EventListner and implement the required method activate method which takes ComponentContext as the argument.

Using session, you can fetch the observation manager like

session.getWorkSpace().getObservationManager()

Using this observation manager you can add event listener with arguments like path, type, event (Node added,  node removed, node moved, persist, property added, property changed, property removed)


Wednesday, February 15, 2017

Custom Transport Handler in CQ/AEM6

Custom Transport Handler in CQ5.6/AEM6


There are a lot of blogs written on this one. However, none of them explain about how it should be unit tested and what are the point a programmer should have in mind while using a custom transport handler. I am going to list down few of them below.

1. There must be a custom ContentBuilder defined. An example definition could be as follows.

@Component(metatype = false)
@Service(ContentBuilder.class)
@Property(name = "name", value = "Custom Content Builder")
public class CustomContentBuilder implements ContentBuilder {
public static final String NAME = "Custom Content Builder";
public static final String TITLE = "Custom Content Builder";
public ReplicationContent create(Session session, ReplicationAction action,
ReplicationContentFactory factory) throws ReplicationException {
return ReplicationContent.VOID;
}
public String getName() {
return TITLE;
}
public String getTitle() {
return TITLE;
}
public ReplicationContent create(Session session, ReplicationAction action,
ReplicationContentFactory factory, Map<String, Object> arg3){
// TODO Auto-generated method stub
return ReplicationContent.VOID;
}
}
2. While defining your agent in author agents that uses your custom transport handler, select your custom content builder's name i.e.  in above case it is "Custom Content Builder" as a value of Synchronization Type.


In above example instead of default it should be "Custom Content Builder"

Notes : The custom handler can be invoked on the author environment by invoking activate request on the page. This works fine even when the custom handler is configured on the publish side and the request is invoked from author side in case of AEM 6.0 but, this will not work fine in CQ5.6


Monday, January 30, 2017

Programmatic Cache Invalidation in AEM 6

Programmatic Cache Invalidation in AEM 6


There are three ways of doing it.

1. By sending post request to the dispatcher cache invalidation URL as follows.

                HttpClient client = new HttpClient();
HostConfiguration configuration = new HostConfiguration();
                // This uri is http://dispatcherhost:dispatcherport/dispatcher/invalidate.cache
                // Without this host configuration there will be and exception with the message "Host is null"
configuration.setHost(uri);
client.setHostConfiguration(configuration);
PostMethod post = new PostMethod(uri);
                // CQ-Action:Delete will delete the cache from dispatcher.
                // For cache invalidation Activate action should be used.
post.setRequestHeader("CQ-Action", "Activate");
                // pagePath specifies the page that needs to be invalidated
post.setRequestHeader("CQ-Handle", pagePath);
StringRequestEntity body = new StringRequestEntity(pagePath, null, null);
post.setRequestEntity(body);
post.setRequestHeader("Content-length",String.valueOf(body.getContentLength()));
client.executeMethod(post);
post.releaseConnection();

2. Using DispatcherFlusher provided by ACS commons.

First make reference to DispatcherFlusher

       @Reference
      private DispatcherFlusher dispatcherFlusher;

Next make use of it to flush the cache

             dispatcherFlusher.flush(getResourceResolver(repo.loginAdministrative(null)), pagePath);

3. FlushService (Available in AEM 6.2+ versions)
   
             FlushService flushService = sling.getService(Replicator.class);
             flushService.sendFlushUrl("admin",FlushService.FlushType.IMMEDIATE_FLUSH, pagePath,FlushService.RefetchType.IMMEDIATE_REFETCH,new String[] {pagePath});






Some more AEM 6 Interview Questions for Architects

 Some more AEM 6 Interview Questions for Architects 1. Consider you have a workflow with two steps. One step is to transfer the asset from s...