Sunteți pe pagina 1din 48

CQ5

What is CQ5? What is a Content Management


System?
Ans- CQ5 is a java based content management system from adobe, previously Day
CQ5.
1) It is based on a content repository(i.e it uses a content repository to store the
content of a website) and use JCR(java content repository) specification to access the
content repository.
2) It uses RESTful Apache Sling framework to map request url to the corresponding
node in content repository.
3) it uses OSGi framework to allow modular application development. It
means individual pieces of your application(called bundles in terms of OSGi) can be
independently started and stopped. CQ5 uses Apache Felix as the OSGi container.

why a content management system is required?


Ans- Some websites are very dynamic in nature, content needs to be updated
frequently, so it is easier to manage the content of such websites using a CMS.

Adobe CQ5 platform allows you to build content-centric applications that combine Web
Content Management, Workflow Management, Digital Asset Management and Social
Collaboration.

That is how, it deliver a global solution that allows companies to manage incredible
amounts of information, multiple internal and external websites, a myriad of media
assets, and detailed workflow

This product is used for increasing functionality while reducing complexity and use of
standards helps to ensure long-term stability.

3- What is the technology stack of cq5?


Cq5 uses the following technologies :

JCR 2.0 – java specification for accessing a content repository,

A- cq5 uses its own implementation of jcr called CRX.


B- Apache Jackrabbit is an open-source implementation of jcr 2.0 specification.

Apache Sling – RESTful framework to access a jcr over http protocol. It maps the
request url to the node in jcr.

OSGi – framework for modular application development using java. Each module called
bundle can be independently started and stopped.
4- What is a content repository? What is JCR?
A Content repository is basically a place where digital content is stored. The structure of
the content repository is hierarchial and represented as a tree structure where each
node of the tree is used to store content.

Java Content Repository is a specification provided by the java community to access


the content repository in a uniform way (platform independent and vendor independent
way). The specification was initially released as JSR-170(JCR 1.0) and then later
revised version 2 as (JCR-283). The javax.jcr API provides the various classes and
interfaces to access a content repository

Apache Jackrabbit is an open-source implementation of JCR- 2.0 specification.

It provides some wrapper classes and interfaces specific for many more functionalities
on top of jcr.

The org.apache.jackrabbit packages are used to access Jackrabbit.

5- What is REST? What is a RESTful Framework?


REST stands for Representational State Transfer. It is an architectural style where data and
functionality is considered as resources and accessed using a Uniform Resource Identifier
(URI).
REST-style architectures conventionally consist of clients and servers. Clients initiate requests to servers;
servers process requests and return appropriate responses. Requests and responses are built around
the transfer of representations of resources.

One more thing which differentiates as RESTful framework from other web-development frameworks is
that generally all web-development frameworks rely heavily only on HTTP Get and Post Requests. While
a restful leverages the maximum of http protocol. It uses all the types of http request (HEAD, GET, POST,
PUT, DELETE).
For example - consider a scenario where you want to delete a product from a product list with
product_id=111;

The server side code for the same will be somewhat like this if a HTTP GET request is sent from
client-browser with product_id=111 appended to the url.
public void doGet(HttpServletRequest request, HttpServletResponse response)
{

String prod_id = req.getParameter(“product_id”);

Connection con = DBConnection.getConnection();

Statement st = con.createStatement();

st.executeQuery(“delete * from product where product_id=’”+product_id+”’”);

As you can see in the above piece of code, we are using a GET request to perform a delete
operation on a resource. Therefore we are not using the real power of HTTP protocol. According
to REST principles, the same could have been done by sending a HTTP DELETE request from
client browser and at server side.

public void doDelete(HttpServletRequest request, HttpServletResponse response)


{

String prod_id = req.getParameter(“product_id”);

Connection con = DBConnection.getConnection();

Statement st = con.createStatement();

st.executeQuery(“delete * from product where product_id=’”+product_id+”’”);

Similarly to read a resource – use GET – scenario – get product details


create a new resource – POST – scenario – add a new product
update a resource – PUT - scenario – update an existing product details
get product meta information – use HEAD – scenario – reading the meta-information of products

According to the REST architecture, there are 6 constraints which should be followed:

Client–server
There should be a clear separation between a client and server.

Stateless

The client–server communication is further constrained by no client context being stored on the
server between requests. Each request from any client contains all of the information necessary
to service the request, and any session state is held in the client.

Cacheable

As on the World Wide Web, clients can cache responses. Responses must therefore, implicitly or
explicitly, define themselves as cacheable, or not, to prevent clients reusing stale or
inappropriate data in response to further requests. Well-managed caching partially or
completely eliminates some client–server interactions, further improving scalability and
performance.

Layered system

A client cannot ordinarily tell whether it is connected directly to the end server, or to an
intermediary along the way. Intermediary servers may improve system scalability by enabling
load-balancing and by providing shared caches. They may also enforce security policies.

Code on demand (optional)

Servers can temporarily extend or customize the functionality of a client by the transfer of
executable code. Examples of this may include compiled components such as Java applets and
client-side scripts such as JavaScript.

Uniform interface

The uniform interface between clients and servers, discussed below, simplifies and decouples
the architecture, which enables each part to evolve independently. The four guiding principles
of this interface are detailed below.

The only optional constraint of REST architecture is "code on demand". One can characterise
applications conforming to the REST constraints described in this section as "RESTful".[8] If a
service violates any of the required constraints, it cannot be considered RESTful.

Complying with these constraints, and thus conforming to the REST architectural-style, enables
any kind of distributed hypermedia system to have desirable emergent properties, such as
performance, scalability, simplicity, modifiability, visibility, portability, and reliability.
6- What is Sling? How is it different from other web-
development frameworks?
Apache Sling is RESTful framework to access a java content repository over http
protocol.

It is a content driven framework that is it maps the incoming user request based on URI
to the corresponding node in the content repository and depending on the type of the
request(GET,POST, etc) executes the corresponding dynamic script.

For example - consider a scenario where admin is hitting a Indian website admin page
and getting the details of admin.

The incoming URL request from user will be

www.example.com/pages/admin.html

This would be mapped by the sling resource resolver to a node in the JCR

/content/example/pages/admin

Now the Sling resource resolver will check the properties of this node and check the
sling:resourceType property of this node, which will tell the script that will be used to
render the content of this page.

For example if value of sling:resourceType property is


/apps/example/pages/GET/body.jsp

Then for all the incoming GET requests on the admin node, the above script will be
used to render the content.
The main advantages of sling are: it maps the url directly to the content. it is restful.

7- How is resource resolution done in Sling?


Consider the URL

GET – www.mywebsite.com/products/product1.printable.a4.html/a/b?x=12

Here the type of request will be HTTP GET request

In Apache Sling each (http) request is mapped onto a JCR resource, i.e. a repository node. This
is very different from other web frameworks you might be familiar with, say, Struts or Rails. In
these frameworks a request is mapped onto a controller, i.e. a url really addresses application
code, so the application developer usually implements some application logic that retrieves
model data and passes it on to the view.

Just like Rails or Struts, Sling implements a model-view-controller architecture. However,


in Sling a request addresses a piece of content. The mapping between request and
model (data, content) is accomplished through the url so there is no need for further
custom mapping logic.

Node selection

So, how does this work in detail? Consider an http GET request for the url:

/content/corporate/jobs/developer.html

First, Sling will look in the repository for a file located at exactly this location. If such a file is
found, it will be streamed into the response as is. This behavior allows you to use Sling as a
web server and store your web application's binary data in the repository as well.

However, if there is no file to be found Sling will look for a repository node located at:

/content/corporate/jobs/developer

(i.e. it drops the file extension). If this node cannot be found Sling will return the http code 404.

Script folders

The scripts that Sling uses to process http requests are stored in subfolders of "/apps". Those
subfolders are usually of type nt:folder, but that's not a requirement.

Script selection

Nodes can have a special property named "sling:resourceType" that determines the resource
type. assume that the resource type is, say, "hr/job". The selected script will then be
"/apps/hr/job/job.esp" (the last part of the resource type will have to be the file name). This
works for GET requests and URLs ending in ".html".

Requests using other request methods, say POST, will cause Sling to look for the script at
"/apps/hr/job/job.POST.esp". Request URLs ending in something else than ".html", say
".pdf", will make Sling look at "/apps/hr/job/job.pdf.esp". The convention to distinguish the
two cases is that http methods are all uppercase and the extension of the request is all
lowercase.

In a content-centric application the same content must often be displayed in different variations,
e.g. as a teaser view and as a detail view. In Sling this is achieved through selectors. The
selector is specified in the URL like e.g.
/content/corporate/jobs/developer.detail.html

For this URL Sling would locate the script at "/apps/hr/job/job.detail.esp"

If the selected resource has no special resource type a script will be looked up based on
the content path. For example, the script for /content/corporate/jobs.html will be
searched in /apps/corporate.

Script engine

The ".esp"(Encapsulated PostScript) extension of the scripts used in the examples above
indicates script engine to use. ".esp" stands for Ecma script and internally uses Rhino, Mozilla's
Javascript engine. Other supported extensions are ".rb" for JRuby scripts, ".jsp" for JSPs or
".jst" for client-side execution (".jst" denotes Javascript template).

Some interesting special cases

The examples above describe rendering nodes as html or as a pdf. Howevere, there are also
some built-in renderers for json and txt. The corresponding node presentations are located at
(using the example form above):

/content/corporate/jobs/developer.json

and

/content/corporate/jobs/developer.txt

respectively.

For http error handling (404 or 500) Sling will look for a script at
"/libs/sling/servlet/errorhandler/404.esp" and 500.esp, respectively.

(1) Script Location

Scripts to handle the processing or a resource are looked up in a single location:

{scriptPathPrefix}/{resourceTypePath}

Where {scriptPathPrefix} is an absolute path prefix (as per


ResourceResolver.getSearchPath()) to get absolute paths and {resourceTypePath} is
the resource type converted to a path. If the {resourceTypePath} is actually an absolute
path, the {scriptPathPrefix} is not used.

Example: Given the search path [ "/apps", "/libs" ] and a resource type of sling:sample,
the following locations will be searched for scripts:

* /aps/sling/sample
* /libs/sling/sample
(2) Within the location(s) found through above mechanism a script is searched whose
script name matches the pattern
{resourceTypeLabel}.{selectorString}.{requestMethod}.{requestExtension}.{scriptExte
nsion}

where the fields have the following meaning:

{resourceTypeLabel} - the last segment of the {resourceTypePath} (see above)


This part is required. Only scripts whose name starts with this name are
considerd
{selectorString} - the selector string as per RequestPathInfo.getSelectorString
This part is optional. The more selectors of the selector string match,
the
better.
{requestMethod}
The request method name. This is optionalfor GET or HEAD requests
and is required for non-GET/non-HEAD requests
{requestExtension}
The extension of the request. This is optional.
{scriptExtension}
The extension indicating the script language. Not used for selecting
the script but for selecting the ScriptEngine. This is of course not existing
for servlets.

If multiple scripts would apply for a given request, the script with the best match is
selected. Generally speaking a match is better if it is more specific. More in detail, a
match with more selector matches is better than a match with less selector
matches, regardless of any request extension or method name match.

For example, consider a request to resource /foo/bar.print.a4.html of type sling:sample.


Assuming we have the following list of scripts in the correct location:

(1) sample.esp
(2) sample.GET.esp
(3) sample.GET.html.esp
(4) sample.html.esp
(5) sample.print.esp
(6) sample.print.a4.esp
(7) sample.print.html.esp
(8) sample.print.GET.html.esp
(9) sample.print.a4.html.esp
(10) sample.print.a4.GET.html.esp
It would probably be (10) - (9) - (6) - (8) - (7) - (5) - (3) - (4) - (2) - (1). Note that (6) is a
better match than (8) because it matches more selectors even though (8) has a method
name and extension match where (6) does not.

If there is a catch, e.g. between print.esp and print.jsp, the first script in the listing would
be selected (of course, there should not be a catch...)

7- What is OSGi? What is the benefit of OSGi? What is


Felix?
Open Services Gateway Initiative----OSGi

OSGi is a framework which allows modular development of applications using


java.
A large application can be constructed using small reusable components(called bundles
in terms of OSGi) each of which can be independently started, stopped.

Consider a scenario where you have a large application which uses a logging
framework. This logging framework can be deployed as an OSGi Bundle, which can be
managed independently. Therefore, it can be started when required by our application
and can be stopped when not in use.

Also the OSGi container makes these bundles available as services, which can be
subscribed by other parts of application.
The main advantages of using OSGi :
1) reduces the complexity of the system.
2) Makes the components loosely couples and easy to manage.
3) Increases the performance of the system, since parts of application which are not in
use,need not to be loaded in the memory.

The OSGi Framework is made up of three layers -- Module, Lifecycle, and Services --
that define how extensible applications are built and deployed. The responsibilities of
the layers are:

Bundle = jar + OSGI information (specified in the JAR manifest file – META-INF/MANIFEST.MF)

Module --- Defines how a module, or a Bundle in OSGi-speak, is defined.


(difference between jar and OSGi)----
Basically, a bundle is just a plain old JAR file, whose manifest file has some defined
entries. These entries identify the bundle with a symbolic name, a version and list of
package which a bundle provides “Export-Package” and what a bundle requires to be
operative Import-Package and Require-Bundle.
Lifecycle --- The lifecycle layer defines the states a bundle may be in and describes
the state changes. By providing a class, which implements the BundleActivator
interface and which is named in the Bundle-Activator manifest header, a bundle may
hook into the lifecycle process when the bundle is started and stopped.
Services --- For the application to be able to interact, the OSGi Core Specification
defines the service layer. This describes a registry for services, which may be shared.

8. What are templates ?


A Template is used to create a Page and enables you to define a consistent style for the
pages in your application.. A template is a hierarchy of nodes that has the same structure
as the page to be created, but without any actual content.
Each Template will present you with a selection of components available for use.
• Templates are built up of Components;
• Components use, and allow access to, Widgets and these are used to render the
Content.

 If you want your template to be displayed in the Create Page dialog when
creating a page right under Websites from the Websites console, set the
allowedPaths property of the template node to: /content(/.*)?

Templates are used to create Pages of type cq:Page (as mentioned earlier, a Page
is a special type of Component). Each CQ Page has a structured node jcr:content.
This:
• is of type cq:PageContent
• is a structured node-type holding a defined content-definition
• has a property sling:resourceType to reference the component holding the sling
scripts used for rendering the content

9. What is Dispatcher ?What is the role of Dispatcher in


CQ5?
The Dispatcher is the Adobe caching and/or load balancing tool that helps
realize a fast and dynamic Web authoring environment.
For caching, the Dispatcher module uses the Web server's ability to serve static
content. The Dispatcher places the cached documents in the document root of the Web
server.
It has 2 responsibilities.
1) Caching – . For caching, the Dispatcher works as part of an HTTP server,
such as Apache, with the aim of storing (or "caching") as much of the static
website content as possible and accessing the website's layout engine as
infrequently as possible.
2) Load-balancing – In a load balancing role, the Dispatcher distributes user
requests (load) across different clustered CQ instances, To increase the
performance by load-balancing.

Dispatcher uses 2 main strategies for caching.


1) Cache as much content as possible as static pages.
2) Accessing layout engine as little as possible.

How does the Dispatcher perform caching?


The Dispatcher uses the web server's ability to serve static content. The Dispatcher
stores cached documents in the web server’s document root. The Dispatcher has
two primary methods for updating the cache content when changes are made to the
website.
Content Updates remove the pages that have changed, as well as files that are
directly associated with them.
Auto-Invalidation automatically invalidates those parts of the cache that may be
out of date after an update. For example, it effectively flags relevant pages as
being out of date, without deleting anything.

How does CQ perform load balancing?


The following list describes the advantages for load balancing:
In practice this means that the Dispatcher shares document requests between
several instances of CQ. The Dispatcher keeps internal statistics for each
document category, so it can estimate the load and distribute the queries
efficiently.
Performance Statistics -If the Dispatcher does not receive responses from an
instance, it will automatically relay requests to one of the other instance(s). Thus,
if an instance becomes unavailable, the only effect is a slowdown of the site.
Sticky Connections - when a user session is established, then all incoming requests
from that user should be served by the same cq instance, because other cq
instances cannot recognize the user session and generate personalized pages for
him. Dispatcher makes sure all requests for user session are served from the
same cq instance.
10. What is Replication? How is Content Moved from
author to publish instance?What is Activation?
https://docs.adobe.com/docs/v5_2/html-
resources/cq5_howto_replication_agents/ch01s02.ht
ml
https://docs.adobe.com/docs/en/cq/5-6-1/deploying/replication.html

1) Publish (activate) content from author to publish environment using replication agent.
2) Explicitly flush content from the dispatcher cache.
3) Return user input from the publish environment to the author environment.

REPLICATION PROCESS:

1) First, the author requests that certain content to be published (activated).


2) The request is passed to the appropriate default replication agent.
3) Replication agent packages the content and places it in the replication queue.
4) the content is lifted from the queue and transported to the publish environment using
the configured protocol.
5) a servlet in the publish environment receives the request and publishes the received
content, the default servlet is http://localhost:4502/bin/receive.

If any content is updated, then it flushes the older content from dispatcher cache, but it
won't put new content at the same time. New content will be fetched into cache, when the
next time it is requested.

A development environment can contain multiple cq-author and multiple cq-publish


instances, therefore an author instance can be configured to have many replication
agents. Each of which will replicate the content in 1 or more publish instances.

11. How is content moved from publish instance to


author instance?What is Reverse Replication?
Consider the scenario where your website is having a blog or a forum, and the users
are posting comments in the blog. Then that comments will only be in publish instance.
The content is moved from publish instance to author instance using reverse replication
and the job is done by reverse replication agent.
The reverse replication agent places any content updates in an outbox configured in
publish instance. The replication listeners in author environment keep listening to the
publish outbox and whenever any content is placed in publish outbox, the listeners
update the content in author instance.

12. What is persistence manager in cq5?


CQ uses persistence manager to save the content to a persistent storage like file
system or a database.
By default the crx content is stored using Tar Persistence manager. It stores the content
to file-system in standard linux archive files called tar.
if you want to store the repository content in a database, then you can configure cq5 to
use a database persistence manager.

What is the difference between 1. <c:import url="layout-


link.jsp" /> 2. <sling:include path="layout-link.jsp"
/> 3. <cq:include script="layout-link.jsp" />What is the
advantage of each tag? When should each be used?
CQ Include is most appropriate when you are doing standard component/template
development.
Sling include is most appropriate when you are trying to include a piece of content as
based strictly on sling resource resolution and not CQ component type logic.
1. <c:import url="layout-link.jsp" />
this is the import tag of the Standard Tag Library. This tag is documented
athttp://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/c/import.htmland does not know
about Sling directly.But this tag is using a RequestDispatcher to dispatch the request.

2. <sling:include path="layout-link.jsp" />


This is the include tag of the Sling JSP Tag library. This tag knows about Sling and also
supportsRequestDispatcherOptions.
3. <cq:include script="layout-link.jsp" />
This tag is Communiqué specific extension of the Sling JSP Tag library include tag. it
supports callings scripts in addition to just including renderings of resources.

What is the advantage of each tag? When should each be used?


In a Communiqué application, the Communiqué or Sling include tag provides you more
Sling support.
15. What are Clientlibs?
Clientlib: CQ Static Resource Management
performance can be improved by considering various factors while designing a new
application, few of them are listed below:

1) Web page size


A web page is composed of HTML markup, JS files, CSS files and images. We should try to
keep page size as low as possible so that page is loaded quickly in browser.
2) Ajax calls v/s full page reload
There are many instances where it’s always better to make an Ajax call to hit the server and
update a small area (HTML DOM) of page rather than reloading whole page.
3) Amount of data transfer between server and browser
When we make a call to service on server, the services should only return page/context specific
data rather returning whole information/data. We can call server again (via Ajax calls) to fetch
limited data and update page accordingly.

In this post I’ll try to show the benefit of using client libs feature to reduce the page size. Let’s
consider a scenario where we have a web application built using CQ and it has multiple pages
that are composed of many component. Each component needs a set of JS, CSS and images
which might not be needed on other pages so, it does not make sense to load all those
irrelevant resources on other pages where that component is not present.

For example we have a login page and a home page that user sees after successful login. The
login page is composed of a login component (with a form) to enter username and password
and we are using a jQuery validation plugin to validate form before submitting it to server. Once
user is validated we redirect user to home page which does not have any form (i.e. we don’t
need validation jQuery
plugin) on this page and there is no point in including validation plugin and we only need jQuery
javascript file.

Login Page: needs jQuery and jQuery Validation plugin


Home Page: needs just jQuery

Normally, we include resource (like JS, CSS) in section of a page (in CQ it’s a template). If
jQuery and jQuery validation plugin is included in head section of template then it’ll be included
on every page no matters whether that page actually needs them or not and hence the page
size is increased unnecessarily. There is better way to handle this in CQ and load the resources
when they are actually needed and this is where CQ’s clientlib feature comes in to play.
What is client lib feature?
With client lib feature we can categorize every JS and CSS file as a library (with a specific
name) and can include/import them in individual component or template (if it is used globally).
For the time being consider this as java import feature. If on a page there are multiple
component that needs the same library then CQ will make sure that the library is loaded only
once. We can also define dependencies while creating clientlibs, e.g. jQuery validation plugin is
dependent on base jQuery JS file.

How to define a client lib in CQ?


To define a client lib CQ follow below steps:
1) create a folder called clientlibs (by right clicking on designs folder) under /etc/designs
(actually we can create this folder anywhere we want but, to keep it simple and consistent I am
creating this under designs folder)

2) Create a new node under clientlibs folder called as jqvalidate with type as
cq:ClientLibraryFolder (as shown below):
3) Copy/Put your JS (jq.validate-min-XXX.js) file in jqvalidate folder (we can also copy and css
file to this folder if there is any).
4) Create a file js.txt in jqvalidate folder (also create another file css.txt if you have copied any
css file in jqvalidate folder).
5) Add name of JS file (e.g. jq.validate-min-XXX.js) in js.txt (also add name of CSS file in
css.txt) file and save it.

6) Click on jqvalidate folder node in crxde and open the Properties tab and update/add 2 new
properties as shown below and save the node:
NOTE: both properties are of type String Array (String[])
a) categories: This is the name using which we’ll be referencing our jQuery validation client lib in
our components and templates.
b) dependencies: Using this property we define the dependency of current library (in this case
jQuery validation) on another client lib (in this case cq.jquery).
At this point we are done with creation of a validation library now, we’ll see how to use for
developing components and templates.

How to use/import client lib?


To include a client lib in your component/template simply add following code/tag:

view plaincopy to clipboardprint?

1. <cq:includeclientlib categories="jquery.validate">

2. </cq:includeclientlib>

If you want to load multiple client libs then provide comma separated names against categories
attribute in above tag e.g.

1. <cq:includeclientlib categories="jquery.validate, someother.clientlib">

2. </cq:includeclientlib>

The "clientlib" functionality will manage all your Javascript and CSS resources in your
application. It takes cares of dependency management, merging files and minifying content.

t takes cares of dependency management, merging files and minifying content.

http://experiencedelivers.adobe.com/cemblog/en/experiencedelivers/2012/12/clientlibs-
explained-by-example.html
16. What is the difference between design dialog and a
normal dialog?

A design dialog is used to globally store variables through the template properties’ whereas a
normal dialog stores all variables inside the page’s properties. One of the major benefits of
using the design dialog is that if you have a hundred pages sharing the same template the
variables will be shared amongst them. Also, note that you can have both design dialog and
normal dialog on a page.

A dialog saves content relative to the given page. In comparison, a 'design' dialog saves
content globally (at a template level).

Dialog is a key element of your component as they provide an interface for authors to
configure and provide input to that component. The user input will be stored at page level.

Design dialog will share the content at the template level. Also we can dynamically change
the content in design mode.

Within CQ, there are some key folder structures. For example, you may have a page at the
following path:

/content/your-site/en_HK/your-page

Within that page you have a component that has both a dialog and a design dialog. When you
save content in the dialog, it is saved to a node beneath the given page. Something like:

/content/your-site/en_HK/your-page/jcr_content/some-par-sys/your-component

However, when you save content to the design dialog, it is saved to a 'global' design
path. Something like:

/etc/design/your-site/en_HK/your-template/jcr_content/your-component
This mechanism allows the content that has been saved in the design dialog for the GIVEN
TEMPLATE to be available in all templates of the same type (basically).

http://daycq.blogspot.in/2011/12/dialog-designdialog.html

17. What is Personalization?


Personalization provides your users with a customized environment that displays
dynamic content selected according to their specific needs.
Personalization centers on providing the user with a tailor-made environment displaying
dynamic content that is selected according to their specific needs; be this on the basis
of predefined profiles, user selection, or interactive user behavior.
Teaser Component used in Personalization and Segmentation also.

18. What is a CQ5 overlay/override component?


I've been asked to create a CQ5 "overlay" component by simply copying the out-
of-box component from /libs/foundation/components/flash to
/apps/myproject/components/flash. My question is: what happens to the original - is it
just ignored?

Use of the Overlay component is , when you want to use the out-of-box component and
you want to add some extra feature in it , so instead of changing the code from
“libs/foundation/components/component-name.jsp” just follow the below process and
use it. By using this we can use the out-of-box feature with our extra feature without
changing behaviour of out-of-box component . So that other projects which are using it
can't be affected.

Example : Overlaying the TEXT component.

1. Create the “foundation/components” folder under apps as in figure 1.


2. Copy the text component from “libs/foundation/components/text” to above path.
3. Append the below code in text.jsp
4. Change the jcr:title to Text Overlayed.

<div style="border-width:1px;border-style:solid;border-
color:black;width:100%;background:grey;color:white">
Overlaid text component
</div>
Figure 1 : create the foundation/components folder under apps.

5. Now open the “http://localhost:7502/cf#/content/geometrixx/en.html” page, you


will see the

Figure 2 : The text component used by geometrixx page will now use the code from
“apps/foundation/components/text” instead of
“libs/foundation/components/text”

This will CHANGE how the foundation component behaves in all instances. And the
existing sidekick component remains, but behaves differently.
It is not ignored. Both components can show up in the authors' sidekick -- one will
say flash (foundation), the other flash (myproject).

If/libs/foundation/components/flash needs an overlay, you "overlay" the corresponding


file at location /apps/foundation/components/flash/filename This will CHANGE how the
foundation component behaves in all instances. And the existing sidekick component
remains, but behaves differently.
If you have a NEW component at /apps/myproject/components/flash, it can inherit from
the foundation component via sling:resourceSuperType on the new component. In that
case, you have a new component in the sidekick. In your new component, you could
use the same values forjcr:title, componentGroup, or you could change them to
distinguish your component in the sidekick. If the title, componentGroups are the same,
the sidekick can distinguish them with parenthesis around the webapp (foundation) vs
(myproject). However, I have seen situations where it is impossible as an author to
distinguish them.

19. How to extend/inherit/Enhance the components ?


Difference between the Overlay components and Extended Components is -
Overlay/Overrided Component Extended/Inherited Components
1. Universally available across the WEM. 1.Not universally available across
WEM as they are inherited for
specific project.
2. They are copied from 2. They are extended by using
“/libs/foundation/components/ ” to “ sling:resourceSuperType ”
“/apps/foundation/components/” property

Example 1 : Extending the text component.


1. Create the project under apps folder. As in figure.

2.
Add the below properties to the component.

3. Open “newtext.jsp” add the below code in it


<%--
New Text Component component.
--%><%
%><%@include file="/libs/foundation/global.jsp"%><%
%><%@page session="false" %><%
%><div style="border-width:1px;border-style:solid;border-
color:black;width:100%;background:red;color:white">
Inherited text component
</div>
<%
%><cq:text property="text"/>

EXAMPLE 2 :

1. Page Component inherting the behaviour of foundation/components/page

Figure 1 : page component is using sling:resourceSuperType


:foundation/components/page
Figure 2 : blog component is using sling:resourceSuperType –
Test/components/page
3. Test/page/body.jsp
<%@ include file="/libs/foundation/global.jsp" %>
<div><cq:include script="header.jsp"/></div>
<div><cq:include script="content.jsp"/></div>
<div><cq:include script="footer.jsp"/></div>
4. Test/page/content.jsp
<%@include file="/libs/foundation/global.jsp"%><%
%><%@page session="false" %>
<h1> Base content <h1>
5. Test/page/footer.jsp
<%@include file="/libs/foundation/global.jsp"%><%
%><%@page session="false" %>
This is the Footer
6. Test/page/header.jsp
<%@include file="/libs/foundation/global.jsp"%><%
%><%@page session="false" %>
This is Header
<cq:include path="header" resourceType="foundation/components/iparsys"/>
6. Test/blog/content.jsp
<%@include file="/libs/foundation/global.jsp"%><%
%><%@page session="false" %>
<h1>Blog Content</h1>

20. Difference between Parbase and parsys?


Parbase Parsys
Parbase is a key component as it allows The paragraph system (parsys) is a
components to inherit attributes from other compound component that allows authors to
components, similar to subclasses in object add components of different types to a page
oriented languages such as Java, C++, and and contains all other paragraph
so on. For example, when you open components. Each paragraph type is
the/libs/foundation/components/text node in represented as a component. The
the CRXDE Lite, you see that it has a paragraph system itself is also a
property named sling:resourceSuperType, component, which contains the other
which references the parbase component. paragraph components.
The parbase here defines tree scripts to
render images, titles, and so on, so that all
components subclassed from this parbase
can use this script.
Also for image component : crop,map etc
inheritd
Users do not need access to the parbase.

21. Difference between Parsys and Iparsys?


Parsys iParsys
Parsys is a placeholder where we Iparsys or Inherited Paragraph
can drag and drop the component and the System is similar to parsys except it allows
script (or content) inside the component you to inherit the created paragraphs from
will be rendered to that place. the parent.

22. “What benefit does an OSGi Bundle provide over a


conventional Java “jar” file?”

While it is true that you can start and stop a “jar” file, the concept of a bundle expands upon the
conventional “jar” file by including metadata such as the version and list of services imported
and exported by the bundle. This allows an OSGi bundle to be installed, updated, and
uninstalled without taking down the entire application. Also, OSGi bundling allows multiple
versions to exist, with the OSGi framework assuming the responsibility of matching “service
consumers” with “service providers”. The net result is that an OSGi bundle is more of a
standalone “software module” than a “jar”, “war”, or “ear” file.

Sling is based on OSGi. OSGi (Open Services Gateway Initiative) defines an architecture for
developing and deploying modular applications and libraries. As such, extending Sling with
application-specific components ("bundles" as they are called in OSGi lingo) essentially means
creating a bundle

23. Create a OSGi bundle?How will you expose the Bundle/Service?

A bundle is a jar file plus some meta information. Let us start with a simple service interface
class. In OSGi development it is common practice to use interfaces and implementing classes.
package com.day.samples;

import javax.jcr.Node;

import javax.jcr.RepositoryException;

public interface HelloService {

public String sayHello();

public String getReversedNodePath(Node

node) throws RepositoryException;

public String getRepository();

public void log(String text);

This is really just a plain old Java interface, nothing OSGi- or Sling-specific to be seen here, just
some JCR classes are imported. I chose these four methods because they provide some
insights how to develop OSGi bundles on top of Sling. However, they are not "required" in the
sense that e.g. EJB 2 would require a certain structure of your classes. The implementing class
looks like:

package com.day.samples.impl;

import javax.jcr.Node;

import javax.jcr.RepositoryException;

import org.apache.sling.jcr.api.SlingRepository;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import com.day.samples.HelloService;
public class HelloServiceImpl implements

HelloService{

private SlingRepository repository;

private static final Logger log =

LoggerFactory.getLogger(HelloServiceImpl.class);

public String sayHello() {

return ("Hello World!!");

public String getReversedNodePath(Node node)

throws RepositoryException {

return new

StringBuffer(node.getPath()).reverse().

toString();

public String getRepository() {

return

repository.getDescriptor(

SlingRepository.REP_NAME_DESC);

protected void bindRepository(SlingRepository

repository) {
this.repository = repository;

protected void unbindRepository(SlingRepository

repository) {

this.repository = null;

public void log(String text) {

log.error(text);

The implementation imports the SlingRepository class and a logger class that comes with Sling.
In order to compile this class you will need to have the Sling jars on your classpath. If you use
CRX Quickstart find them in launchpad/felix/bundleXX.

For the bundle description we will need a descriptor file called MANIFEST.MF located in META-
INF and contains:

Manifest-Version: 1.0

Bundle-ManifestVersion: 2

Bundle-Name: HelloWorld Plug-in

Bundle-SymbolicName: HelloWorld

Bundle-Version: 1.0.0

Import-Package: org.osgi.framework;version="1.3.0",

org.apache.sling.jcr.api,org.slf4j

Export-Package: com.day.samples;version="1.0.0"

Private-Package: com.day.samples.impl

Service-Component: OSGI-INF/serviceComponents.xml
Note that the packages that are used in the implementing class above must be imported.
Also, the packages that shall be exposed from our bundle to other bundles must be
marked as "exported". Further, there must be a reference to the second needed descriptor file
OSGI-INF/serviceComponents.xml. This file contains:

<?xml version="1.0" encoding="UTF-8"?>

<components

xmlns:scr="http://www.osgi.org/xmlns/scr/v1.0.0">

<scr:component enabled="true" immediate="true"

name="com.day.samples.impl.HelloServiceImpl">

<scr:implementation

class="com.day.samples.impl.HelloServiceImpl"/>

<scr:service servicefactory="false">

<scr:provide

interface="com.day.samples.HelloService"/>

</scr:service>

<scr:property name="service.description"

value="Say hello sample service"/>

<scr:property name="service.vendor"

value="Day"/>

<scr:property name="service.pid"

value="com.day.samples.impl.HelloServiceImpl"/>

<scr:reference name="repository"

interface="org.apache.sling.jcr.api.

SlingRepository"

cardinality="1..1" policy="static"

bind="bindRepository"

unbind="unbindRepository"/>

</scr:component>
</components>

This file configures which implementation of the interface shall be used. It also configures the
"injection" of the repository variable into the HelloServiceImpl class (highlighted). The "setter" is
configured in the "bind" attribute. HelloServiceImpl must implement this method.

For creating an OSGi bundle you just need to compile these classes and package them in a jar
file together with the descriptors (the complete bundle is attached).

The Sling/Felix console


The Sling console is a web application that comes with Sling and CRX Quickstart that allows
you (among other things) to deploy new bundles. It is located at
http://localhost:7402/system/console/list. Bundle details can be seen by clicking on a bundle
name. This reveals e.g. the bundle version and the exported packages. For example, note that
the org.slf4j package imported by HelloServiceImpl is exported by a bundle named "Sling-OSGi
LogService Implementation".

Upload your bundle jar file, press "Install or Update" and "Refresh Packages". Your bundle
should now show up in the list of bundles. If it has not been started start it yourself by pressing
"start".

Accessing the service


In order to be useful the deployed OSGi service should be accessible from esp templates. That
works like this:

<% var service =

sling.getService(

Packages.com.day.samples.HelloService);

%>

<%= service.sayHallo() %>

The HelloService also contains a method getReversedNodePath(Node node) that takes a JCR
node as a parameter (it diabolically returns the node's path as a reversed string). For passing
the currently processed node to this method use:
<%= service.getReversedNodePath(currentNode)%>

The method log(String text) in HelloService writes into Sling's log file. This can come in handy
for debugging purposes. Note again that the logger package needs to be imported in
MANIFEST.MF in order to be visible.

In the method getRepository() the name of the current repository is returned. This method
illustrates how to access the repository from within the bundle and thus perform manipulations
or queries on the repository.

Final remarks
If you care to look at Sling's source code to learn more you will notice the lack of configuration
files like serviceComponents.xml. The reason for this is that the Sling develpers use a Maven
plugin that automatically generates these artifacts. You can still find them in the generated jar
files, of course.

9.Building-workflows-in-adobe-cq5

--http://blog.navigationarts.com/building-workflows-in-adobe-cq5/

24. Explain LDAP Configuration and Synchronization in


CQ5 ?

How does CQ interface with LDAP systems?


CQ interfaces with LDAP systems, such as Apache Directory or Windows Active Directory, using
the Java Authentication and Authorization Service (JAAS).

What LDAP information is synchronized with CQ?


Information about users and groups is synchronized between CQ and the LDAP system.
Although LDAP accounts might be assigned to groups, these associations often reflect
organizational properties, because the accounts may be applied to multiple applications. It is
recommended that you apply CRX groups to the accounts to control permissions within CRX or
any dependent applications, such as CQ.

Difference between nt:folder and sling:folder?


Sling:folderNode type to be used as a replacement for nt:folder: it can be used
as a child of nt:folder and allows to add unstructured content.
/libs/sling/nodetypes/sling.cnd"

you are free to add whatever property you want in a sling:folder (not in a nt:folder)

- you are free to add whatever nodetype you want in a sling:folder (not in a nt:folder)

The "nt" means "Node Type", and a "node type: folder. The "sling" prefix means that this one special
folder belongs to the type "Sling",

nt:folder represents a plain file system folder (it can have nt:folder and nt:file children and only a
few restricted meta data properties).

Error 409 “could not save changes” come when we save a node of nt:unstructured type under
nt:folder

difference between sling:resourceType and sling:


super resource type

Tool page – miscadmin


Webpage – siteadmin

13) Difference between OSGi bundle and Normal Jar file?

1) OSGi bundles are jar files with metadata inside manifest file, found at META-
INF/MANIFEST.MF. This metadata, when read by an OSGi runtime container, is what gives
the bundle its power.

2) With OSGi, just because a class is public doesn't mean you can get to it. All bundles
include an export list of package names, and if a package isn't in the export list, it doesn't
exist to the outside world. This allows developers to build an extensive internal class
hierarchy and minimize the surface area of the bundle's API without abusing the notion of
package-private visibility. A common pattern, for instance, is to put interfaces in one
package and implementations in another, and only export the interface package.

3) All OSGi bundles are given a version number, so it's possible for an application to
simultaneously access different versions of the same bundle (eg: junit 3.8.1 and junit 4.0.).
Since each bundle has its own classloader, both bundles classes can coexist in the same
JVM.

4) OSGi bundles declare which other bundles they depend upon. This allows them to
ensure that any dependencies are met before the bundle is resolved. Only resolved bundles
can be activated. Because bundles have versions, versioning can be included in the
dependency specification, so one bundle can depend on version junit version 3.8.1 and
another bundle depend on junit version 4.0.

5) In OSGi bundle, there will be an Activator.java class in OSGi which is an optional


listener class to be notified of bundle start and stop events

6) How is resource resolution done in Sling?

The below images tells us how a URL is resolved and mapped to a resource.
Consider the URL

GET – www.mywebsite.com/products/product1.printable.a4.html/a/b?x=12

Here the type of request will be HTTP GET request

We can break it down into its composite parts:

Protocol Host content path selector(s) extension suffix param(s)

http:// Mywebsite products/product1 .printable.a4. html / a/b ? x=12

Read Node in CQ5-


ResourceResolver resourceResolver = slingRequest.getResourceResolver();
Session session = resourceResolver.adaptTo(Session.class);
Node rootNode = session.getRootNode();

“UHG OPTUM PROJECT”


About the Project--- In this project, we have done Design & Implementation of “Electronic
Payments and Statements” site of UHG with AEM CQ, Angular JS and Rest Web service
technology. This site was existed already; we have migrated to AEM CQ. Rest web services were
already written to fetch the data in JSON format. JSON object was handled in Angular JS. Then
CQ was used for configuration and showing the labels and data on the basis of user type, CSR
(customer service representative, Internal Users) and EPS both the flow.
1- I was from starting of this project, so participated with tech-arch in the analysis,
designing and deciding of the components and there number according to the
requirement. (75 components were created)
Explanation: - we were having the current site. So daily we sit with the client side tech team and
our team (CQ and UI), discussed each of the pages and required component on that page with
its functionality.
2- Generated the Maven project structure in the file system.
Explanation: -
$ mvn archetype:generate
-
1 DarchetypeRepository=http://repo.adobe.com/nexus/content/groups/public/
2 \
3 DarchetypeGroupId=com.day.jcr.vault \
4 DarchetypeArtifactId=multimodule-content-package-archetype \
5 DarchetypeVersion=1.0.2 \
6
DgroupId=my-group-id \
7
8 DartifactId=myproject \
9 Dversion=1.0-SNAPSHOT \
10 Dpackage=com.mycompany.myproject \
11 DappsFolderName=myproject \
12 DartifactName="My Project" \
13 DcqVersion="5.6.1" \
DpackageGroup="My Company"

http://docs.adobe.com/docs/en/cq/5-6-1/developing/developmenttools/how-to-build-aem-
projects-using-apache-maven.html

It created two folder “bundle” and “content” for OSGI and CQ Content. We imported in eclipse
IDE for development and modified the pom file with dependency and configuration. For detail
read the link given.

3- For build process, created a batch file. Mvn build cmd was there and cURL commands
were there for downloading, uploading and installing the packages on the other local
server QA. This was done for the automation. On build success on QA server then build
was deployed on the dev and staging server of client by batch file.
mvn clean install -PautoInstallPackage > build_deploy_local.log
For cURL, see below in file.

4- There are two flows (EPS and CSR) in the projects with almost same pages. So dialogs
were having most of the fields same. For the different fields, we have created the
different tabs in the dialog, on the basis of the tags of the page; it shows the tab
associated with that page.
Explanation: - we have given the tag on the page from page property. It got save at jcr:content
node. We read it in jsp and set it in html hidden type field. In listener of the dialog, we fetched
this variable and on the basis of it, we did hide and show of the tabs.
https://docs.adobe.com/docs/en/cq/5-6-1/developing/tagging.html
http://cq5experiences.blogspot.in/2014/02/hide-and-show-tab-in-dialog-depending.html

5- Complex dialog was written in extended JS. Which is having some common field at the
top, then some no of fields on left hand side, when we click add, it move all the data on
the right hand side of the dialog in the tabular format. So we can add any no of data set
in the dialog. We can also update the data of the row by right click on that row and click
update. So all data were moved to LHS for update.
Explanation: - We have created a theme config component. This component was included in
EPS template. In dialog, path field for home page was there. Then, at LHS, we were having path
field for css, dropdown for themes. Theme names were created in tags. In the jsp we fetched
the tags and created JSON and set this JSON object value in html hidden type field. The same
we fetched in extended JS for populating the dropdown for this dialog. It was also having
corresponding image field for logo.
After adding these values, it goes to RHS. So we can add themes css and logo for all the themes.

At the time of opening of the page URL, on the basis of the selector, we applied the theme for
the site.

OptumConfigService configService = CRXUtil.getServiceReference(OptumConfigService.class);


String themeAdminPagePath = configService.getThemeConfigPath();

Resource res = resourceResolver.getResource (themeAdminPagePath+"/jcr:content/bs-


mainContentPar/themeconfig");

if(res!=null){
node= res.adaptTo(Node.class);
theams = node.getNodes();
while(theams.hasNext()){
themeNode = theams.nextNode();
logoPath.add(themeNode.getProperty("image").getString());
theme.add(themeNode.getProperty("theme").getString());
cssPath.add(themeNode.getProperty("cssPath").getString());
}
}

%>
6- One more complex component was there. Grid component. We were having lots of
table in the project for the different reports.
So we created one multi-field label comp for table header. It was saving the header name as
label and all small, without space and special character key.

Then we created component for configuring the table for the page by selecting the labels from
dropdown. We have to select the user type to which that label should be shown, these user
type are tags. So we are accessing tags in the extended JS file for the dialog.

Configured table can be selected in the dropdown by the name in the grid component.

Tag path for themes and user type, Home page path for EPS and CSR and theme page path
etc., we have given in configuration.

7- Wrote the controller or u can say helper bean java class for the component for fetching
the values from the content level node and processed on them before showing them on
the page.
Explanation: -
Abstract component and component helper class.

AbstractComponent.java StoreDataPopulationBean.java

How to access in JSP page of the component.


<rcq:useBean id="infoPop"
beanClass="com.richemont.cms.vca.core.components.storelocator.StoreDataPopulationBean
"/>
${infoPop.dataPopulate}
<c:set var="address" value="${data['address']}" />
<c:set var="phone" value="${data['phone']}" />
<c:set var="openingHrs" value="${data['openingHrs']}" />
<div id="store-address">
<ul>
<li><strong><fmt:message key="store-details-address"/></strong>
<address>${address}</address></li>

<li><strong><fmt:message key="store-details-phone"/></strong>
<p>${phone}</p></li>
<li><strong><fmt:message key="store-details-hours"/></strong>
<p>${openingHrs}</p></li>
</ul>
</div>

How we have written service and its implementation component class:-


Service: - Service is an interface. It can be implemented by any no of impl classes. It has only
method declaration for the service.
Implementation/component Class: - impl classes are the service provider and consumer. For a
service, there may be more than 1 provider (impl classes). Impl class can also consume more
than one service.
http://felix.apache.org/documentation/subprojects/apache-felix-maven-scr-plugin/scr-
annotations.html

Impl class has @service (org.apache.felix.scr.annotations.Service) annotation


@Service(value = OptumConfigService.class)
The @Service annotation defines whether and which service interfaces are provided by the component.
This is a class annotation.

Component annotation (org.apache.felix.scr.annotations.Component;)


@Component(label = "Optum Global Configuration service", description = "Optum Global
Configuration service for site level configurations", immediate = true, metatype = true)

Immediate=true---will activate or register the component at the time of bundle installation.

This annotation can be applied on the component class level or on a field defining a constant with the
name of the property. We can see this component is registered in system/console/component

@property annotation (org.apache.felix.scr.annotations.Property)

The @Property annotation defines properties which are made available to the component through
the ComponentContext.getProperties() method. These tags are not strictly required but may be
used by components to defined initial configuration.

/** The Constant DEFAULT_THEME_CONFIG_PATH. */


private static final String DEFAULT_THEME_CONFIG_PATH =
"/content/optum/en/admin/theme";
/** The Constant THEME_CONFIG_PATH. */
@Property(label = "Theme Config Path", description = "Admin Theme Config Page
Path", value = { DEFAULT_THEME_CONFIG_PATH })
It will create the dialog for all the values in configmgr in falix console with this level and
description.

We have written activate method to get and set all the properties from the dialog by
componentcontext (org.osgi.service.component.ComponentContext).
protected void activate(final ComponentContext context) {
final Dictionary properties = context.getProperties();
this.themeConfigPath = properties.get(THEME_CONFIG_PATH).toString();
this.gridConfigPath = properties.get(GRID_CONFIG_PATH).toString();
this.labelConfigPath = properties.get(LABEL_CONFIG_PATH).toString();
this.restWebServiceBaseURL =
properties.get(REST_WEBSERVICE_BASE_URL).toString();
this.homePageEPS = properties.get(HOME_PAGE_EPS).toString();
this.homePageCSR = properties.get(HOME_PAGE_CSR).toString();
this.themeTagsNs = properties.get(TAGS_THEME_NS).toString();
this.userTypeTagsNs = properties.get(TAGS_USERTYPE_NS).toString();
}

OptumConfigService.java OptumConfigServiceImpl.java

How to read these values in JSP Example: -


<%@page import="com.mycompany.mymvnproject.HelloService" %><%

HelloService hs = sling.getService(HelloService.class);

String repositoryName = hs.getRepositoryName();

out.println("HELLO:::::" + repositoryName);

%>

The concept of .json, .xml, .txt, etc

open your browser and hit this url http://localhost:4502/content/geometrixx-


outdoors/en/men/coats.json and probably you will get a json response like this:

{“jcr:createdBy”:”admin”,”jcr:created”:”Fri Jun 15 2012 23:49:17


GMT+0530″,”jcr:primaryType”:”cq:Page”}

If you look carefully you will come to know that these are properties of the node. Sling is
providing the node data in json format when we append the url with “.json”. In the same way the
same is true for xml, txt, pdf.

Let me tell you that .json is enabled by default and .xml, .txt and .pdf are not enabled by default.
To enable/disable the renderer go to felix console configuration tab and search for Apache Sling
GET Servlet and check/uncheck the boxes to enable/disable the renderers.

To explain how this concept can be used in our application, let me take an example of populating
a Dialog drop down with some dynamic values. I can do this in two ways:

1. By using a servlet.
2. By using the concept of .json (renders)

By using a servlet:

Let me first tell how I used to do it with Servlet:

In dialog, create a dropdown widget (xtype: selection, type:select) and add a property as below:
Property name: “options”

Property value: “/bin/myoptionsproviderservlet” (path of the servlet)

(Note that this property should be added to the dropdown widget in the dialog)

Then I write a servlet which gets the dynamic data, forms a json object and populates the
dropdown.

This is a simple case. Using this approach may be difficult when we need to pass a query
parameter to the servlet. Now we need some different approach which makes it easy when
dealing with situation like this.

By using .json:

In dialog, create a dropdown widget (xtype: selection, type:select) and add options property as
below:

Property name: “options”

Property value: “$PATH.optionsprovider.json”

Create a jsp file with name “optionsprovider.json.jsp” (it can be any name, but make sure you
provide the same name in the options property as well) and write a json rendering code in your
jsp, then the drop down will be populated by the output of the “optionsprovider.json.jsp”.

Advantages we get from this approach are:

1. The inbuilt objects will be available if we include global.jsp.


2. No dependency on a bundle resource (basically a servlet, which will be in a bundle).
3. The json response can be cached and the performance can be improved.
4. Avoiding writing servlets.

This way we can render xml, txt, etc.

Usertypes.json.jsp

<%@ page session="false"


import="com.day.cq.commons.jcr.JcrConstants,
com.day.cq.tagging.Tag,
org.apache.sling.api.resource.ResourceUtil,
com.day.cq.tagging.TagManager,
org.apache.sling.commons.json.JSONException,
org.apache.sling.commons.json.io.JSONWriter,
javax.jcr.query.Query,java.util.ArrayList,
java.util.Iterator,
com.optum.website.common.CRXUtil,
com.optum.website.services.OptumConfigService"%>
<%
%><%@include file="/apps/optum/global/global.jsp"%>

<%
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
String val="";
String delim = "";
Value values[] = null;
Node node = null;
Node tempnode = null;
NodeIterator it = null;
ArrayList<String> configs = new ArrayList<String>();
ArrayList<String> configsValue = new ArrayList<String>();
String tagsPath = "/etc/tags/optum/usertypes";
TagManager tagManager =
slingRequest.getResourceResolver().adaptTo(TagManager.class);
if (null != tagManager) {
Tag parent = tagManager.resolve(tagsPath);
Iterator<Tag> iter = parent.listChildren();
while (iter.hasNext()) {
Tag child = iter.next();
configs.add(child.getName());
configsValue.add(child.getTitle());

}
}

%>
[<%
for(int i=0; i<configs.size();i++){
%><%= delim %>
{"text":"<%= configsValue.get(i)
%>","value":"<%=configs.get(i)%>"<%
%>}<%
if ("".equals(delim)) delim = ",";

}
%>]

Connection code with Mongo DB


For general purpose, Create a component and put this code in component JSP.

<%@page import="com.mongodb.*"%>
<%
Mongo mongo = new Mongo("localhost", 27017);

DB db = mongo.getDB("cq"); //”cq” is a DB name.


DBCollection collection = db.getCollection("cq");

// code to insert a collection


BasicDBObject document = new BasicDBObject();
document.put("offerID", 1001);
collection.insert(document);

// reading and displaying a collection


BasicDBObject dbObject = new BasicDBObject();
dbObject.put("name", "arvind");
DBCursor dbCursor = collection.find(dbObject);
while (dbCursor.hasNext()) {
out.println(dbCursor.next());
}

%>

SOAP vs REST: Simple Object Access


Protocol Vs. REpresentational State
Transfer
SOAP is a method of transferring messages, or small amounts of information, over
the Internet. SOAP messages are formatted in XML and are typically sent using
HTTP (hypertext transfer protocol).

1 SOAP uses WSDL for communication between consumer and provider

 WSDL defines contract between client and service and is static by its nature.
 SOAP is a successor of XML-RPC and is very similar, but describes a standard way
to communicate.

 Feed it a web service URL and you can call its web service functions without the need
of specific code.
Binary data that is sent must be encoded first into a format such as base64 encoded.

 Has several protocols and technologies relating to it: WSDL, XSDs, SOAP, WS-
Addressing
REST (REpresentational state transfer):

Rest is a simple way of sending and receiving data between client and server and it doesn’t
have very many standards defined. You can send and receive data as JSON, XML or even
plain text. It is lightweight compared to SOAP.

 In case of REST contract between client and service is somewhat complicated and is
defined by HTTP, URI, Media Formats and Application Specific Coordination Protocol.
It’s highly dynamic unlike WSDL.

 Typically uses normal HTTP methods instead of a big XML format describing
everything. For example to obtain a resource you use HTTP GET, to put a resource
on the server you use HTTP PUT. To delete a resource on the server you use HTTP
DELETE.

 REST is a very simple in that it uses HTTP GET, POST and PUT methods to update
resources on the server.

 REST typically is best used with Resource Oriented Architecture (ROA). In this mode
of thinking everything is a resource, and you would operate on these resources.

 Binary data or binary resources can simply be delivered upon their request.

cURL (Curl URL Request Library)-


install it - http://curl.haxx.se/download.html according to OS.
All command will run on command prompt. So we can create a batch file. And create
an automated process for AEM build, package install, delete etc.

We can also use windows scheduler for this batch file. So all process will run
automatically at the scheduled time.( http://www.sevenforums.com/tutorials/12444-
task-scheduler-create-new-task.html)
DOS Command –
 ECHO – the “print” statement for BAT files. Anything following the word ECHO will be
displayed in the command prompt as text, on its own line.
 ECHO OFF – BAT writers typically put this at the beginning of their files. It means that the
program won’t show the command that you told it to run while it’s running – it’ll just run the
command.
 PAUSE – This outputs the “press any key to continue…” message that you’ve seen all too
many times. It’s helpful because it pauses the BAT file execution until the user tells it to go
again. If you don’t put this in your program, everything will speed by and end before you can
see it.
 CLS – Clears the DOS window (helpful if things get too cluttered!).
 IPCONFIG – Outputs a lot of network information into your DOS box
 PING – Pings an IP, letting you know if your computer was able to contact it. This command
also returns the latency (ping time) and by default pings three times.

Commands:-
1- curl –help
Install the manual for all the default cURL commands
2- curl --manual > <curlManual.txt>
For creating a file of curl manual

3- curl -u admin:admin
http://localhost:4502/crx/packmgr/service.jsp?cmd=help
Help Menu for useful AEM commands
4- curl -u admin:admin
http://localhost:4502/crx/packmgr/service.jsp?cmd=ls
List all the package
5- curl -u admin:admin -X POST
http://localhost:4502/crx/packmgr/service/.json/etc/packa
ges/my_packages/samplepackage.zip?cmd=build
Build the package.

6- curl -u admin:admin -X POST


http://localhost:4502/crx/packmgr/service/.json/etc/packa
ges/my_packages/samplepackage.zip?cmd=uninstall
 Uninstall an existing package
7- curl -u admin:admin -X POST
http://localhost:4502/crx/packmgr/service/.json/etc/packa
ges/my_packages/samplepackage.zip?cmd=install
Installing the existing package.
8- curl -u admin:admin -X POST
http://localhost:4502/crx/packmgr/service/.json/etc/packa
ges/my_packages/samplepackage.zip?cmd=delete
Delete an existing package
9- curl -u admin:admin -F
file=@"C:\sample\samplepackage.zip" -F
name="samplepackage" -F force=true -F install=true
http://localhost:4502/crx/packmgr/service.jsp
Upload and Install an existing package from File system
10- curl -u admin:admin -F
file=@"C:\sample\samplepackage.zip" -F
name="samplepackage" -F force=true -F install=false
http://localhost:4502/crx/packmgr/service.jsp
Upload and don’t install an existing package from File system
11- curl -u admin:admin
http://localhost:4502/etc/packages/my_packages/samplepack
age.zip > <local filepath>
Download an existing package into filesystem

For More Info


http://hashimkhan.in/2015/05/27/aem-with-curl/
User Management command --- Create user, create new group, adding a
property to existing user like age,Delete user and group, change pwd, set a
group for use, remove user from group

Node management----Create node, page, delete node


Replication----Activate and deactivate, tree replication
OSGI Management----Build bundle, start bundle stop bundle, install a bundle
from file system,

JCR query----find a asset from JCR

Back up----Trigger back up or stop it.

How to Build AEM Projects using Apache Maven


http://docs.adobe.com/docs/en/cq/5-6-1/developing/developmenttools/how-to-build-aem-projects-
using-apache-maven.html

SYNCHRONIZING WITH THE REPOSITORY VLT TOOL

You need to synchronize filevault with the repository. To do this:

1. In the command line, navigate to content/jcr_root.

2. Check out the repository by typing the following (substituting your port number for 4502 and your admin
passwords):

1 vlt --credentials admin:admin co --force http://localhost:4502/crx

http://docs.adobe.com/docs/en/cq/5-6-1/core/how_to/how_to_use_the_vlttool.html

Allowed child at template level

These properties allows you to set some contract of structure of pages in you project. For
example: you have 3 templates (and corresponding pages with this templates):

 template-1: allowedChildren="[template-2]"
 template-2: allowedChildren="[template-3]"
 template-3: allowedChildren="[]"
Then in siteadmin, you will be able to create:

 under page with template "template-1" only pages with template "template-2",
 under page with template "template-2" only pages with template "template-3",
 under page with template "template-3" you will not be able to create any page.

If template-1:allowedparent="[template2]"

template1 can be created as child page of page created using template2\

http://docs.adobe.com/docs/en/cq/5-6-1/developing/templates.html#Template%20Availability

Interface vs abstract class

http://www.programmerinterview.com/index.php/java-questions/interface-vs-abstract-class/
http://www.ronaldwidha.net/2008/06/16/a-good-example-of-abstract-class-vs-interface/

Eval--- http://www.w3schools.com/jsref/jsref_eval.asp

Over loading/overriding

http://www.javatpoint.com/method-overloading-vs-method-overriding-in-java

Final Finally Finalize---- http://www.javatpoint.com/difference-between-final-finally-and-finalize

Java Interview Q- http://www.tutorialspoint.com/java/java_interview_questions.htm

Multithreading Example - http://www.tutorialspoint.com/java/java_multithreading.htm

To be study---

https://docs.adobe.com/docs/en/cq/5-6-1/administering/multi_site_manager.html

Remove default p tag in rte (limited scope)

Not sure if you have noticed but when an author types in anything inside the rich text editor
(even if you are in the HTML Editor mode) it gets encapsulated by a P tag. I came across a
situation in which the requirement was to get rid of the default p tag so the rendering engine
consuming the content does not have to parse it out. Please note that you will still get a bunch of
P tags when you have a line break. This is how I got it working.

1. Traverse to your components ‘fieldConfig’


(/apps/blog/components/content/demo/dialog/items/items/title/items/title/fieldConfig) node and
create a new property for ‘fieldConfig’ with name as ‘removeSingleParagraphContainter’, type
as Boolean and value as true. Save.

2. No go back to your content page and refresh it. Add a single line of text while in RichText
mode and then toggle between SourceEdit mode and Rich Text mode. You should not see the P
tags wrapping your line of content.
Disabling the "Target" context menu item in AEM v5.6
https://forums.adobe.com/message/5334713

libs/cq/ui/widgets/source/widgets/wcm/EditBase.js in
/apps/cq/ui/widgets/source/widgets/wcm/EditBase.js and then I just added one line of code. If
you search the js file for addTargetingActions you will find the function that adds the button to
the toolbar. A config object is passed into the function. If you add one line at the beginning of
the funtion just below line 1728...

config.disableTargeting = true;

"jcr:title":"Paragraph System",

"sling:resourceSuperType":"/libs/foundation/components/parsys",

"componentGroup":".hidden",

"cq:isContainer":"true",

"jcr:primaryType":"cq:Component",

"cq:childEditConfig": {

"cq:disableTargeting": true,

"jcr:primaryType": "cq:EditConfig"

},

"cq:editConfig": {

"cq:disableTargeting": true,

"jcr:primaryType": "cq:EditConfig"

}}

https://docs.adobe.com/docs/en/cq/5-6-1/developing/components/dev-targeted.html

https://docs.adobe.com/content/docs/en/aem/6-0/develop/personalization/target.pdf

http://docs.adobe.com/docs/en/aem/6-0/administer/integration/marketing-cloud/target.html

http://docs.adobe.com/docs/en/aem/6-0/author/personalization/target.html

S-ar putea să vă placă și