AEM Dispatcher

 

Methods for Caching

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. i.e. it effectively flags relevant pages as being out of date, without deleting anything.

Content Updates

In a content update, one or more AEM documents change. AEM sends a syndication request to the Dispatcher, which updates the cache accordingly:

  1. It deletes the modified file(s) from the cache.
  2. It deletes all files that start with the same handle from the cache. For example, if the file /en/index.html is updated, all the files that start with /en/index. are deleted. This mechanism allows you to design cache-efficient sites, especially in regard to picture navigations.
  3. It touches the so-called statfile; this updates the timestamp of the statfile to indicate the date of the last change.

The following points should be noted:

  • Content Updates are typically used in conjunction with an authoring system which “knows” what must be replaced.
  • Files that are affected by a content update are removed, but not replaced immediately. The next time such a file is requested, the Dispatcher fetches the new file from the AEM instance and places it in the cache, thereby overwriting the old content.
  • Typically, automatically generated pictures that incorporate text from a page are stored in picture files starting with the same handle – thus ensuring that the association exists for deletion. For example, you may store the title text of the page mypage.html as the picture mypage.titlePicture.gif in the same folder. This way the picture is automatically deleted from the cache each time the page is updated, so you can be sure that the picture always reflects the current version of the page.
  • You may have several statfiles, for example one per language folder. If a page is updated, AEM looks for the next parent folder containing a statfile, and touches that file.

Auto-invalidation

Auto-invalidation automatically invalidates parts of the cache – without physically deleting any files. At every content update, the so-called statfile is touched, so its timestamp reflects the last content update.

The Dispatcher has a list of files that are subject to auto-invalidation. When a document from that list is requested, the Dispatcher compares the date of the cached document with the timestamp of the statfile:

  • if the cached document is newer, the Dispatcher returns it.
  • if it is older, the Dispatcher retrieves the current version from the AEM instance.

Again, certain points should be noted:

  • Auto invalidation is typically used when the inter-relations are complex e.g. for HTML pages. These pages contain links and navigation entries, so they usually have to be updated after a content update. If you have automatically generated PDF or picture files, you may choose to auto-invalidate those too.
  • Auto-invalidation does not involve any action by the dispatcher at update time, except for touching the statfile. However, touching the statfile automatically renders the cache content obsolete, without physically removing it from the cache.

Using a Dispatcher with an Author Server

if you are using AEM with Touch UI you should not cache author instance content. If caching was enabled for the author instance, you need to disable it and delete the contents of the cache directory. To disable caching, you should edit the author_dispatcher.any file and modify the /rule property of the /cache section as follows:

/rules
{
/0000
{ /type "deny" /glob "*"}
}

A Dispatcher can be used in front of an author instance to improve authoring performance. To configure an authoring Dispatcher, do the following:

  • Install a Dispatcher in a web server (this could be Apache, iPlanet, or IIS web server).

  • You may wish to test the newly installed Dispatcher against a working AEM publish instance, to ensure that a baseline correct install has been acheived.

  • Now make sure that the Dispatcher is able to connect via TCP/IP to your author instance.

  • Replace the Dispatcher’s sample dispatcher.any file with the author_dispatcher.any file provided below.

  • Open the author_dispatcher.any in a text editor and make the following changes:

    1. Change the /hostname and /port of the /renders section to point to your author instance.
    2. Change the /docroot of the /cache section to point to a cache directory. In case you are using AEM with Touch UI, see the warning above.
    3. Save the changes.
  • Delete all existing files in the /cache > /docroot directory which you configured above.

  • Restart the web server.

    Dispatcher Configuration Files

    By default the Dispatcher configuration is stored in the dispatcher.any text file, though you can change the name and location of this file during installation.

    The configuration file contains a series of single-valued or multi-valued properties that control the behavior of Dispatcher:

    • Property names are prefixed with a forward slash (“/”).
    • Multi-valued properties enclose child items using braces (“{ }”).

    An example configuration is structured as follows:

    # name of the dispatcher
    /name "internet-server"
    # each farm configures a set off (loadbalanced) renders
    /farms
     {
      # first farm entry (label is not important, just for your convenience)
       /website
         { 
         /clientheaders
           {
           # List of headers that are passed on
           }
         /virtualhosts
           {
           # List of URLs for this Web site
           }
         /sessionmanagement
           {
           # settings for user authentification
           }
         /renders
           {
           # List of AEM instances that render the documents
           }
         /filter
           {
           # List of filters
           }
         /vanity-urls
           {
           # List of vanity URLs
           }
         /cache
           {
           # Cache configuration
           /rules
             {
             # List of cachable documents
             }
           /invalidate
             {
             # List of auto-invalidated documents
             }
           }
         /statistics
           {
           /categories
             {
             # The document categories that are used for load balancing estimates
             }
           }
         /stickyConnectionsFor "/myFolder"
         /health_check
           {
           # Page gets contacted when an instance returns a 500
           }
         /retryDelay "1"
         /numberOfRetries "5"
         /unavailablePenalty "1"
         /failover "1"
         }
     }

    You can include other files that contribute to the configuration:

    • If your configuration file is large you can split it into several smaller files (that are easier to manage) then include these.
    • To include files that are generated automatically.

    For example, to include the file myFarm.any in the /farms configuration use the following code:

    /farms
      {
      $include "myFarm.any"
      }

    Use the asterisk (“*”) as a wildcard to specify a range of files to include.

    Defining Farms – /farms

    The /farms property defines one or more sets of Dispatcher behaviors, where each set is associated with different web sites or URLs. The /farms property can include a single farm or multiple farms:

    • Use a single farm when you want Dispatcher to handle all of your web pages or web sites in the same way.
    • Create multiple farms when different areas of your web site or different web sites require different Dispatcher behavior.

    The /farms property is a top-level property in the configuration structure. To define a farm, add a child property to the /farms property. Use a property name that uniquely identifies the farm within the Dispatcher instance.

    The /farmname property is multi-valued, and contains other properties that define Dispatcher behavior:

    • The URLs of the pages that the farm applies to.
    • One or more service URLs (typically of AEM publish instances) to use for rendering documents.
    • The statistics to use for load-balancing multiple document renderers.
    • Several other behaviors, such as which files to cache and where.

    The value can have include any alphanumeric (a-z, 0-9) character. The following example shows the skeleton definition for two farms named /daycom and /docsdaycom:

    #name of dispatcher
    /name "day sites"
    #farms section defines a list of farms or sites
    /farms
    {
       /daycom
       {
           ...
       }
       /docdaycom
       {
          ...
       }
    }

    If you use more than one render farm, the list is evaluated bottom-up. This is particularly relevant when defining Virtual Hosts for your websites.

    Each farm property can contain the following child properties:

    Property name Description
    /homepage Default homepage
    (optional)(IIS only)
    /clientheaders The headers from the client HTTP request to pass through.
    /virtualhosts The virtual hosts for this farm.
    /sessionmanagement Support for session management and authentication.
    /renders The servers that provide rendered pages (typically AEM publish instances).
    /filter Defines the URLs to which Dispatcher enables access.
    /vanity-urls Configures access to vanity URLs.
    /propagateSyndPost Support for the forwarding of syndication requests.
    /cache Configures caching behavior.
    /statistics Defining statistic categories for load-balancing calculations.
    /stickyConnectionsFor The folder that contains sticky documents.
    /health_check The URL to use to determine server availability.
    /retryDelay The delay before retrying a failed connection.
    /unavailablePenalty Penalties that affect statistics for load-balancing calculations.
    /failover Resend requests to different renders when the original request fails.

    Specify a Default Page (IIS Only) – /homepage

    Caution:

    This parameter is IIS only and will not have any effect in the other web servers.

    The optional /homepage parameter specifies the page that Dispatcher returns when a client requests an undeterminable page or file.

    Typically this situation occurs when a user specifies an URL for which neither IIS or AEM provides an automatic redirection target. For example, if the AEM render instance is shut down after the content is cached, the content redirect URL is unavailable.

    The /homepage section is located inside the /farms section, for example:

    #name of dispatcher
    /name "day sites"
    #farms section defines a list of farms or sites
    /farms
    {
       /daycom
       {
           /homepage "/index.html"
           ...
       }
       /docdaycom
       {
          ...
       }
    }

    Specifying the HTTP Headers to Pass Through – /clientheaders

    The /clientheaders property defines a list of HTTP headers that Dispatcher passes from the client HTTP request to the renderer (AEM instance).

    By default Dispatcher forwards the standard HTTP headers to the AEM instance. In some instances, you might want forward additional headers, or remove specific headers:

    • Add headers, such as custom headers, that your AEM instance expects in the HTTP request.
    • Remove headers, such as authentication headers, that are only relevant to the web server.

    If you customize the set of headers to pass through, you must specify an exhaustive list of headers, including those that are normally included by default.

    The following code is an example configuration for /clientheaders:

    /clientheaders
      {
      "CSRF-Token"
      "X-Forwarded-Proto"
      "referer"
      "user-agent"
      "authorization"
      "from"
      "content-type"
      "content-length"
      "accept-charset"
      "accept-encoding"
      "accept-language"
      "accept"
      "host"
      "if-match"
      "if-none-match"
      "if-range"
      "if-unmodified-since"
      "max-forwards"
      "proxy-authorization"
      "proxy-connection"
      "range"
      "cookie"
      "cq-action"
      "cq-handle"
      "handle"
      "action"
      "cqstats"
      "depth"
      "translate"
      "expires"
      "date"
      "dav"
      "ms-author-via"
      "if"
      "lock-token"
      "x-expected-entity-length"
      "destination"
      "PATH"
      }

    Identifying Virtual Hosts – /virtualhosts

    The /virtualhosts property defines a list of all hostname/URI combinations that Dispatcher accepts for this farm. You can use the asterisk (“*”) character as a wildcard. Values for the /virtualhosts property use the following format:

    [scheme]host[uri][*]

    The following example configuration handles requests for the .com and .ch domains of myCompany, and all domains of mySubDivision:

    /virtualhosts
     {
     "www.myCompany.com"
     "www.myCompany.ch"
     "www.mySubDivison.*"
     }

    Resolving the Virtual Host

    When Dispatcher receives an HTTP or HTTPS request, it finds the virtual host value that best-matches the host, uri, and scheme headers of the request. Dispatcher evaluates the values in the virtualhosts properties in the following order:

    • Dispatcher begins at the lowest farm and progresses upward in the dispatcher.any file.
    • For each farm, Dispatcher begins with the topmost value in the virtualhosts property and progresses down the list of values.

    Dispatcher finds the best-matching virtual host value in the following manner:

    • The first-encountered virtual host that matches all three of the host, the scheme, and the uri of the request is used.
    • If no virtualhosts values has scheme and uri parts that both match the scheme and uri of the request, the first-encountered virtual host that matches the host of the request is used.
    • If no virtualhosts values have a host part that matches the host of the request, the topmost virtual host of the topmost farm is used.

    Therefore, you should place your default virtual host at the top of the virtualhosts property in the topmost farm of your dispatcher.any file.

    Enabling Secure Sessions – /sessionmanagement

    /allowAuthorized must be set to “0” in the /cache section in order to enable this feature.

    Create a secure session for access to the render farm so that users need to log in to access any page in the farm. After logging in, users can access all pages in the farm. See Creating a Closed User Group for information about using this feature with CUGs.

    If sections of your website use different access requirements, you need to define multiple farms.

    /sessionmanagement has several sub-parameters:

    An example configuration looks as follows:

    /sessionmanagement
      {
      /directory "/usr/local/apache/.sessions"
      /encode "md5"
      /header "HTTP:authorization"
      /timeout "800"
      }

    Defining Page Renderers – /renders

    The /renders property defines the URL to which Dispatcher sends requests to render a document. The following example /renders section identifies a single AEM instance for rendering:

    /renders
      {
        /myRenderer
          {
          # hostname or IP of the renderer
          /hostname "aem.myCompany.com"
          # port of the renderer
          /port "4503"
          # connection timeout in milliseconds, "0" (default) waits indefinitely
          /timeout "0"
          }
      }

    The following example /renders section identifies an AEM instance that runs on the same computer as Dispatcher:

    /renders
      {
        /myRenderer
         {
         /hostname "127.0.0.1"
         /port "4503"
         }
      }

    The following example /renders section distributes render requests equally among two AEM instances:

    /renders
      {
        /myFirstRenderer
          {
          /hostname "aem.myCompany.com"
          /port "4503"
          }
        /mySecondRenderer
          {
          /hostname "127.0.0.1"
          /port "4503"
          }
      }

    Configuring Access to Content – /filter

    Use the /filter section to specify the HTTP requests that Dispatcher accepts. All other requests are sent back to the web server with a 404 error code (page not found). If no /filter section exists, all requests are accepted.

    Note: Requests for the statfile are always rejected.

    The /filter section consist of a series of rules that either deny or allow access to content according to patterns in the request-line part of the HTTP request. You should use a whiltelist strategy for your /filter section:

    • First, deny access to everything.
    • Allow access to content as needed.

    Defining a Filter

    Each item in the /filter section includes a type and a pattern that is matched with a specific element of the request line or the entire request line. Each filter can contain the following items:

    • Type: The /type indicates whether to allow or deny access for the requests that match the pattern. The value can be either allow or deny.
    • Element of the Request Line: Include /method, /url, /query, or /protocol and a pattern for filtering requests according to these specific parts of the request-line part of the HTTP request. Filtering on elements of the request line (rather than on the entire request line) is the preferred filter method.
    • glob Property: The /glob property is used to match with the entire request-line of the HTTP request.

    Example Filter: Deny All

    The following example filter section causes Dispatcher to deny requests for all files. You should deny access to all files and then allow access to specific areas.

    /0001  { /glob "*" /type "deny" }

    Requests to an explicitly denied area result in a 404 error code (page not found) being returned.

    Example Filter: Deny Acess to Specific Areas

    Filters also allow you to deny access to various elements for example ASP pages and sensitive areas within a publish instance. The following filter denies access to ASP pages:

    /0002  { /type "deny" /url "*.asp"  }

    Example Filter: Enable POST Requests

    The following example filter allows submitting form data by the POST method:

    /filter {
        /0001  { /glob "*" /type "deny" }
        /0002 { /type "allow" /method "POST" /url "/content/[.]*.form.html" }
    }

    Example Filter: Allow Access to the Workflow Console

    The following example shows a filter used to deny external access to the Workflow console:

    /filter {
        /0001  { /glob "*" /type "deny" }
        /0002  {  /type "allow"  /url "/libs/cq/workflow/content/console*"  }
    }

    When multiple filters patterns apply to a request, the last filter pattern that applies is effective.

    Example filter: Using Regular Expressions

    This filter enables extensions in non-public content directories using a regular expression, defined here between single quotes:

    /005  {  /type "allow" /extension '(css|gif|ico|js|png|swf|jpe?g)' }

    Example filter: Filter Additional Elements of a Request URL

    One of the enhancements introduced in dispatcher 4.2.0 is the ability to filter additional elements of the request URL. The new elements introduced are:

    • path
    • selectors
    • extension
    • suffix

    These can be configured by adding the property of the same name to the filtering rule: /path, /selectors, /extensionand /suffix respectively.

    Below is a rule example that blocks content grabbing from the /content path, using filters for path, selectors and extensions:

    /006 {
            /type "deny"
            /path "/content"
            /selectors '(feed|rss|pages|languages|blueprint|infinity|tidy)'
            /extension '(json|xml|html)'
            }

    Enabling Access to Vanity URLs – /vanity_urls

    Configure Dispatcher to enable access to vanity URLs that are configured for your CQ or AEM pages.

    When access to vanity URLs is enabled, Dispatcher periodically calls a service that runs on the render instance to obtain a list of vanity URLs. Dispatcher stores this list in a local file. When a request for a page is denied due to a filter in the /filter section, Dispatcher consults the list of vanity URLs. If the denied URL is on the list, Dispatcher allows access to the vanity URL.

    To enable access to vanity URLs, add a /vanity_urls section to the /farms section, similar to the following example:

    /vanity_urls {
         /url "/libs/granite/dispatcher/content/vanityUrls.html"
         /file "/tmp/vanity_urls"
         /delay 300
    }

    The /vanity_urls section contains the following properties:

    • /url: The path to the vanity URL service that runs on the render instance. The value of this property must be “/libs/granite/dispatcher/content/vanityUrls.html”.
    • /file: The path to the local file where Dispatcher stores the list of vanity URLs. Make sure that Dispatcher has write-access to this file.
    • /delay: (Seconds) The time between calls to the vanity URL service.

  • Forwarding Syndication Requests – /propagateSyndPost

    Syndication requests are usually intended for Dispatcher only, so by default they are not sent to the renderer (for example, an AEM instance).

    If necessary, set the /propagateSyndPost property to “1” to forward syndication requests to Dispatcher. If set, you must make sure that POST requests are not denied in the filter section.

    Configuring the Dispatcher Cache – /cache

    The /cache section controls how Dispatcher caches documents. Configure several sub-properties to implement your caching strategies:

    • /docroot
    • /statfile
    • /serveStaleOnError
    • /allowAuthorized
    • /rules
    • /statfileslevel
    • /invalidate
    • /invalidateHandler
    • /allowedClients
    • /ignoreUrlParams
    • /headers
    • /mode

    An example cache section might look as follows:

    /cache
      {
      /docroot "/opt/dispatcher/cache"
      /statfile  "/tmp/dispatcher-website.stat"         
      /allowAuthorized "0"
          
      /rules
        {
        # List of files that are cached
        }
      /invalidate
        {
        # List of files that are auto-invalidated
        }
      }

    Specifying the Cache Directory

    The /docroot property identifies the directory where cached files are stored.

    Note:

    The value must be the exact same path as the document root of the web server so that Dispatcher and the web server handle the same files.
    The web server is responsible for delivering the correct status code when the dispatcher cache file is used, that’s why it is important that it can find it as well.

    If you use multiple farms, each farm must use  a different document root.

    Naming the Statfile

    The /statfile property identifies the file to use as the statfile. Dispatcher uses this file to register the time of the most recent content update. The statfile can be any file on the web server.

    The statfile has no content. When content is updated, Dispatcher updates the timestamp. The default statfile is named .stat and is stored in the docroot. Dispatcher blocks access to the statfile.

    Note:

    If /statfileslevel is configured, Dispatcher ignores the /statfile property and uses .stat as the name.

    Caching When Authentication is Used

    The /allowAuthorized property controls whether requests that contain any of the following authentication information are cached:

    • The authorization header.
    • A cookie named authorization.
    • A cookie named login-token.

    By default, requests that include this authentication information are not cached because authentication is not performed when a cached document is returned to the client. This configuration prevents Dispatcher from serving cached documents to users who do not have the necessary rights.

    However, if your requirements permit the caching of authenticated documents, set /allowAuthorized to one:

    /allowAuthorized “1”

    Note:

    To enable session management (using the /sessionmanagement property), the /allowAuthorized property must be set to “0”.

    Specifying the Documents to Cache

    The /rules property controls which documents are cached according to the document path. Regardless of the /rules property, Dispatcher never caches a document in the following circumstances:

    • If the request URI contains a question mark (“?”).
      This usually indicates a dynamic page, such as a search result that does not need to be cached.
    • The file extension is missing.
      The web server needs the extension to determine the document type (the MIME-type).
    • The authentication header is set (this can be configured)
    • If the AEM instance responds with the following headers:
      • no-cache
      • no-store
      • must-revalidate

    Each item in the /rules property includes a glob pattern and a type:

    • The glob pattern is used to match the path of the document.
    • The type indicates whether to cache the documents  that match the glob pattern. The value can be either allow (to cache the document) or deny (to always render the document).

    If you do not have dynamic pages (beyond those already excluded by the above rules), you can configure Dispatcher to cache everything. The rules section for this looks as follows:

    /rules
      {
        /0000  {  /glob "*"   /type "allow" }
      }

    If there are some sections of your page that are dynamic (for example a news application) or within a closed user group, you can define exceptions:

    Note:

    Closed user groups must not be cached as user rights are not checked for cached pages.

    /rules
      {
       /0000  { /glob "*" /type "allow" }
       /0001  { /glob "/en/news/*" /type "deny" }
       /0002  { /glob "*/private/*" /type "deny"  }  
      }

    Invalidating Files by Folder Level

    Use the /statfileslevel property to selectively invalidate cached files according to their path:

    • Dispatcher creates .stat files in each folder from the docroot folder down to the level that you specify. The docroot folder is level 0.
    • When a file is updated, Dispatcher locates the folder on the file path that is at the statfileslevel, and invalidates all files below that folder.

    Instead of invalidating all files, only the files on the same path as an updated file are cached.

    For example, a multi-language website uses the structure /content/myWebsite/xx/topics, where xx represents the 2-letter identifier for each language. When /statfileslevel is three, (/statfileslevel = “3”), a .stat file is created in the following folders:

    • /content
    • /content/myWebsite
    • /content/myWebsite/xx (each language folder contains a .stat file)

    When a file in the /content/myWebsite/fr/topics folder is activated, the .stat file below /content/myWebsite/fr is touched. All files in the fr folder are invalidated.

    Note: If you specify a value for the /statfileslevel property, the /statfile property is ignored.

    Automatically Invalidating Cached Files

    The /invalidate property defines the documents that are automatically invalidated when content is updated.

    With automatic invalidation, Dispatcher does not delete cached files after a content update, but checks their validity when they are next requested. Documents in the cache that are not auto-invalidated will remain in the cache until a content update explicitly deletes them.

    Automatic invalidation is typically used for HTML pages. HTML pages often contain links to other pages, making it difficult to determine whether a content update affects a page. To make sure that all relevent pages are invalidated when content is updated, automatically invalidate all HTML pages. The following configuration invalidates all HTML pages:

    /invalidate
    {
     /0000  { /glob "*" /type "deny" }
     /0001  { /glob "*.html" /type "allow" }
    }

    This configuration causes the following activiy when the /content/geometrixx/en.html file is activated:

    • All the files with pattern en.* are removed from the /content/geometrixx/ folder.
    • The /content/geometrixx/en/jcr_content folder is removed.
    • All the other files that match the /invalidate configuration are not immediately deleted. These files are deleted when the next request occurs. In our example /content/geometrixx.html is not deleted, it will be deleted when /content/geometrixx.html is requested.

    If you offer automatically generated PDF and ZIP files for download, you might have to automatically invalidate these as well. A configuration example this looks as follows:

    /invalidate
      {
       /0000 { /glob "*" /type "deny" }
       /0001 { /glob "*.html" /type "allow" }
       /0002 { /glob "*.zip" /type "allow" }
       /0003 { /glob "*.pdf" /type "allow" }
      }

    The AEM integration with Adobe Analytics delivers configuration data in an analytics.sitecatalyst.js file in your website. The example dispatcher.any file that is provided with Dispatcher includes the following invalidation rule for this file:

    {
       /glob "*/analytics.sitecatalyst.js"  /type "allow"
    }

    Using custom invalidation scripts

    The /invalidateHandler property allows you to define a script which is called for each invalidation request received by Dispatcher.

    It is called with the following arguments:

    • Handle
      The content path that is invalidated
    • Action
      The replication Action (e.g. Activate, Deactivate)
    • Action Scope
      The replication Action’s Scope (empty, unless a header of CQ-Action-Scope: ResourceOnly is sent, see Invalidating Cached Pages from AEM for details)

    This can be used to cover a number of different use cases, such as invalidating other application specific caches, or to handle cases where the externalized URL of a page and its place in the docroot does not match the content path.

    Below example script logs each invalidate request to a file.

    1
    /invalidateHandler "/opt/dispatcher/scripts/invalidate.sh"

    sample invalidation handler script

    1
    2
    3
    #!/bin/bash
    printf "%-15s: %s %s" $1 $2 $3>> /opt/dispatcher/logs/invalidate.log

    Limiting the Clients That Can Flush the Cache

    The /allowedClients property defines specific clients that are allowed to flush the cache. The globbing patterns are matched against the IP.

    The following example:

    1. denies access to any client
    2. explicitly allows access to the localhost
    /allowedClients
      {
       /0001 { /glob "*.*.*.*"  /type "deny" }
       /0002 { /glob "127.0.0.1" /type "allow" }
      }

    It is recommended that you define the /allowedClients.

    If this is not done, any client can issue a call to clear the cache; if this is done repeatedly it can severely impact the site performance.

    Ignoring URL Parameters

    The ignoreUrlParams section defines which URL parameters are ignored when determining whether a page is cached or delivered from cache:

    • When a request URL contains parameters that are all ignored, the page is cached.
    • When a request URL contains one or more parameters that are not ignored, the page is not cached.

    When a parameter is ignored for a page, the page is cached the first time that the page is requested. Subsequent requests for the page are served the cached page, regardless of the value of the parameter in the request.

    To specify which parameters are ignored, add glob rules to the ignoreUrlParams property:

    • To ignore a parameter, create a glob property that allows the parameter.
    • To prevent the page to be cached, create a glob property that denies the parameter.

    The following example causes Dispatcher to ignores the “q” parameter, so that request URLs that include the q parameter are cached:

    1
    2
    3
    4
    5
    /ignoreUrlParams
    {
        /0001 { /glob "*" /type "deny" }
        /0002 { /glob "q" /type "allow" }
    }

    Using the example ignoreUrlParams value, the following HTTP request causes the page to be cached because the q parameter is ignored:

    1
    GET /mypage.html?q=5

    Using the example ignoreUrlParams value, the following HTTP request causes the page to not be cached because the pparameter is not ignored:

    1
    GET /mypage.html?q=5&p=4

     For information about glob properties, see Designing Patterns for glob Properties.

    Caching HTTP Response Headers

    Note:

    This feature is avaiable with version 4.1.11 of the Dispatcher.

    The /headers property allows you to define the HTTP header types that are going to be cached by the Dispatcher. On the first request to an uncached resource, all headers matching one of the configured values (see the configuration sample below) are stored in a separate file, next to the cache file. On subsequent requests to the cached resource, the stored headers are added to the response.

    Presented below is a sample from the default configuration:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    /cache {
      ...
      /headers {
        "Cache-Control"
        "Content-Disposition"
        "Content-Type"
        "Expires"
        "Last-Modified"
        "X-Content-Type-Options"
        "Last-Modified"
      }
    }

    Note:

    Also, be aware that file globbing characters are not allowed. For more details, see Designing Patterns for glob Properties.

    Dispatcher Cache File Permissions

    The mode property specifies what file permissions are applied to new directories and files in the cache. This setting is restricted by the umask of the calling process. It is an octal number constructed from the sum of one or more of the following values:

    • 0400 Allow read by owner.
    • 0200 Allow write by owner.
    • 0100 Allow the owner to search in directories.
    • 0040 Allow read by group members.
    • 0020 Allow write by group members.
    • 0010 Allow group members to search in the directory.
    • 0004 Allow read by others.
    • 0002 Allow write by others.
    • 0001 Allow others to search in the directory.

    The default value is 0755 which allows the owner to read, write or search and the group and others to read or search.

    Configuring Time Based Cache Invalidation – /enableTTL

    If set, the enableTTL property will evaluate the response headers from the backend, and if they contain a Cache-Controlmax-age or Expires date, an auxiliary, empty file next to the cache file is created, with modification time equal to the expiry date. When the cached file is requested past the modification time it is automatically re-requested from the backend.

    You can enable the feature by adding this line to the dispatcher.any file:

    1
    /enableTTL "1"

    Note:

    This feature is avaiable with version 4.1.11 of the Dispatcher.

    Configuring Load Balancing – /statistics

    The /statistics section defines categories of files for which Dispatcher scores the responsiveness of each render. Dispatcher uses the scores to determine which render to send a request.

    Each category that you create defines a glob pattern. Dispatcher compares the URI of the requested content to these patterns to determine the category of the requested content:

    • The order of the categories determines the order in which they are compared to the URI.
    • The first category pattern that matches the URI is the category of the file. No more category patterns are evaluated.

    Dispatcher supports a maximum of 8 statistics categories. If you define more than 8 categories, only the first 8 are used.

    Render Selection

    Each time Dispatcher requires a rendered page, it uses the following algorithm to select the render:

    1. If the request contains the render name in a renderid cookie, Dispatcher uses that render.
    2. If the request includes no renderid cookie, Dispatcher compares the render statistics:
      1. Dispatcher determines the cateogry of the request URI.
      2. Dispatcher determines which render has the lowest response score for that category, and selects that render.
    3. If no render is selected yet, use the first render in the list.

    The score for a render’s category is based on previous response times, as well as previous failed and successful connections that Dispatcher attempts. For each attempt, the score for the category of the requested URI is updated.

    Note:

    If you do not use load balancing, you can omit this section.

    Defining Statistics Categories

    Define a category for each type of document for which you want to keep statistics for render selection. The /statistics section contains a /categories section. To define a category, add a line below the /categories section that has the following format:

    /name { /glob “pattern“}

    The category name must be unique to the farm. The pattern is described in the Designing Patterns for glob Properties section.

    To determine the category of a URI, Dispatcher compares the URI with each category pattern until a match is found. Dispatcher begins with the first category in the list and cointinues in order. Therefore, place categories with more specific patterns first.

    For example, Dispatcher the default dispatcher.any file defines an HTML category and an others category. The HTML category is more specific and so it appears first:

    1
    2
    3
    4
    5
    6
    7
    8
    /statistics
      {
      /categories
        {
          /html { /glob "*.html" }
          /others  { /glob "*" }
        }
      }

    The following example also includes a category for search pages:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    /statistics
      {
      /categories
        {
          /search { /glob "*search.html" }
          /html { /glob "*.html" }
          /others  { /glob "*" }
        }
      }

    Reflecting Server Unavailability in Dispatcher Statistics

    The /unavailablePenalty property sets the time (in tenths of a second) that is applied to the render statistics when a connection to the render fails. Dispatcher adds the time to the statistics category that matches the requested URI.

    For example, the penalty is applied when the TCP/IP connection to the designated hostname/port cannot be established, either because AEM is not running (and not listening) or because of a network-related problem.

    The /unavailablePenalty property is a direct child of the /farm section (a sibling of the /statistics section).

    If no /unavailablePenalty property exists, a value of “1” is used.

    1
    /unavailablePenalty "1"

    Identifying a Sticky Connection Folder – /stickyConnectionsFor

    The /stickyConnectionsFor property defines one folder that contains sticky documents; this will be accessed using the URL. Dispatcher sends all requests, from a single user, that are in this folder to the same render instance. Sticky connections ensure that session data is present and consistent for all documents. This mechanism uses the renderid cookie.

    The following example defines a sticky connection to the /products folder:

    1
    /stickyConnectionsFor "/products"

    When a page is composed of conent from several content nodes, include the /paths property that lists the paths to the content. For example, a page contains content from /content/image, /content/video, and /var/files/pdfs. The following configuration enables sticky connections for all content on the page:

    1
    2
    3
    4
    5
    6
    7
    /stickyConnections {
      /paths {
        "/content/image"
        "/content/video"
        "/var/files/pdfs"
      }
    }

    Handling Render Connection Errors

    Configure Dispatcher behavior when the render server returns a 500 error, or is unavailable.

    Specifying a Health Check Page

    Use the /health_check property to specify a URL that is checked when a 500 status code occurs. If this page also returns a 500 status code the instance is considered to be unavailable and a configurable time penalty (/unavailablePenalty) is applied to the render before retrying.

    1
    2
    3
    4
    5
    /health_check
      {
      # Page gets contacted when an instance returns a 500
      /url "/health_check.html"
      }

    Specifying the Page Retry Delay

    The /retryDelay property sets the time (in seconds) that Dispatcher waits between rounds of connection attempts with the farm renders. For each round, the maximum number of times Dispatcher attempts a connection to a render is the number of renders in the farm.

    Dispatcher uses a value of “1” if /retryDelay is not explicitly defined. The default value is appropriate in most cases.

    1
    /retryDelay "1"

    Configuring the Number of Retries

    The /numberOfRetries property sets the maximum number of rounds of connection attempts that Dispatcher performs with the renders. If Dispatcher cannot successfully connect to a render after this number of retries, Dispatcher returns a failed response.

    For each round, the maximum number of times Dispatcher attempts a connection to a render is the number of renders in the farm. Therefore, the maximum number of times that Dispatcher attempts a connection is (/numberOfRetries) x (the number of renders).

    “5” is the default value used if not explicitly defined.

    1
    /numberOfRetries "5"

    Using the Failover Mechanism

    Enable the failover mechanism on your Dispatcher farm to resend requests to different renders when the original request fails. When failover is enabled, Dispatcher has the following behavior:

    • When a request to a render returns HTTP status 503 (UNAVAILABLE), Dispatcher sends the request to a different render.
    • When a request to a render returns HTTP status 50x (other than 503), Dispatcher sends a request for the page that is configured for the health_check property.
      • If the health check returns 500 (INTERNAL_SERVER_ERROR), Dispatcher sends the original request to a different render.
      • If the healtch check returns HTTP status 200, Dispatcher returns the initial HTTP 500 error to the client.
    To enable failover, add the following line to the farm (or website):
    1
    /failover "1"

    Note:

    To retry HTTP requests that contain a body, Dispatcher sends a Expect: 100-continue request header to the render before spooling the actual contents. CQ 5.5 with CQSE then immediately answers with either 100 (CONTINUE) or an error code. Other servlet containers should support this as well.

    Ignoring Interruption Errors – /ignoreEINTR

    Caution:

    This option is not usually needed. You only need to use this when you see the following log messages:

        Error while reading response: Interrupted system call

    Any file system oriented system call can be interrupted EINTR if the object of the system call is located on a remote system accessed via NFS. Whether these system calls can time out or be interrupted is based on how the underlying file system was mounted on the local machine.

    Use the /ignoreEINTR parameter if your instance has such a configuration and the log contains the following message:

    Error while reading response: Interrupted system call

    Internally, Dispatcher reads the response from the remote server (i.e. AEM) using a loop that can be represented as:

    while (response not finished) {
    read more data
    }

    Such messages can be generated when the EINTR occurs in the “read more data” section and are caused by the reception of a signal before any data was received.

    To ignore such interrupts you can add the following parameter to dispatcher.any (before /farms):

    /ignoreEINTR “1”

    Setting /ignoreEINTR to “1” causes Dispatcher to continue to attempt to read data until the complete response is read. The default value is 0 and deactivates the option.

AEM Workflows

Workflows enable you to automate Experience Manager activities. Workflows consist of a series of steps that are executed in a specific order. Each step performs a distinct activity such as activating a page or sending an email message. Workflows can interact with assets in the repository, user accounts, and Experience Manager services. Therefore, workflows can coordinate complicated activities that involve any aspect of Experience Manager.

Basics of AEM Workflow Model

Creating a workflow allows user to define and execute a series of steps. In AEM we call workflow as Workflow models .Below are the basic terms used in aem workflow model.

Model : It is made up of WorkflowNodes and WorkflowTransitions. Workflow models are versioned. Running Workflow Instances keep the initial workflow model version that is set when the workflow is started.

Step : There are different types of workflow steps:

  • Participant (User/Group): These types of steps generate a work item and assigns it to a user or group. A user must complete the work item to advance the workflow.
  • Process (Script, Java method call): This type of step is executed automatically by the system. An ECMA script or Java class implements the step. Container (Sub Workflow): This step starts another workflow model.
  • OR Split/Join: Uses logic to decide which step to execute next in the workflow.
  • AND Split/Join: Executes multiple steps simultaneously. All the steps share the following common properties: Autoadvance and Timeout alerts (scriptable).

 

Transition : Defines the link between two consecutive steps.

WorkItem : A workflow instance can have one or many WorkItems at the same time (depending on the workflow model).

Payload : References the resource that has to be advanced through a workflow. The payload implementation references a resource in the repository (by either a path or an UUID) or a resource by a URL or by a serialized java object. Referencing a resource in the repository is very flexible and in conjunction with sling very productive: for example the referenced node could be rendered as a form.

Lifecycle : It is created when a new workflow is started and ends when the end node is processed. The following actions are possible on a workflow instance:

  • Terminate
  • Suspend
  • Resume
  • Restart

Completed and terminated instances are archived.

Inbox : Each logged in user has its own workflow inbox in which the assigned WorkItems are accessible.

Launcher : Allows you to define a workflow to be launched if a specific node has been updated. When we create a new workflow model it consist of three default steps Flow Start ,Flow End and a dummy participant step named as step 1.

  • Flow Start and Flow End represent start and end of workflow.
  • Step1 Participant Step is assigned to admin user to configure a work step. We can edit or delete this step and add new steps as required.

Custom WorkFlow

//This is a component so it can provide or consume services
@Component
  
   
@Service
 
@Properties({
    @Property(name = Constants.SERVICE_DESCRIPTION, value = "Test Email workflow process implementation."),
    @Property(name = Constants.SERVICE_VENDOR, value = "Adobe"),
    @Property(name = "process.label", value = "Test Email Workflow Process") })
public class CustomStep implements WorkflowProcess
{
      
     
/** Default log. */
protected final Logger log = LoggerFactory.getLogger(this.getClass());
     
//Inject a MessageGatewayService
@Reference
private MessageGatewayService messageGatewayService;
     
public void execute(WorkItem item, WorkflowSession wfsession,MetaDataMap args) throws WorkflowException {
         
try
{
    log.info("Here in execute method");    //ensure that the execute method is invoked   
         
    //Declare a MessageGateway service
    MessageGateway<Email> messageGateway;
         
    //Set up the Email message
    Email email = new SimpleEmail();
         
    //Set the mail values
    String emailToRecipients = "tblue@nomailserver.com";
    String emailCcRecipients = "wblue@nomailserver.com";
     
    email.addTo(emailToRecipients);
    email.addCc(emailCcRecipients);
    email.setSubject("AEM Custom Step");
    email.setFrom("scottm@adobe.com");
    email.setMsg("This message is to inform you that the CQ content has been deleted");
     
    //Inject a MessageGateway Service and send the message
    messageGateway = messageGatewayService.getGateway(Email.class);
 
    // Check the logs to see that messageGateway is not null
    messageGateway.send((Email) email);
}
 
    catch (Exception e)
    {
    e.printStackTrace()  ;
    }
 }
}

AEM Architecture

aemstack

AEM technology stack can be divide into following,

  1. Java Runtime Environment (commonly known as JRE)
  2. Granite Platform
  3. AEM modules(Adobe Experience Manager)
  4. Custom Application Module (your website)

Java Runtime Environment [JRE]:

AEM is more or less a combination of or collection of jars, jsps [Java Server Pages], servlets, Java classes along with static resources such as HTMLS, pictures, assets etc. To drive this architecture, it needs JRE.

This makes AEM compatible with any OS that supports required JRE.

Granite Platform:

Granite platform is key role player in AEM stack. Granite is Adobe’s open web stack.

As you can observe from image above, Granite platform consists of below listed modules:

  1. CQSE Servlet Engine
  2. CRX Content Repository
  3. Sling Content Delivery
  4. OSGi Framework

CQSE Servlet Engine: AEM requires an application server that supports Java Servlets API 2.4 or later. The AEM software package is available in two forms:

  1. cq-quickstart.jar: it includes everything needed to get up and running (also called as a “standalone executable jar”). Quickstart Standalone jar file contains a built in servlet engine. As the name “Standalone” suggests user can simply double-click the jar file to install an AEM instance with built in servlet-engine. You do not require any dedicated external application server for servlet handling. In this case you only need a JRE and a standalone quickstart JAR file.
  2. cq-quickstart.war: for deployment in a third-party application server. WAR file do not contain built in servlet engine. In this case, you need a JRE, a WAR file and third party application server for servlet handling.

CRX Content Repository: Everything in AEM is stored in nodes and properties in built-in CRX content repository. CRX is content repository of JCR type. JCR specifications combine features of relational database and file systems, allowing fine-grained access to content repository in File-system Fashion and also in Database fashion.

Let’s understand some terms here itself:

  • CRX (Content repository Xtreme): CRX is repository built into AEM.
  • JSR (Java Specification Request): JSR’s are the formal documents that describe proposed specifications and technologies for adding to the Java platform. There are hundreds of JSR. CRX is Adobe’s implementation of the JSR-283.
  • JCR (Content Repository API for Java): It can be defined as the specifications for accessing content repository using JAVA API in uniform manner. So, JCR is “type of repository”. CRX is an implementation of JCR. Similarly, Apache Jackrabbit is an example of JCR.

To summarize, CRX is content repositories of type JCR and CRX is an implementation of JSR (JSR-283).

The Java Content Repository (JCR) standard, JSR 283, specifies a vendor-independent and implementation-independent way to access content bi-directionally on a granular level within a content repository.

Sling Content Delivery: Sling is a Web application framework based on REST principles. Sling allows easy development of content oriented applications. AEM is based on sling. Sling uses repository of type JCR, such as, CRX and Apache jackrabbit.

“Using Sling, the type of content to be rendered is not the first processing consideration. Instead the main consideration is whether the URL resolves to a content object for which a script can then be found to perform the rendering. This provides excellent support for web content authors to build pages which are easily customized to their requirements.”  

The advantages of content first approach are significant when we have a wide range of different content elements, or when you need easily customizable pages.

OSGi Framework (Open Service Gateway Initiative): OSGi (Open Service Gateway Initiative) is a Java framework for developing and deploying modular software programs and libraries. OSGI is modular system which implements a dynamic components / applications in form of bundles. AEM is based on OSGi. AEM can be thought of as a conglomeration of bundles(components). All the bundles in AEM can be operated from web console.

A bundle is a jar file holding Java classes and a special metadata file (META-INF subfolder). Applications or components coming in form of bundles installed, started, stopped, updated, and uninstalled without requiring a reboot. Each bundle(component/application) is a tightly coupled, dynamically loadable collection of classes, jars, and configuration files that explicitly declare their external dependencies.

OSGi framework, elements of AEM as well as any additional custom applications on top AEM platform are implemented in OSGI bundles.

AEM Modules:

AEM runs on Granite platform. AEM is a complete package of below mentioned modules built on Granite platform in OSGI framework.

  • Websites
  • Mobile Applications
  • Digital Publications
  • Forms
  • Digital Assets
  • Communities
  • Online Commerce

Customers can leverage these application-level building blocks to create customized solutions by building applications of their own.

Custom Application Module (your website):

Customer’s can build their own customized application module o top of AEM. The underlying technology stack empower customer to take advantage of AEM features such as flexibility, simplicity in the management and delivery of website’s, content and assets, and reduced complexity of delivering online experiences to the right customers.

Sling Servlet Registration AEM 6.3

To register a servlet the following properties play a vital role.

  1. sling.servlet.paths: A list of absolute paths under which the servlet is accessible as a Resource. The property value must either be a single String, an array of Strings or a Vector of Strings.

A servlet using this property might be ignored unless its path is included in the Execution Paths (servletresolver.paths) configuration(Apache Sling Servlet/Script Resolver and Error Handler) setting of the SlingServletResolver service.

 

@Component(service = Servlet.class,

property = {

Constants.SERVICE_DESCRIPTION + “=Simple Demo Servlet”,

“sling.servlet.methods=” + HttpConstants.METHOD_GET,

“sling.servlet.paths=” + “/bin/servlet”,

“sling.servlet.extensions=” + “sample”,

})

public class ResolveServletUsingPath extends SlingSafeMethodsServlet {

@Override

protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {

 

}}

 

This Servlet service registered with these properties is registered under this path: /bin/servlet

 

Note: In the above example, Servlet is only registered by path, so the registration properties sling.servlet.method, sling.servlet.extension has been ignored.

  1. sling.servlet.resourceTypes:The resource type(s) supported by the servlet. The property value must either be a single String, an array of Strings or a Vector of Strings.

Note:Either this property(sling.servlet.resourceTypes) or the sling.servlet.paths property must be set, or the servlet is ignored. If both are set, the servlet is registered using both ways.

Fig – Register the servlet using resource type
@Component(service=Servlet.class,

property={

Constants.SERVICE_DESCRIPTION + “=Simple Demo Servlet”,

“sling.servlet.methods=” + HttpConstants.METHOD_GET,

“sling.servlet.resourceTypes=”+ “community-components/components/componentpage”,

“sling.servlet.extensions=” + “sample”,

})

public class MyServlet extends SlingSafeMethodsServlet {
@Override

protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)throws IOException

{

 

}

}

  1. sling.servlet.selectors:The request URL selectors supported by the servlet. The selectors must be configured as they would be specified in the URL that is as a list of dot-separated strings such as print.a4. The property value must either be a single String, an array of Strings or a Vector of Strings. This property is only considered for the registration with sling.servlet.resourceTypes.
@Component(service=Servlet.class,

property={

Constants.SERVICE_DESCRIPTION + “=Simple Demo Servlet“,

“sling.servlet.methods=” + HttpConstants.METHOD_GET,

“sling.servlet.resourceTypes=”+ “community-components/components/componentpage”,

  “sling.servlet.selectors=”+”img”,

              “sling.servlet.selectors=”+”tab”,

})

public class MyServlet extends SlingSafeMethodsServlet {
@Override

protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)throws IOException

{

}

}

The request can be:

http://localhost:4502/content/community-components/en/tagcloud/jcr:content.img.json

http://localhost:4502/content/community-components/en/tagcloud/jcr:content.tab.json

  1. sling.servlet.extensions:The request URL extensions supported by the servlet for requests. The property value must either be a single String, an array of Strings or a Vector of Strings. This property is only considered for the registration with sling.servlet.resourceTypes.

 

  1. sling.servlet.methods: The request methods supported by the servlet. This property is only considered for the registration with sling.servlet.resourceTypes. If this property is missing, the value defaults to GET and HEAD, regardless of which methods are actually implemented/handled by the servlet.
  2. sling.servlet.prefix: The prefix or numeric index to make relative paths absolute. If the value of this property is a number (int), it defines the index of the search path entries from the resource resolver to be used as the prefix.

The defined search path is used as a prefix to mount this servlet. The number can be -1 which always points to the last search entry. If the specified value is higher than than the highest index of the search paths, the last entry is used. The index starts with 0. If the value of this property is a string and parseable as a number, the value is treated as if it would be a number. If this property is not specified, it defaults to the default configuration of the sling servlet resolver.
So if:

  • prefix=0 or prefix=/apps/, then it will accept the default request(relative path of resourceType) and the resourceType starts with “/apps”.because /apps is the first index of search path entry.
  • prefix=1 or prefix =/libs/ then it will accept the default request(relative path of resourceType) and the resourceType starts with “/libs”
  • the default scenario is prefix=-1, then it will accept the default request(relative path of resourceType) and the resourceType starts with “/libs” because /libs is last search entry.


Note:Binding resources by paths is discouraged.
Always try to register servlet using resourceTypes in place of paths.You can use selectors and extension to uniquely identify a servlet.

@Component(service=Servlet.class,

property={

Constants.SERVICE_DESCRIPTION + “=Simple Demo Servlet“,

“sling.servlet.methods=” + HttpConstants.METHOD_GET,

“sling.servlet.resourceTypes=”+ “sling/servlet/default”,

“sling.servlet.selectors=”+ “data”,

“sling.servlet.extensions=”+ “sample”
})

public class MyServlet extends SlingSafeMethodsServlet {
@Override

protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)throws IOException

{

}

}

The request can be:

http://{server host:server port}/{any path}.data.json

The value of “sling.servlet.resourceTypes” is “sling/servlet/default” to handle all kinds of requests having any path.We can also consider it as a default resourceType.

 

There is an OSGi Configuration named Apache Sling Servlet/Script Resolver and Error Handler in the felix console

Fig – Servlet/Script resolver configuration

There are four options in this configuration:

    • Servlet Registration Root Path:If the servlet don’t have prefix, the value of prefix need to be picked from this configuration.
  • Cache Size: This property configures the size of the cache used for script resolution.To see the scripts which are being cached
    1. Go to the Felix console.
    2. Go to Sling->Script Cache Status
Fig – Check Sling Cache Status in felix console

The cache of script resolution can be seen here:

Fig – Check Cached Script in felix console
  • Execution Paths: The paths to search for executable scripts. This configuration means : All the paths starts with the paths they have provided will be allowed.

If no path is specified, this will be treated like (/=root) which allows all scripts. If we add one path without ending with /, then it means it will only allow exact path.

  • Default Extension:The list of extensions for which the default behavior will be used.

There is a sling resolver test provided by Felix console where we can check that a particular request resolves to which servlet.

Fig – Servlet Resolver option in felix 
Fig – Check servlet is resolving or not

Link Checker AEM6.3

AEM External link checker:-

AEM Link Checker is based on an eventHandler and gets triggered on creates and updates for /content and its child nodes. All content under selected root path is parsed and links are validated. All the validation of links is done asynchronously in the background and the HTML is updated based on verification results.

Note:- If you are having huge repository (/content), that includes frequent updation of links. Then it is not advised to use link checker due to performance issues. As it gets triggered periodically and traverse the whole repository for validating links. This may cause slowness in your author instance.

Now lets see how aem link checker works:-

As soon as author save any link on page, either using rte or any custom component. Link checker eventHandler gets triggered.

Link checker event Handler traverse /content node and checks for new/updated links, once found it will store that mapping under /var/linkchecker cache folder.

Then control goes to Day CQ Link Checker Service, It checks for the scheduler.period configuration. Once scheduler time is met, it triggers the scheduler to validate the links syntax and structure against all the given configuration like the special prefix that it has to ignore during validation and the patter that the link check should use to verify the syntax of the url.

Once the syntax is validated the results are then pushed to  /etc/linkchecker.html. But the links will remain in pending state, until Day CQ Link Checker Task scheduler validated these links by making an ajax GET call. AEM link checker scheduler Day CQ Link Checker Task  runs periodically to check validity of valid and in valid links that are store under /etc/linkchecker.html.

Administrator user can configure the frequency on which he want to run this scheduler by updating Scheduler Period property its default value is 3600 sec. Once triggered it will remove all the invalid or unreachable links from /etc/linkchecker.html(http://localhost:4502/etc/linkchecker.html).

AEM Link checker is configured using below four services:-

  • Day CQ Link Checker Info Storage Service – configures the link cache size. default is 500.
  • Day CQ Link Checker Service – Configure the frequency of background check, default interval is 5 seconds
  • Day CQ Link Checker Task – Configure the frequency of background check for validating links.
  • Day CQ Link Checker Transformer – config for all the elements that need to be transformed by the link checker and rewritten.

AEM internal link checker:- Internal Links are validated as soon as content author add any internal links (repository links ex: /content/we-retail/ca) on page either using rte or any custom component. After validation, if url is no longer valid, then they are removed on the publisher or shown as broken links on the author.

Fixing broken links that link checker is not able to validate:-

Sometimes, you might run into a broken link situation means link is not available on publish even though it is a valid link. This might be because aem link checker automatically checks links and will not publish a broken link. Sometimes it is good as you have a self monitoring system that prevents you from publishing a broken link but what happen when you know that the link is correct even though aem is not able to publish it as it is considering it as broken, then it is a problem.

There are two types of links that link checker requires configuration for validating:- Links that have a special prefix (ex: href=”tel:123-123-1234″ or href=”*|something|*”). Links that after post processing having query param, which you want to mark as always valid or skip validation.

 

Replication in AEM 6.3

Replication agents are central to Adobe Experience Manager (AEM) as the mechanism used to:

  • Publish (activate) content from an author to a publish environment.
  • Explicitly flush content from the Dispatcher cache.
  • Return user input (for example, form input) from the publish environment to the author environment (under control of the author environment).

Requests are queued to the appropriate agent for processing.

User data (users, user groups, and user profiles) are not replicated between author and publish instances.

For multiple publish instances, user data is Sling distributed when User Synchronization is enabled.

Replicating from Author to Publish

Replication, to a publish instance or dispatcher, takes place in several steps:

  • 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.
  • 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.
chlimage_1

Replicating from Publish to Author

Some features allow users to enter data on a publish instance.

In some cases, a type of replication known as reverse replication, is needed to return this data to the author environment from where it is redistributed to other publish environments.  Due to security considerations, any traffic from the publish to the author environment must be strictly controlled.

Reverse replication uses an agent in the publish environment which references the author environment. This agent places the data into an outbox. This outbox is matched with replication listeners in the author environment. The listeners poll the outboxes to collect any data entered and then distribute it as necessary. This ensures that the author environment controls all traffic.

In other cases, such as for Communities features (for example, forums, blogs, comments, and reviews), the amount of user generated content (UGC) being entered in the publish environment is difficult to efficiently synchronize across AEM instances using replicaiton.

AEM Communities never uses replication for UGC.  Instead, the deployment for Communities requires a common store for UGC.

Replication – Out of the Box

 

To follow this example and use the default replication agents you need to Install AEM with:

  • the author environment on port 4502
  • the publish environment on port 4503

Enabled by default :

  • Agents on author : Default Agent (publish)

Effectively disabled by default (as of AEM 6.1) :

  • Agents on author  : Reverse Replication Agent (publish_reverse)
  • Agents on publish : Reverse Replication (outbox)

Replication Agents – Out of the Box

The following agents are available in a standard AEM installation:

  • Default Agent
    Used for replicating from author to publish.
  • Dispatcher Flush
    This is used for managing the Dispatcher cache.
  • Reverse Replication
    Used for replicating from publish to author.  Reverse replication is not used for Communities features, such as forums, blogs, and comments.  It is effectively disabled as the outbox is not enabled.  Use of reverse replication would require custom configuration.
  • Static Agent
    This is an “Agent that stores a static representation of a node into the filesystem.”.
    For example with the default settings, content pages and dam assets are stored under /tmp, either as HTML or the appropriate asset format.
    This was requested so that when the page is requested directly from the application server the content can be seen. This is a specialized agent and (probably) will not be required for most instances.

Replication Agents – Configuration Parameters

When configuring a replication agent from the Tools console, four tabs are available within the dialog:

Settings

  • Name : A unique name for the replication agent.

  • Description : A description of the purpose this replication agent will serve.

  • Enabled : Indicates whether the replication agent is currently enabled.

    When the agent is enabled the queue will be shown as:

    • Active when items are being processed.
    • Idle when the queue is empty.
    • Blocked when items are in the queue, but cannot be processed; for example, when the receiving queue is disabled.
  • Serialization Type : The type of serialization:

    • Default: Set if the agent is to be automatically selected.
    • Dispatcher Flush: Select this if the agent is to be used for flushing the dispatcher cache.
  • Retry Delay : The delay (waiting time in milliseconds) between two retries, should a problem be encountered.

    Default: 60000

  • Agent User Id : Depending on the environment, the agent will use this user account to:

    • collect and package the content from the author environment
    • create and write the content on the publish environment

    Leave this field empty to use the system user account (the account defined in sling as the administrator user; by default this is admin).

     

    Caution:

    For an agent on the author environment this account must have read access to all paths that you want to have replicated.

             For an agent on the publish environment this account must have the create/write access required to replicate the content.

     

    Note:

    This can be used as a mechanism for selecting specific content for replication.

  • Log Level : Specifies the level of detail to be used for log messages.

    • Error: only errors will be logged
    • Info: errors, warnings and other informational messages will be logged
    • Debug: a high level of detail will be used in the messages, primarily for debug purposes

    Default: Info

  • Use for reverse replication : Indicates whether this agent will be used for reverse replication; returns user input from the publish to author environment.

  • Alias update : Selecting this option enables alias or vanity path invalidation requests to Dispatcher.

Transport

  • URI

    This specifies the receiving servlet at the target location. In particular, you can specify the hostname (or alias) and context path to the target instance here.

    For example:

    The protocol specified here (HTTP or HTTPS) will determine the transport method.

    For Dispatcher Flush agents, the URI property is used only if you use path-based virtualhost entries to differentiate between farms, you use this field to target the  farm to invalidate. For example, farm #1 has a virtual host of http://www.mysite.com/path1/* and farm #2 has a virtual host of http://www.mysite.com/path2/*. You can use a URL of /path1/invalidate.cache to target the first farm and /path2/invalidate.cache to target the second farm.

  • User

    User name of the account to be used for accessing the target.

  • Password

    Password for the account to be used for accessing the target.

  • NTLM Domain

    Domain for NTML authentication.

  • NTLM Host

    Host for NTML authentication.

  • Enable relaxed SSL

    Enable if you want self-certified SSL certificates to be accepted.

  • Allow expired certs

    Enable if you want expired SSL certificates to be accepted.

Proxy

The following settings are only needed if a proxy is needed:

  • Proxy Host

    Hostname of the proxy used for transport.

  • Proxy Port

    Port of the proxy.

  • Proxy User

    User name of the account to be used.

  • Proxy Password

    Password of the account to be used.

  • Proxy NTLM Domain

    The proxy NTLM domain.

  • Proxy NTLM Host

    The proxy NTLM domain.

Extended

  • Interface

    Here you can define the socket interface to bind to.

    This sets the local address to be used when creating connections. If this is not set, the default address will be used. This is useful for specifying the interface to use on multi-homed or clustered systems.

  • HTTP Method

    The HTTP method to be used.

    For a Dispatcher Flush agent this is nearly always GET and should not be changed (POST would be another possible value).

  • HTTP Headers

    These are used for Dispatcher Flush agents and specify elements that must be flushed.

    For a Dispatcher Flush agent the three standard entries should not need changing:

    • CQ-Action:{action}
    • CQ-Handle:{path}
    • CQ-Path:{path}

    These are used, as appropriate, to indicate the action to be used when flushing the handle or path. The sub-parameters are dynamic:

    • {action} indicates a replication action
    • {path} indicates a path

    They are substituted by the path/action relevant to the request and therefore do not need to be “hardcoded”:

    Note:

    If you have installed AEM in a context other than the recommended default context, then you will need to register the context in the HTTP Headers. For example:
    CQ-Handle:/<yourContext>{path}

  • Close Connection

    Enable to close the connection after each request.

  • Connect Timeout

    Timeout (in milliseconds) to be applied when trying to establish a connection.

  • Socket Timeout

    Timeout (in milliseconds) to be applied when waiting for traffic after a connection has been established.

  • Protocol Version

    Version of the protocol; for example 1.0 for HTTP/1.0.

Triggers

These settings are used to define triggers for automated replication:

  • Ignore default

    If checked, the agent is excluded from default replication; this means it will not be used if a content author issues a replication action.

  • On Modification

    Here a replication by this agent will be automatically triggered when a page is modified. This is mainly used for Dispatcher Flush agents, but also for reverse replication.

  • On Distribute

    If checked, the agent will automatically replicate any content that is marked for distribution when it is modified.

  • On-/Offtime reached

    This will trigger automatic replication (to activate or deactivate a page as appropriate) when the ontimes or offtimes defined for a page occur. This is primarily used for Dispatcher Flush agents.

  • On Receive

    If checked, the agent will chain replicate whenever receiving replication events.

  • No Status Update

    When checked the agent will not force a replication status update.

  • No Versioning

    When checked the agent will not force versioning of activated pages.

Configuring your Replication Agents

Controlling Access to Replication Agents

Access to the pages used to configure the replication agents can be controlled by using user and/or group page permissions on the etc/replication node.

Note:

Setting such permissions will not affect users replicating content (e.g. from the Websites console or sidekick option). The replication framework does not use the “user session” of the current user to access replication agents when replicating pages.

  • Caution:

    Do not use the “Test Connection” link for the Reverse Replication Outbox on a publish instance.

    If a replication test is performed for an Outbox queue, any items that are older than the test replication will be re-processed with every reverse replication.

    If such items already exist in a queue, they can be found with the following XPath JCR query and should be removed.

    /jcr:root/var/replication/outbox//*[@cq:repActionType=’TEST’]

How do I use reverse replication and what’s necessary to make sure that it works?

Out-of-the box, only cq:Page nodes are reverse replicated. For any other node, it’s necessary to use the two last methods, as a project-specific implementation.

There are three possibilities

  • Use the SlingPostServlet (that is, do not create any custom post servlets or POST.jsp to handle the incoming requests) so that it implicitly triggers a related PageEvent. Then set a property name “cq:distribute” and set its value to “true” on the nodes you want to reverse replicate.
    • To implement this solution, it’s unnecessary to write any code. You can use the Form component to set all the necessary hidden fields.
  • Use your own code that accesses the repository, modify the properties “cq:lastModified,” “cq:lastModifiedBy” and “cq:distribute.”
    • Posted data can be controlled, internal code writes the data.
    • To implement this solution, it’s necessary to write the code for your project.
  • Use your own code that calls the replicate method from Replicator service with options to use distribution mode.
    • Replication is controlled from your code.
    • To implement this solution, write the code specific for your project.

Use your own code to implement a reverse replication solution

  • Add the following code to fire the event related to the page you want to reverse replicate (the example below was extracted from sample PostDataServlet.java):
...
  // set the page to hide in the navigation
  Node pageContainer = newCommentPage.getContentResource().adaptTo(Node.class);
  pageContainer.setProperty("cq:lastModified", Calendar.getInstance());
  pageContainer.setProperty("cq:lastModifiedBy", session.getUserID());
  pageContainer.setProperty("cq:distribute", true);
...
  session.save();
...

 

Attached is an example using a component to render the form and display the previous post. For each post, it creates a subpage that contains a paragraph with text in it. By doing so, it ensures that each post can be managed separately (and avoids collision with posts that could be generated from other publish instances). The storage location is defined as a parameter in the component dialog (that is, /content/usergenerated/comments/form1, which you can create using a folder in the siteadmin).

On the author instance, you can define a workflow model that would be launched when a page is created below your comments page.

Make sure that you clear the cq:distribute value in your workflow, if you reactivate the content on author to the publish, otherwise it goes in an endless loop !!!

On the publish instance, make sure that the user has sufficient rights to create content. If you test with anonymous, then change the rights accordingly using CRX Explorer for the given jcr path).

Note on replication

For replication to work properly then store data with the following rules:
(1) the replicated (root) node’s nodetype must extend nt:hierarchyNode
(2) all direct child nodes that are not nt:hierarchyNodes must be aggregated
(3) the subtrees of all nodes from (2), apart from nodetypes, must be aggregated

Adobe recommends to use the cq:Page (/jcr:content) as container for your data, as you can then easily manage it and use it with the user interface (siteadmin, and so on). You can use PageManager API to create the page.

 

Note:

Certain terms related to publishing can be confused:

  • Publish / Unpublish
    These are the primary terms for the actions that make your content publicly available on your publish environment (or not).
  • Activate / Deactivate
    These terms are synonymous with publish/unpublish.
  • Replicate / Replication
    These are the technical terms describing the movement of data (e.g. page content, files, code, user comments) from one environment to another such as when publishing or reverse-replicating user comments.

Note:

If you do not have the required privileges for publishing a specific page:

  • A workflow will be triggered to notify the appropriate person of your request to publish.
  • This workflow may have been customized by your development team.
  • A message will be displayed briefly to notify you that the workflow was triggered.

Depending on your location, you can publish:

  • From the page editor
  • From the sites console

From Page Editor

Depending on whether the page has references that need publishing:

  • The page will be published directly if there are no references to be published.
  • If the page has references that need publishing, these will be listed in the Publish wizard, where you can either:
    • Specify which of the assets/tags/etc. you want to publish together with the page, then use Publish to complete the process.
    • Use Cancel to abort the action.

Note:

Publishing from the editor is a shallow publish, i.e. only the selected page/pages is/are published and any child pages are not.

From Sites Console

In the sites console there are two options for publishing:

  • Quick Publish
  • Manage Publication

Quick Publish

Quick Publish is for simple cases and publishes the selected page(s) immediately without any further interaction. Because of this, any non-published references will also be published automatically.

Note:

Quick Publish is a shallow publish, i.e. only the selected page/pages is/are published and any child pages are not.

Manage Publication

Manage Publication offers more options than Quick Publish, allowing for the inclusion of child pages, customization of the references, and starting any applicable workflows as well as offering the option to publish at a later date.

Client Library in AEM 6.3

Modern websites rely heavily on client-side processing driven by complex JavaScript and CSS code. Organizing and optimizing the serving of this code can be a complicated issue.

To help deal with this issue, AEM provides Client-side Library Folders, which allow you to store your client-side code in the repository, organize it into categories, and define when and how each category of code is to be served to the client. The client-side library system then takes care of producing the correct links in your final webpage to load the correct code.

How Client-Side Libraries Work in AEM

The standard way to include a client-side library (that is, a JS or CSS file) in the HTML of a page is simply to include a <script> or <link> tag in the JSP for that page, containig the path to the file in question. For example,

<head>
   ...
   <script type="text/javascript" src="/etc/clientlibs/granite/jquery/source/1.8.1/jquery-1.8.1.js"></script>
   ...
</head>

While this approach works in AEM, it can lead to problems when pages and their constituent components become complex. In such cases there is the danger that multiple copies of the same JS library may be included in the final HTML output. To avoid this and to allow logical organization of client-side libraries AEM uses client-side library folders.

A client-side library folder is a repository node of type cq:ClientLibraryFolder. It’s definition in CND notation is

[cq:ClientLibraryFolder] > sling:Folder
  - dependencies (string) multiple
  - categories (string) multiple
  - embed (string) multiple
  - channels (string) multiple

 

By default, cq:ClientLibraryFolder nodes can be placed anywhere within the /apps, /libs and /etc subtrees of the repository (these defaults, and other settings can be controlled through the Adobe Granite HTML Library Manager panel of the System Console).

Each cq:ClientLibraryFolder is populated with a set of JS and/or CSS files, along with a few supporting files (see below). The properties of the cq:ClientLibraryFolder are configured as follows:

  • categories: Identifies the categories into which the set of JS and/or CSS files within this cq:ClientLibraryFolder fall. The categories property, being multi-valued, allows a library folder to be part of more than one category (see below for how this may be useful).
  • dependencies: This is a list of other client library categories on which this library folder depends. For example, given two cq:ClientLibraryFolder nodes F and G, if a file in F requires another file in G in order to function properly, then at least one of the categories of G should be among the dependencies of F.
  • embed: Used to embed code from other libraries. If node F embeds nodes G and H, the resulting HTML will be a concetration of content from nodes G and H.
  • allowProxy: If a client library is located under /apps, this property allows acces to it via proxy servlet.

Referencing Client-Side Libraries

Because HTL is the preferred technology for developing AEM sites, HTL should be used to include client-side libraries in AEM. However it is also possible to do so using JSP.

Using HTL

In HTL, client libraries are loaded through a helper template provided by AEM, which can be accessed through data-sly-use. Three templates are available in this file, which can be called through data-sly-call:

  • css – Loads only the CSS files of the referenced client libraries.
  • js  – Loads only the JavaScript files of the referenced client libraries.
  • all – Loads all the files of the referenced client libraries (both CSS and JavaScript).

Each helper template expects a categories option for referencing the desired client libraries. That option can be either an array of string values, or a string containing a comma separated values list.

Using JSP

Add a ui:includeClientLib tag to your JSP code to add a link to client libraries in the generated HTML page. To reference the libraries, you use the value of the categories property of the ui:includeClientLib node.

<%@taglib prefix="ui" uri="http://www.adobe.com/taglibs/granite/ui/1.0" %>
<ui:includeClientLib categories="<%= categories %>" />

 

For example, the /etc/clientlibs/foundation/jquery node is of type cq:ClientLibraryFolder with a categories property of value cq.jquery. The following code in a JSP file references the libraries:

<ui:includeClientLib categories="cq.jquery"/>

 

The generated HTML page contains the following code:

<script type="text/javascript" src="/etc/clientlibs/foundation/jquery.js"></script>

 

 

Caution:

<cq:includeClientLib>, which in the past was commonly used to include client libraries, has been deprecated since AEM 5.6. <ui:includeClientLib> should be used instead as detailed above.

Creating Client Library Folders

Create a cq:ClientLibraryFolder node to define JavaScript and Cascading Style Sheet libraries and make them available to HTML pages. Use the categories property of the node to identify the library categories to which it belongs.

The node contains one or more source files that, at runtime, are merged into a single JS and/or CSS file. The name of the generated file is the node name with either the .js or .css file name extension. For example, the library node named cq.jquery results in the generated file named cq.jquery.js or cq.jquery.css.

Client library folders contain the following items:

  • The JS and/or CSS source files to merge.
  • Resources that support CSS styles, such as image files.Note: You can use subfolders to organize source files.
  • One js.txt file and/or one css.txt file that identifies the source files to merge in the generated JS and/or CSS files.

 

The web client must have permissions to access the cq:ClientLibraryFolder node. You can also expose libraries from secured areas of the repository .

Overriding Libraries in /lib

Client library folders located below /apps take precedence over same-named folders that are similarly located in /libs. For example, /apps/cq/ui/widgets takes precedence over /libs/cq/ui/widgets. When these libraries belong to the same category, the library below /apps is used.

Locating a Client Library Folder and Using the Proxy Client Libraries Servlet

In previous versions, client library folders were located below /etc/clientlibs in the repository. This is still supported, however it is recommended that client libraries now be located under /apps. This is to locate the client libraries near the other scripts, which are generally found below /apps and /libs.

Note:

In order to better isolate code from content and configuration, it is recommended to locate client libraries under /apps and expose them via /etc.clientlibs by leveraging the allowProxy property.

In order for the client libraries under /apps to be accessible, a proxy servelt is used. The ACLs are still enforced on the client library folder, but the servlet allows for the content to be read via /etc.clientlibs/ if the allowProxy property is set to true.

A static resource can only be accessed via the proxy, if it resides below a resource below the client library folder.

As an example:

  • You have a clientlib in /apps/myproject/clientlibs/foo
  • You have a static image in /apps/myprojects/clientlibs/foo/resources/icon.png

Then you set the allowProxy property on foo to true.

  • You can then request /etc.clientlibs/myprojects/clientlibs/foo.js
  • You can then reference the image via /etc.clientlibs/myprojects/clientlibs/foo/resources/icon.png

Caution:

When using proxied client libraries, the AEM Dispatcher configuration may require an update to ensure the URIs with the extension clientlibs are allowed.

Caution:

Adobe recommends locating client libraries under /apps and making them available using the proxy servlet. However keep in mind that best practice still requires that public sites never include anything that is served directly over an /apps or /libs path.

 

Linking to Dependencies

When the code in your client library folder references other libraries, identify the other libraries as dependencies. In the JSP, the ui:includeClientLib tag that references your client library folder causes the HTML code to include a link to your generated library file as well as the dependencies.

The dependencies must be another cq:ClientLibraryFolder. To identify dependencies, add a property to your cq:ClientLibraryFolder node with the following attributes:

  • Name: dependencies
  • Type: String[]
  • Values: The value of the categories property of the cq:ClientLibraryFolder node that the current library folder depends on.

For example, the /etc/clientlibs/myclientlibs/publicmain has a dependency on the cq.jquery library. The JSP that references the main client library generates HTML that includes the following code:

<script src="/etc/clientlibs/foundation/cq.jquery.js" type="text/javascript">
<script src="/etc/clientlibs/mylibs/publicmain.js" type="text/javascript">

Embedding Code From Other Libraries

You can embed code from a client library into another client library. At runtime, the generated JS and CSS files of the embedding library includes the code of the embedded library.

Embedding code is useful for providing access to libraries that are stored in secured areas of the repository.

App-Specific Client Library Folders

It is a best practice to keep all application-related files in their application folder below /app. It is also a best practice to deny access for web site visitors to the /app folder. To satisfy both best practices, create a client library folder below the /etc folder that embeds the client library that is below /app.

Use the categories property to identify the client library folder to embed. To embed the library, add a property to the embedding cq:ClientLibraryFolder node, using the following property attributes:

  • Name: embed
  • Type: String[]
  • Value: The value of the categories property of the cq:ClientLibraryFolder node to embed.

Using Embedding to Minimize Requests

In some cases you may find that the final HTML generated for typical page by your publish instance includes a relatively large number of <script> elements, particularly if your site is using client context information for analaytics or targeting. For example, in a non-optimized project you might find the following series of <script> elements in the HTML for a page:

<script type="text/javascript" src="/etc/clientlibs/granite/jquery.js"></script>
<script type="text/javascript" src="/etc/clientlibs/granite/utils.js"></script>
<script type="text/javascript" src="/etc/clientlibs/granite/jquery/granite.js"></script>
<script type="text/javascript" src="/etc/clientlibs/foundation/jquery.js"></script>
<script type="text/javascript" src="/etc/clientlibs/foundation/shared.js"></script>
<script type="text/javascript" src="/etc/clientlibs/granite/underscore.js"></script>
<script type="text/javascript" src="/etc/clientlibs/foundation/personalization/kernel.js"></script>

In such cases, it can be useful to combine all the required client library code in to a single file so that the number of back and forth requests on page load is reduced. To do this you can embed the required libraries into you app-specific client library using the embed property of the cq:ClientLibraryFolder node.

The following client library categories are incuded with AEM. You should embed only those that are required for he functioning of your particular site. However, you should maintain the order listed here:

  1. browsermap.standard
  2. browsermap
  3. jquery-ui
  4. cq.jquery.ui
  5. personalization
  6. personalization.core
  7. personalization.core.kernel
  8. personalization.clientcontext.kernel
  9. personalization.stores.kernel
  10. personalization.kernel
  11. personalization.clientcontext
  12. personalization.stores
  13. cq.collab.comments
  14. cq.collab.feedlink
  15. cq.collab.ratings
  16. cq.collab.toggle
  17. cq.collab.forum
  18. cq.cleditor

Paths in CSS Files

When you embed CSS files, the generated CSS code uses paths to resources that are relative to the embedding library. For example, the publicly-accessible library /etc/client/libraries/myclientlibs/publicmain embeds the/apps/myapp/clientlib client library:

 

The main.css file contains the following style:

body {
  padding: 0;
  margin: 0;
  background: url(images/bg-full.jpg) no-repeat center top;
  width: 100%;
}

The CSS file that the publicmain node generates contains the following style, using the URL of the original image:

body {
  padding: 0;
  margin: 0;
  background: url(../../../apps/myapp/clientlib/styles/images/bg-full.jpg) no-repeat center top;
  width: 100%;
}

Using a Library for Specific Mobile Groups

Use the channels property of a client library folder to identify the mobile group that uses the library. The channels property is useful when libraries of the same category are designed for different device capabilities.

To associate a client library folder with a device group, add a property to your cq:ClientLibraryFolder node with the following attributes:

  • Name: channels
  • Type: String[]
  • Values: The name of the mobile group. To exclude the library folder from a group, prefix the name with an exclamation mark (“!”).

For example, the following table lists the value of the channels property for each client library folder of the cq.widgetscategory:

Client library folder Value of channels property
/libs/cq/analytics/widgets !touch
/libs/cq/analytics/widgets/themes/default !touch
/libs/cq/cloudserviceconfigs/widgets !touch
/libs/cq/searchpromote/widgets !touch
/libs/cq/searchpromote/widgets/themes/default [no value]
/libs/cq/touch/widgets touch
/libs/cq/touch/widgets/themes/default touch
/libs/cq/ui/widgets !touch
/libs/cq/ui/widgets/themes/default !touch

Using Preprocessors

AEM allows for pluggable preprocessors and ships with support for YUI Compressor for CSS and JavaScript and Google Closure Compiler (GCC) for JavaScript with YUI set as AEM’s default preprocessor.

The pluggable preprocessors allow for flexible usage including:

  • Defining ScriptProcessors that can process script sources
  • Processors are configurable with options
  • Processors can be used for minification, but also for non-minified cases
  • The clientlib can define which processor to use

Note:

By default, AEM uses the YUI Compressor. Switching to GCC compressor for particular clientlibs may solve some issues observed when using YUI.

Caution:

Do not place a minified library in a client library. Instead provide the raw library and if minification is required, use the options of the preprocessors.

Usage

You can choose to configure the preprocessors configuration per clientlibrary or system-wide.

  • Add the multivalue properties cssProcessor and jsProcessor on the clientlibrary node
  • Or define the system default configuration via the HTML Library Manager OSGi configuration

A preprocessor configuration on the clientlib node takes precedence over the OSGI configuration.

Format and Examples

Format

config:= mode ":" processorName options*;
mode:= "default" | "min";
processorName := "none" | <name>;
options := ";" option;
option := name "=" value;

 

YUI Compressor for CSS Minification and GCC for JS

cssProcessor: ["default:none", "min:yui"]
jsProcessor: ["default:none", "min:gcc;compilationLevel=advanced"]

Typescript to Preprocess and Then GCC to Minify and Obfuscate

jsProcessor: [
   "default:typescript",
   "min:typescript",
   "min:gcc;obfuscate=true"
]

Additional GCC Options

failOnWarning (defaults to "false")
languageIn (defaults to "ECMASCRIPT5")
languageOut (defaults to "ECMASCRIPT5")
compilationLevel (defaults to "simple") (can be "whitespace", "simple", "advanced")

Set System Default Minifier

YUI is set as the default minifier in AEM. To change this to GCC, follow these steps.

  • Go to Apache Felix Config Manager at http://localhost:4502/system/console/configMgr

  • Find and edit the Adobe Granite HTML Library Manager.

  • Enable the Minify option (if not already enabled).

  • Set the value JS Processor Default Configs to min:gcc.

    Options can be passed if separated with a semicolon e.g. min:gcc;obfuscate=true.

  • Click Save to save the changes.

Debugging Tools

AEM provides several tools for debugging and testing client library folders.

See Embedded Files

To trace the origin of embedded code, or to ensure that embedded client libraries are producing the expected results, you can see the names of the files that are being embedded at runtime. To see the file names, append the debugClientLibs=trueparameter to the URL of your web page. The library that is generated contains @import statements instead of the embedded code.

In the example in the previous Embedding Code From Other Libraries section, the /etc/client/libraries/myclientlibs/publicmain client library folder embeds the /apps/myapp/clientlib client library folder. Appending the parameter to the web page produces the following link in the web page’s source code:

<link rel="stylesheet" href="/etc/clientlibs/mycientlibs/publicmain.css">

 

Opening the publicmain.css file reveals the following code:

@import url("/apps/myapp/clientlib/styles/main.css");

 

<p”>Use the following procedure to see the names of embedded files:</p”>

  1. In the address box of your web browser, append the following text to the URL of your HTML:?debugClientLibs=true
  2. When the page loads, view the page source.
  3. Click the link that is provided as the href for the link element to open the file and view the source code.

Discover Client Libraries

The /libs/cq/ui/components/dumplibs/dumplibs component generates a page of information about all client library folders on the system. The /libs/cq/ui/content/dumplibs node has the component as a resource type. To open the page, use the following URL (use a different host and port as required):

http://localhost:4502/libs/cq/ui/content/dumplibs.test.html

The information includes the library path and type (CSS or JS), and the values of the library attributes, such as categories and dependencies. Subsequent tables on the page show the libraries in each category and channel.

See Generated Output

The dumplibs component includes a test selector that displays the source code that is generated for ui:includeClientLib tags. The page includes code for different combinations of js, css, and themed attributes.

  1. Use one of the following methods to open the Test Output page:

    The default page shows output for tags with no value for the categories attribute.

  2. To see the output for a category, type the value of the client library’s categories property and click Submit Query.

Configuring Library Handling for Development and Production

The HTML Library Manager service processes cq:ClientLibraryFolder tags and generates the libraries at runtime. The type of environment, development or production, determines how you should configure the service:

  • Increase security: Disable debugging
  • Improve performance: Remove whitespace and compress libraries.
  • Improve readability: Include whitespace and do not compress.

 

Components AEM6.3

When you start to develop new components you need to understand the basics of their structure and configuration.

This process involves reading the theory and looking at the wide range of component implementations in a standard AEM instance. This latter approach is slightly complicated by the fact that although AEM has shifted to the modern, touch-enabled UI, it continues to support the classic UI.

Overview

This section covers key concepts and issues as an introduction to the details needed when developing your own components.

Planning

Before starting to actually configure/code your component you should ask:

  • What exactly do you need the new component to do?
    • A clear specification helps at all stages of development, testing and handover.
      Details may change over time, but the specification can be updated (though changes should be documented too).
  • Do you need to create your component from scratch, or can you inherit the basics from an existing component?
    • There is no need to reinvent the wheel.
    • There are several mechanisms provided by AEM to allow you to inherit and extend details from another component definition including override, overlay and the Sling Resource Merger.
  • Will your component require logic to select/manipulate the content?
    • Logic should be kept separate from the user interface layer. HTL is designed to help ensure this happens.
  • Will your component need CSS formatting?
    • CSS formatting should be kept separate from the component definitions. Define conventions for naming your HTML elements so that you can modify them through external CSS files.
  • What security aspects should I take into consideration?

Touch-Enabled vs Classic UI

Before any serious discussion starts about developing components you need to know which UI your authors will be using:

  • Touch-Enabled UI
    The standard user interface that was introduced in AEM 5.6.0 as a preview and extended in 6.x. It is based on the unified user experience for the Adobe Marketing Cloud, using the underlying technologies of Coral UI and Granite UI.
  • Classic UI
    User interface based on ExtJS technology that was introduced with CQ 5.1.

Components can be implemented to support the touch-enabled UI, the classic UI or both. When looking at a standard instance you will also see out-of-the-box components that were originally designed for the classic UI, or the touch-enabled UI, and/or both.

For this reason we will cover the basics of both, and how to recognize them, on this page.

Content Logic and Rendering Markup

It is recommended to keep the code responsible for markup and rendering separate from the code that controls the logic used to select the component’s content.

This philosophy is supported by HTL, a templating language that is purposely limited to ensure a real programming language is used to define the underlying business logic. This (optional) logic is invoked from HTL with a specific command. This mechanism highlights the code that is called for a given view and, if required, allows specific logic for different views of the same component.

HTL vs JSP

HTL is a HTML templating language, introduced with AEM 6.0.

The discussion of whether to use HTL or JSP (Java Server Pages) when developing your own components should be straightforward as HTL is now the recommended scripting language for AEM.

Both HTL and JSP can be used for developing components for both the classic and the touch-enabled UI. Although there can be a tendency to assume that HTL is only for the touch-enabled UI and JSP for the classic UI, this is a misconception and more due to timing. The touch-enabled UI and HTL were incorporated into AEM over approximately the same period. Since HTL is now the recommended language, it is being used for new components, which tend to be for the touch-enabled UI.

Note:

The exceptions are Granite UI Foundation Form Fields (as used in dialogs). These still require the use of JSP.

Developing Your Own Components

To create your own components for the appropriate UI see (after reading this page):

A quick way to get started is to copy an existing component and then make the changes you want. To learn how to create your own components and add them to the paragraph system see:

Moving Components to the Publish Instance

The components that render content must be deployed on the same AEM instance as the content. Therefore, all components that are used for authoring and rendering pages on the author instance must be deployed on the publish instance. When deployed, the components are available to render activated pages.

Use the following tools to move your components to the publish instance:

Note:

These mechanisms can also be used for transferring your component between other instances e.g. from your development to your test instance.

Components to be Aware of from the Start

  • Page:
    • AEM has the page component (cq:Page).
    • This is a specific type of resource that is important for content management.
    • A page corresponds to a web page holding content for your website.
  • Paragraph system(s):
    • The paragraph system is a key part of a website as it manages a list of paragraphs. It is used to hold and structure the individual components that hold the actual content.
    • You can create, move, copy, and delete paragraphs in the paragraph system.
    • You can also select the components to be available for use within a specific paragraph system.
    • There are various paragraph systems available within a standard instance (e.g. parsys, responsivegrid).

Structure

The structure of an AEM component is powerful and flexible, the main considerations are:

  • Resource Type
  • Component Definition
  • Properties and Child Nodes of a Component
  • Dialogs
  • Design Dialogs
  • Component Availability
  • Components and the Content They Create

Resource Type

A key element of the structure is the resource type.

  • Content structure declares intentions.
  • Resource type implement them.

This is an abstraction that helps ensure that even when the look and feel changes over time,
 the intention stays the time.

Component Definition

Component Basics

The definition of a component can be broken down as follows:

  • AEM components are based on Sling.
  • AEM components are (usually) located under:
    • HTL: /libs/wcm/foundation/components
    • JSP: /libs/foundation/components
  • Project/Site specific components are (usually) located under:
    • /apps/<myApp>/components
  • AEM standard components are defined as cq:Component and have the key elements:
    • jcr properties:
      A list of jcr properties; these are variable and some may be optional though the basic structure of a component node, its properties and subnodes are defined by the cq:Component definition
    • Resources:
      These define static elements used by the component.
    • Scripts:
      Are used to implement the behavior of the resulting instance of the component.
  • Root Node:
    • <mycomponent> (cq:Component) – Hierarchy node of the component.
  • Vital Properties:
    • jcr:title – Component title; for example, used as a label when the component is listed in the components browser or sidekick.
    • jcr:description – Description for the component; can be used as mouse-over hint in the components browser or sidekick.
    • Classic UI:
      • icon.png – Icon for this component.
      • thumbnail.png – Image shown if this component is listed within the paragraph system.
    • Touch UI
  • Vital Child Nodes:
    • cq:editConfig (cq:EditConfig) – Defines the edit properties of the component and enables the component to appear in the Components browser or Sidekick.
      Note: if the component has a dialog, it will automatically appear in the Components browser or Sidekick, even if the cq:editConfig does not exist.
    • cq:childEditConfig (cq:EditConfig) – Controls author UI aspects for child components that do not define their own cq:editConfig.
    • Touch-Enabled UI:
      • cq:dialog (nt:unstructured) – Dialog for this component. Defines the interface allowing the user to configure the component and/or edit content.
      • cq:design_dialog (nt:unstructured) – Design editing for this component
    • Classic UI:
      • dialog (cq:Dialog) – Dialog for this component. Defines the interface allowing the user to configure the component and/or edit content.
      • design_dialog (cq:Dialog) – Design editing for this component.

Component Icon in Touch UI

The icon or abbreviation for the component is defined via JCR properties of the component when the component is created by the developer. These properties are evaluated in the following order and the first valid property found is used.

  1. cq:icon – String property pointing to a standard icon in the Coral UI library to display in the component browser
    • Use the value of the HTML attribute of the Coral icon.
  2. abbreviation – String property to customize the abbreviation of the component name in the component browser
    • The abbreviation should be limited to two characters.
    • Providing an empty string will build the abbreviation from first two characters of the jcr:title property.
      • For example “Im” for “Image”
      • The localized title will be used to build the abbreviation.
    • The abbreviation is only translated if the component has an abbreviation_commentI18n property, which is then used as translation hint.
  3. cq:icon.png or cq:icon.svg – Icon for this component, which is shown in the component browser
    • 20 x 20 pixels is the size of icons of standard components.
      • Larger icons will be downsized (client-side).
    • The recommended color is rgb(112, 112, 112) -> #707070
    • The background of standard component icons is transparent.
    • Only .png and .svg files are supported.
    • If importing from the file system via Eclipse plugin, filenames need to be esacaped as _cq_icon.png or _cq_icon.svg for example.
    • .png takes precedent over .svg if both are present

If none of the above properties (cq:icon, abbreviation, cq:icon.png or cq:icon.svg) are found on the component:

  • The system will search for the same properties on the super components following the sling:resourceSuperTypeproperty.
  • If nothing or an empty abbreviation is found at the super component level, the system will build the abbreviation from the first letters of the jcr:title property of the current component.

To cancel the inheritance of icons from super components, setting an empty abbreviation property on the component will revert to the default behavior.

The Component Console displays how the icon for a particular component is defined.

SVG Icon Example

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="20px" height="20px" viewBox="0 0 20 20" enable-background="new 0 0 20 20" xml:space="preserve">
    <ellipse cx="5" cy="5" rx="3" ry="3" fill="#707070"/>
    <ellipse cx="15" cy="5" rx="4" ry="4" fill="#707070"/>
    <ellipse cx="5" cy="15" rx="5" ry="5" fill="#707070"/>
    <ellipse cx="15" cy="15" rx="4" ry="4" fill="#707070"/>
</svg>

Properties and Child Nodes of a Component

Many of the nodes/properties needed to define a component are common to both UIs, with differences remaining independent so that your component can work in both environments.

A component is a node of type cq:Component and has the following properties and child nodes:

Name
Type
Description
. cq:Component Current component. A component is of node type cq:Component.
componentGroup String Group under which the component can be selected in the Components browser (touch-enabled UI) or Sidekick (classic UI).
A value of .hidden is used for components that are not available for selection from the UI such as the actual paragraph systems.
cq:isContainer String Indicates whether the component is a container component and therefore can contain other components such as a paragraph system.
cq:dialog nt:unstructured Definition of the edit dialog for the touch-enabled UI.
dialog cq:Dialog Definition of the edit dialog for the classic UI.
cq:design_dialog nt:unstructured Definition of the design dialog for the touch-enabled UI.
design_dialog cq:Dialog  Definition of the design dialog for the classic UI.
dialogPath String Path to a dialog to cover the case when the component does not have a dialog node.
cq:cellName String If set, this property is taken as Cell ID. For more information, please refer to the Knowledge Base article How are Design Cell IDs built.
cq:childEditConfig cq:EditConfig When the component is a container, as for example a paragraph system, this drives the edit configuration of the child nodes.
cq:editConfig cq:EditConfig Edit configuration of the component.
cq:htmlTag nt:unstructured  Returns additional tag attributes that are added to the surrounding html tag. Enables addition of attributes to the automatically generated divs.
cq:noDecoration Boolean If true, the component is not rendered with automatically generated div and css classes.
cq:template nt:unstructured If found, this node will be used as a content template when the component is added from the Components Browser or Sidekick.
cq:templatePath String Path to a node to use as a content template when the component is added from the Components browser or Sidekick. This must be an absolute path, not relative to the component node.
Unless you want to reuse content already available elsewhere, this is not required and cq:template is sufficient (see below).
jcr:created Date Date of creation of the component.
jcr:description String Description of the component.
jcr:title String Title of the component.
sling:resourceSuperType String When set, the component inherits from this component.
virtual sling:Folder Enables creation of virtual components. To see an example, please look at the contact component at:
/libs/foundation/components/profile/form/contact
<breadcrumb.jsp> nt:file Script file.
icon.png nt:file Icon of the component, appears next to the Title in Sidekick.
thumbnail.png nt:file Optional thumbnail that is shown while the component is dragged into place from Sidekick.

If we look at the Text component (either version), we can see these elements:

  • HTL (/libs/wcm/foundation/components/text)

    chlimage_1

     

  • JSP (/libs/foundation/components/text)

    screen_shot_2012-02-13at60457pm

     

Properties of particular interest include:

  • jcr:title – title of the component; this can be used to identify the component, for example, it appears in the component list within the components browser or sidekick
  • jcr:description – description for the component; can be used as mouse-over hint in the component list within sidekick
  • sling:resourceSuperType: this indicates the path of inheritance when extending a component (by overriding a definition)

Child nodes of particular interest include:

  • cq:editConfig (cq:EditConfig) – this controls visual aspects; for example, it can define the appearance of a bar or widget, or can add customized controls
  • cq:childEditConfig (cq:EditConfig) – this controls the visual aspects for child components that do not have their own definitions
  • Touch-Enabled UI:
    • cq:dialog (nt:unstructured) – defines the dialog for editing content of this component
    • cq:design_dialog (nt:unstructured) – specifies the design editing options for this component
  • Classic UI:
    • dialog (cq:Dialog) – defines the dialog for editing content of this component (specific to the classic UI)
    • design_dialog (cq:Dialog) – specifies the design editing options for this component
    • icon.png – graphics file to be used as an icon for the component in the Sidekick
    • thumbnail.png – graphics file to be used as a thumbnail for the component while dragging it from the Sidekick

Dialogs

Dialogs are a key element of your component as they provide an interface for authors to configure and provide input to that component.

Depending on the complexity of the component your dialog may need one or more tabs – to keep the dialog short and to sort the input fields.

Dialog definitions are specific to the UI:

Note:

  • For compatibility purposes the touch-enabled UI can use the definition of a classic UI dialog, when no dialog has been defined for the touch-enabled UI.
  • The Dialog Conversion Tool is also provided to help you extend/convert components that only have dialogs defined for the classic UI.
  • Touch-Enabled UI

    • cq:dialog (nt:unstructured) nodes:
      • define the dialog for editing content of this component
      • specific to the touch-enabled UI
      • are defined using Granite UI components
      • have a property sling:resourceType, as standard Sling content structure
      • can have a property helpPath to define the context sensitive help resource (absolute or relative path) that is accessed when the Help icon (the ? icon) is selected.
        • For out-of-the box components this often references a page in the documentation.
        • If no helpPath is specified, the default URL (documentation overview page) is shown.
    chlimage_1

     

    Within the dialog, individual fields are defined:

    screen_shot_2012-02-13at60937pm

     

  • Classic UI

    • dialog (cq:Dialog) nodes
      • define the dialog for editing content of this component
      • specific to the classic UI
      • are defined using ExtJS widgets
      • have a property xtype, which refers to ExtJS
      • can have a property helpPath to define the context sensitive help resource (absolute or relative path) that is accessed when the Help button is selected.
        • For out-of-the box components this often references a page in the documentation.
        • If no helpPath is specified, the default URL (documentation overview page) is shown.
    chlimage_1

     

    Within the dialog, individual fields are defined:

    chlimage_1

     

    Within a classic dialog:

    • you can create the dialog as cq:Dialog, which will provide a single tab – as in the text component, or if you need multiple tabs, as with the textimage component, the dialog can be defined as cq:TabPanel.
    • a cq:WidgetCollection (items) is used to provide a base for either input fields (cq:Widget) or further tabs (cq:Widget). This hierarchy can be extended.

Design Dialogs

Design dialogs are very similar to the dialogs used to edit and configure content, but they provide the interface for authors to configure and provide design details for that component.

Design dialogs are available in Design Mode, though they are not needed for all components e.g. Title and Image both have design dialogs, whereas Text does not.

The design dialog for the paragraph system (e.g. parsys) is a special case as it allows the user to specific other components to be available for selection (from the components browser or sidekick) on the page.

Adding your Component to the Paragraph System

Once a component has been defined it must be made available for use. To make a component available for use in a paragraph system you can either:

  • Open Design Mode for a page and enable the required component.

  • Add the required component(s) to the components property of your template definition under:

    /etc/designs/<yourProject>/jcr:content/<yourTemplate>/par

    For example, see:

    /etc/designs/geometrixx/jcr:content/contentpage/par

    chlimage_1

Components and the Content They Create

If we create and configure an instance of the Title component on the page: <content-path>/Prototype.html

  • Touch-Enabled UI

    chlimage_1

     

  • Classic UI

    screen_shot_2012-02-01at34257pm

     

Then we can see the structure of the content created within the repository:

screen_shot_2012-02-13at61405pm

 

In particular, if you look at the actual text for a Title:

  • the definition (for both UIs) have the property name=./jcr:title
    • /libs/foundation/components/title/cq:dialog/content/items/column/items/title
    • /libs/foundation/components/title/dialog/items/title
  • within the content, this generates the property jcr:title holding the author’s content.

The properties defined are dependent on the individual definitions. Although they can be more complex than above they still follow the same basic principles.

Component Hierarchy and Inheritance

Components within AEM are subject to 3 different hierarchies:

  • Resource Type Hierarchy
    This is used to extend components using the property sling:resourceSuperType. This enables the component to inherit. For example a text component will inherit various attributes from the standard component.

    • scripts (resolved by Sling)
    • dialogs
    • descriptions (including thumbnail images, icons, etc)
  • Container Hierarchy
    This is used to populate configuration settings to the child component and is most commonly used in a parsys scenario.
    For example, configuration settings for the edit bar buttons, control set layout (editbars, rollover), dialog layout (inline, floating) can be defined on the parent component and propagated to the child components.
    Configuration settings (related to edit functionality) in cq:editConfig and cq:childEditConfig are propagated.
  • Include Hierarchy
    This is imposed at runtime by the sequence of includes.
    This hierarchy is used by the Designer, which in turn acts as the base for various design aspects of the rendering; including layout information, css information, the available components in a parsys among others.

Edit Behavior

This section explains how to configure the edit behavior of a component. This includes attributes such as actions available for the component, characteristics of the inplace editor and the listeners related to events on the component.

The configuration is common to both the touch-enabled and classic UI, albeit with certain, specific differences.

The edit behavior of a component is configured by adding a cq:editConfig node of type cq:EditConfig below the component node (of type cq:Component) and by adding specific properties and child nodes. The following properties and child nodes are available:

  • cq:editConfig node properties:

    • cq:actions (String array): defines the actions that can be performed on the component.
    • cq:layout (String): : defines how the component is edited in the classic UI.
    • cq:dialogMode (String): defines how the component dialog is opened in the classic UI
      • In the touch-enabled UI, dialogs are always floating in desktop mode, and automatically opened as fullscreen in mobile.
    • cq:emptyText (String): defines text that is displayed when no visual content is present.
    • cq:inherit (Boolean): defines if missing values are inherited from the component that it inherits from.
    • dialogLayout (String): defines how the dialog should open.
  • cq:editConfig child nodes:

    • cq:dropTargets (node type nt:unstructured): defines a list of drop targets that can accept a drop from an asset of the content finder
      • Multiple drop targets are only available in the classic UI.
      • In the touch-enabled UI a single drop target is allowed.
    • cq:actionConfigs (node type nt:unstructured): defines a list of new actions that are appended to the cq:actions list.
    • cq:formParameters (node type nt:unstructured): defines additional parameters that are added to the dialog form.
    • cq:inplaceEditing (node type cq:InplaceEditingConfig): defines an inplace editing configuration for the component.
    • cq:listeners (node type cq:EditListenersConfig): defines what happens before or after an action occurs on the component.

Note:

In this page, a node (properties and child nodes) is represented as XML, as shown in the following example.

    cq:actions="[edit]"
    cq:dialogMode="floating"
    cq:layout="editbar"
    jcr:primaryType="cq:EditConfig">
    <cq:listeners
        jcr:primaryType="cq:EditListenersConfig"
        afteredit="REFRESH_PAGE"/>
</jcr:root>

 

There are many existing configurations in the repository. You can easily search for specific properties or child nodes:

  • To look for a property of the cq:editConfig node, e.g. cq:actions, you can use the Query tool in CRXDE Lite and search with the following XPath query string:
    //element(cq:editConfig, cq:EditConfig)[@cq:actions]
  • To look for a child node of cq:editConfig, e.g. you can search for cq:dropTargets, which is of type cq:DropTargetConfig; you can use the Query tool in CRXDE Lite and search with the following XPath query string:
    //element(cq:dropTargets, cq:DropTargetConfig)

Configuring with cq:EditConfig Properties

cq:actions

The cq:actions property (String array) defines one or several actions that can be performed on the component. The following values are available for configuration:

Property Value Description
text:<some text> Displays the static text value <some text>
Only visible in classic UI. The touch-enabled UI does not display actions in a contextual menu, so this is not applicable.
– Adds a spacer.
Only visible in classic UI. The touch-enabled UI does not display actions in a contextual menu, so this is not applicable.
edit Adds a button to edit the component.
delete Adds a button to delete the component
insert Adds a button to insert a new component before the current one
copymove Adds a button to copy and cut the component.

The following configuration adds an edit button, a spacer, a delete and an insert button to the component edit bar:

    cq:actions="[edit,-,delete,insert]"
    cq:layout="editbar"
    jcr:primaryType="cq:EditConfig"/>

The following configuration adds the text “Inherited Configurations from Base Framework” to the component edit bar:

    cq:actions="[text:Inherited Configurations from Base Framework]"
    cq:layout="editbar"
    jcr:primaryType="cq:EditConfig"/>

 

cq:layout (Classic UI Only)

The cq:layout property (String) defines how the component can be edited in the classic UI. The following values are available:

Property Value Description
rollover Default value. The component edition is accessible “on mouse over” through clicks and/or context menu.
For advanced use, note that the corresponding client side object is: CQ.wcm.EditRollover.
editbar The component edition is accessible through a toolbar.
For advanced use, note that the corresponding client side object is: CQ.wcm.EditBar.
auto The choice is left to the client side code.

Note:

The concepts of rollover and editbar are not applicable in the touch-enabled UI.

The following configuration adds an edit button to the component edit bar:

    cq:actions="[edit]"
    cq:layout="editbar"
    jcr:primaryType="cq:EditConfig">
</jcr:root>

 

cq:dialogMode (Classic UI Only)

The component can be linked to an edit dialog. The cq:dialogMode property (String) defines how the component dialog will be opened in the classic UI. The following values are available:

Property Value Description
floating The dialog is floating.
inline (default value). The dialog is anchored over the component.
auto If the component width is smaller than the client side CQ.themes.wcm.EditBase.INLINE_MINIMUM_WIDTH value, the dialog is floating, otherwise it is inline.

Note:

In the touch-enabled UI, dialogs are always floating in desktop mode and automatically opened as fullscreen in mobile.

The following configuration defines an edit bar with an edit button, and a floating dialog:

    cq:actions="[edit]"
    cq:dialogMode="floating"
    cq:layout="editbar"
    jcr:primaryType="cq:EditConfig">
</jcr:root>

cq:emptyText

The cq:emptyText property (String) defines text that is displayed when no visual content is present. It defaults to: Drag components or assets here.

cq:inherit

The cq:inherit property (boolean) defines whether missing values are inherited from the component that it inherits from. It defaults to false.

dialogLayout

The dialogLayout property defines how a dialog should open by default.

  • A value of fullscreen opens the dialog in full screen.
  • An empty value or absence of the property defaults to opening the dialog normally.
  • Note that the user can always toggle the fullscreen mode within the dialog.
  • Does not apply to the classic UI.

Configuring with cq:EditConfig Child Nodes

cq:dropTargets

The cq:dropTargets node (node type nt:unstructured) defines a list of drop targets that can accept a drop from an asset dragged from the content finder. It serves as a collection of nodes of type cq:DropTargetConfig.

Note:

Multiple drop targets are only available in the classic UI.

In the touch-enabled UI only the first target will be used.

Each child node of type cq:DropTargetConfig defines a drop target in the component. The node name is important because it must be used in the JSP, as follows, to generate the CSS class name assigned to the DOM element that is the effective drop target:

<drop target css class> = <drag and drop prefix> +
<node name of the drop target in the edit configuration>

The <drag and drop prefix> is defined by the Java property:

com.day.cq.wcm.api.components.DropTarget.CSS_CLASS_PREFIX.

For example, the class name is defined as follows in the JSP of the Download component
(/libs/foundation/components/download/download.jsp), where file is the node name of the drop target in the edit configuration of the Download component:

String ddClassName = DropTarget.CSS_CLASS_PREFIX + “file”;

The node of type cq:DropTargetConfig needs to have the following properties:

Property Name Property Value
accept Regex applied to the asset mime type to validate if dropping is allowed.
groups Array of drop target groups. Each group must match the group type that is defined in the content finder extension and that is attached to the assets.
propertyName Name of the property that will be updated after a valid drop.

The following configuration is taken from the Download component. It enables any asset (the mime-type can be any string) from the media group to be dropped from the content finder into the component. After the drop, the component property fileReference is being updated:

<cq:dropTargets jcr:primaryType="nt:unstructured">
    <file
        jcr:primaryType="cq:DropTargetConfig"
        accept="[.*]"
        groups="[media]"
        propertyName="./fileReference"/>
</cq:dropTargets>

 

cq:actionConfigs (Classic UI Only)

The cq:actionConfigs node (node type nt:unstructured) defines a list of new actions that are appended to the list defined by the cq:actions property. Each child node of cq:actionConfigs defines a new action by defining a widget.

The following sample configuration defines a new button (with a separator for the classic UI):

  • a separator, defined by the xtype tbseparator;
    • This is only used by the classic UI.
    • This definition is ignored by the touch-enabled UI as xtypes are ignored (and separators are unnecessary as the action toolbar is constructed differently in the touch-enabled UI).
  • a button named Manage comments that runs the handler function CQ_collab_forum_openCollabAdmin().
    cq:actions="[EDIT,COPYMOVE,DELETE,INSERT]"
    jcr:primaryType="cq:EditConfig">
    <cq:actionConfigs jcr:primaryType="nt:unstructured">
        <separator0
            jcr:primaryType="nt:unstructured"
            xtype="tbseparator"/>
        <manage
            jcr:primaryType="nt:unstructured"
            handler="function(){CQ_collab_forum_openCollabAdmin();}"
            text="Manage comments"/>
    </cq:actionConfigs>
</jcr:root>

Note:

See Add New Action to a Component Toolbar as an example for the touch-enabled UI.

cq:formParameters

The cq:formParameters node (node type nt:unstructured) defines additional parameters that are added to the dialog form. Each property is mapped to a form parameter.

The following configuration adds a parameter called name, set with the value photos/primary to the dialog form:

<cq:formParameters
    jcr:primaryType="nt:unstructured"
    name="photos/primary"/>

 

cq:inplaceEditing

The cq:inplaceEditing node (node type cq:InplaceEditingConfig) defines an inplace editing configuration for the component. It can have the following properties:

Property Name Property Value
active (boolean) True to enable the inplace editing of the component.
configPath (String) Path of the editor configuration. The configuration can be specified by a configuration node.
editorType (String) Editor type. The available types are:

  • plaintext: to be used for non HTML content.
  • title: is an enhanced plaintext editor that converts graphical titles into a plaintext before editing begins. Used by the Geometrixx title component.
  • text: to be used for HTML content (uses the Rich Text Editor).

The following configuration enables the inplace editing of the component and defines plaintext as the editor type:

<cq:inplaceEditing
    jcr:primaryType="cq:InplaceEditingConfig"
    active="{Boolean}true"
    editorType="plaintext"/>

 

cq:listeners

The cq:listeners node (node type cq:EditListenersConfig) defines what happens before or after an action on the component. The following table defines its possible properties.

Property Name Property Value
Default Value

(Classic UI Only)

beforedelete The handler is triggered before the component is removed.
beforeedit The handler is triggered before the component is edited.
beforecopy The handler is triggered before the component is copied.
beforemove The handler is triggered before the component is moved.
beforeinsert The handler is triggered before the component is inserted.
Only operational for the touch-enabled UI.
beforechildinsert The handler is triggered before the component is inserted inside another component (containers only).
afterdelete The handler is triggered after the component is removed. REFRESH_SELF
afteredit The handler is triggered after the component is edited. REFRESH_SELF
aftercopy The handler is triggered after the component is copied. REFRESH_SELF
afterinsert The handler is triggered after the component is inserted. REFRESH_INSERTED
aftermove The handler is triggered after the component is moved. REFRESH_SELFMOVED
afterchildinsert The handler is triggered after the component is inserted inside another component (containers only).

Note:

The REFRESH_INSERTED and REFRESH_SELFMOVED handlers are only available in the classic UI.

Note:

Default values for the listeners are only set in the classic UI.

Note:

In the case of nested components there are certain restrictions on actions defined as properties on the cq:listeners node:

  • For nested components, the values of the following properties must be REFRESH_PAGE:
    • aftermove
    • aftercopy

The event handler can be implemented with a custom implementation. For example (where project.customerAction is a static method):

afteredit = “project.customerAction”

The following example is equivalent to the REFRESH_INSERTED configuration:

afterinsert=”function(path, definition) { this.refreshCreated(path, definition); }”

Note:

For the classic UI, to see which parameters can be used in the handlers, refer to the before<action> and after<action> events section of the CQ.wcm.EditBar and CQ.wcm.EditRollover widget documentation.

With the following configuration the page is refreshed after the component has been deleted, edited, inserted or moved:

<cq:listeners
    jcr:primaryType="cq:EditListenersConfig"
    afterdelete="REFRESH_PAGE"
    afteredit="REFRESH_PAGE"
    afterinsert="REFRESH_PAGE"
    afterMove="REFRESH_PAGE"/>

Templates AEM6.3

Page Templates – Editable

Editable templates have been introduced to:

  • Allow specialized authors to create and edit templates.
    • Such specialized authors are called template authors
    • Template authors must be members of the template-authors group.
  • Provide templates that retain a dynamic connection to any pages created from them. This ensures that any changes to the template are reflected in the pages themselves.
  • Make the page component more generic so the core page component can be used without customization.

With editable templates, the pieces that make a page are isolated within components. You can configure the necessary combinations of components in a UI, thereby eliminating the need for a new page component to be developed for each page variation.

Note:

Static templates are also available.

This document:

  • Gives an overview of creating editable templates
  • Describes the admin/developer tasks required to create editable templates
  • Describes the technical underpinnings of editable templates

This document assumes that you are already familiar with creating and editing templates. See the authoring document Creating Page Templates, which details the capabilities of editable templates as exposed to the template author.

Note:

Following tutorial might also be of interest for setting up an editable page template in a new project:
Getting Started with AEM Sites Part 2 – Creating a Base Page and Template

Creating a New Template

Creating editable templates is primarily done with the template console and template editor by a template author. This section gives an overview of this process and follows with a description of what occurs at a technical level.

For information on how to use editable templates in an AEM project see Creating an AEM project using Lazybones.

When creating a new editable template you:

  • Create a folder for the templates. This is not mandatory, but is recommended best practice.

  • Select a template type. This is copied to create the template definition.

    Note:

    A selection of template types are provided out-of-the-box. You can also create your own site-specific template types if required.

  • Configure the structure, content policies, initial content, and layout of the new template.

    Structure

    • The structure allows you define components and content for your template.
    • Components defined in the template structure cannot be moved on a resulting page nor deleted from any resulting pages.
      • If you are creating a template in a custom folder outside of the We.Retail sample content, you can choose Foundation Components or use Core Components.
    • If you want page authors to be able to add and remove components, add a paragraph system to the template.
    • Components can be unlocked and locked again to allow you to define initial content.

    For details on how a template author defines the structure, see Creating Page Templates.

    For technical deatils of the structure, see Structure in this document.

    Policies

    • The content policies define the design properties of a component.
      • For example, the components available or minimum/maximum dimensions.
    • These are applicable to the template (and pages created with the template).

    For details on how a template author defines policies, see Creating Page Templates.

    For technical deatil of policies, see Content Policies in this document.

    Initial Content

    • Initial Content defines content that will appear when a page is first created based on the template.
    • Initial content can then be edited by page authors.

    For details on how a template author defines the structure, see Creating Page Templates.

    For technical details on initial content, see Initial Content in this document.

    Layout

    • You can define the template layout for a range of devices.
    • Responsive layout for templates operates as it does for page authoring.

    For details on how a template author defines the template layout, see Creating Page Templates.

    For technical details on template layout, see Layout in this document.

  • Enable the template, then allow it for specific content trees.

    • A template can be enabled or disabled to make it available or unavailable to page authors.
    • A template can be made available or unavailable for certain page branches.

    For details on how a template author enables a template, see Creating Page Templates.

    For technical deatils on enabling a template, see Enabling and Allowing a Template for Use in this document

  • Use it to create content pages.

    • When using a template to create a new page there is no visible difference and no indication between static and editable templates.
    • For the page author, the process is transparent.

    For details on how a page author uses templates to create a page, see Creating and Organizing Pages.

    For technical details on creating pages with editable templates, see Resultant Content Pages in this document.

Note:

The editor client library assumes the presence of the cq.shared namespace in content pages, and if it is absent the JavaScript error Uncaught TypeError: Cannot read property ‘shared’ of undefined will result.

All sample content pages contain cq.shared, so any content based on them automatically includes cq.shared. However, if you decide to create your own content pages from scratch without basing them on sample content, you must make sure to include the cq.sharednamespace.

See Using Client-Side Libraries for further information.

Caution:

Never enter any information that needs to be internationalized into a template.

Template Folders

For organizing your templates you can use the following folders:

  • global
  • Site-specific
    The site-specific folders that you create to organize your templates are created with an account holding admin priviliges.

Note:

Even though you can nest your folders, when the user views them in the Templates console they are presented as a flat structure.

In a standard AEM instance the global folder already exists in the template console. This holds default templates and acts as a fallback if no policies and/or template-types are found in the current folder. You can add your default templates to this folder or create a new folder (recommended).

Note:

It is best practice to create a new folder to hold your customized templates and not to use the global folder.

Caution:

Folders must be created by a user with admin rights.

Template types and policies are inherited across all folders according to the following order of precedence:

  1. The current folder.
  2. Parent(s) of the current folder.
  3. /conf/global
  4. /apps
  5. /libs

A list of all allowed entries is created. If any configurations overlap (path/label), only the instance closest to the current folder is presented to the user.

To create a new folder, you can either do this:

  • Programmatically or with CRXDE Lite
  • Using the Configuration Browser

Using CRXDE Lite

  • A new folder (under /conf) can be created for your instance either programmatically or with CRXDE Lite.

    The following structure must be used:

    1
    2
    3
    4
    5
    6
    /conf
        <your-folder-name> [sling:Folder]
            settings [sling:Folder]
                wcm [cq:Page]
                    templates [cq:Page]
                    policies [cq:Page]
  • You can then define the following properties on the folder root node:

    <your-folder-name> [sling:Folder]

    Name: jcr:title

    • Type: String
    • Value: The title (for the folder) you want to appear in the Templates console.
  • In addition to the standard authoring permissions and privileges (e.g. content-authors) you now need to assign group(s) and define the required access rights (ACLs) for your authors to be able to create templates in the new folder.

    The template-authors group is the default group that needs to be assigned. See the following section ACLs and Groups for details.

    See Access Right Management for full details on managing and assigning access rights.

Using the Configuration Browser

  • Go to Global Navigation -> Tools > Configuration Browser.

    The existing folders are listed to the left including the global folder.

     

  • Click Create.

  • In the Create Configuration dialog the following fields need to be configured:

    • Title: Provide a title for the configuration folder
    • Editable Templates: Tick to allow for editable templates within this folder
  • Click Create

Note:

In the Configuration Browser, you can edit the global folder and activate the Editable Templates option if you wish to create templates within this folder, however this is not recommended best practice.

ACLs and Groups

Once your template folders are created (either via CRXDE or with the Configuration Browser), ACLs must defined for the appropriate groups for the template folders to ensure proper security.

The template folders for the We.Retail reference implementation can be used as an example.

The template-authors Group

The template-authors group is the group used to manage access to templates and comes standard with AEM, but is empty. Users must be added to the group for the project/site.

Caution:

The template-authors group is only for users that must be able to create new templates.

Editing templates is very powerful and if not done properly exiting templates can be broken. Therefore this role should be focused and only include qualified users.

The following table details the necessary permissions for template editing.

Path Role / Group Permissions Description
/conf/<your-folder>/settings/wcm/templates Template Authors read, write, replicate Template authors that create, read, update, delete, and replicate templates in site specific /confspace
Anonymous Web User read Anonymous Web User must read templates while rendering a page
Content Authors replicate replicateContent authors need to activate the templates of a page when activating a page
/conf/<your-folder>/settings/wcm/policies Template Author read, write, replicate Template authors that create, read, update, delete, and replicate templates in site specific /conf space
Annonymous Web User read Anonymous Web User must read policies while rendering a page
Content Authors replicate Content authors need to activate the policies of a template of a page when activating a page
/conf/<site>/settings/template-types Template Author read Template author creates a new template based on one of the predefined template types.
Anonymous Web User none Anonymous Web User must not access the template types

This default template-authors group only covers the project setups, where all template-authors members are allowed to access and author all templates. For more complex setups, where multiple template authors groups are needed to separate access to templates, more custom template authors groups must be created. However the permissions for the template authors groups would still be the same.

Legacy Templates under /conf/global

Templates should no longer be stored in /conf/global, however for some legacy installations there may still be templates in this location. ONLY in such legacy situations should the following /conf/global paths be explicitly configured.

Path Role / Group Permissions Description
/conf/global/settings/wcm/templates Template Authors read, write, replicate Template authors that create, read, update, delete, and replicate templates in /conf/global
Anonymous Web User read Anonymous Web User must read templates while rendering a page
Content Authors replicate Content authors need to activate the templates of a page when activating a page
/conf/global/settings/wcm/policies Template Author read, write, replicate Template authors that create, read, update, delete, and replicate templates in /conf/global
Anonymous Web User read Anonymous Web User must read policies while rendering a page
Content Authors replicate Content authors need to activate the policies of a template of a page when activating a page
/conf/global/settings/wcm/template-types Template Author read Template author creates a new template based on one of the predefined template types
Anonymous Web User none Anonymous Web User must not access the template types

Template Type

When creating a new template you need to specify a template type:

  • Template types effectively provide templates for a template. When creating a new template the structure and initial content of the selected template type is used to create to the new template.
    • The template type is copied to create the template.
    • Once the copy has occurred, the only connection between the template and the template type is a static reference for information purposes.
  • Template types allow you to define:
    • The resource type of the page component.
    • The policy of the root node, which defines the components allowed in the template editor.
    • Optionally (but recommended), the breakpoints for the responsive grid and setup of the mobile emulator. This is optional, because the configuration could also be defined on the root page of the site.
  • AEM provides a small selection of out-of-the-box template types such as HTML5 Page and Adaptive Form Page.
    • Additional examples are provided as a part of the We.Retail sample content.
  • Template types are typically defined by developers.

The out-of-the box template types are stored under:

  • /libs/settings/wcm/template-types

Caution:

You must not change anything in the /libs path. This is because the content of /libs is overwritten the next time you upgrade your instance (and may be overwritten when you apply either a hotfix or feature pack).

Your site-specific template types should be stored in the comparable location of:

  • /apps/settings/wcm/template-types

Definitions for your customized templates types should be stored in user-defined folders (recommended) or alternatively in global. For example:

  • /conf/<my-folder-01>/<my-folder-02>/settings/wcm/template-types
  • /conf/<my-folder>/settings/wcm/template-types
  • /conf/global/settings/wcm/template-types

Caution:

The template types have to respect the correct folder structure (i.e. /settings/wcm/…), otherwise the template types will not be found.

Creating Template Types

If you have created a template that can serve as the basis of other templates, you can copy this template as a template type.

  • Create a template as you would any editable template as documented here, which will serve as the basis of your template type.

  • Using CRXDE Lite, copy the newly-created template from the templates node to the template-types node under the template folder.

  • Delete the template from the templates node under the template folder.

  • In the copy of the template that is under the template-types node, delete all cq:template and cq:templateType jcr:content properties.

You can also develop your own template type using an example editable template as a basis, available on GitHub.

CODE ON GITHUB

You can find the code of this page on GitHub

Template Definitions

Definitions for editable templates are stored user-defined folders (recommended) or alternatively in global. For example:

  • /conf/<my-folder>/settings/wcm/templates
  • /conf/<my-folder-01>/<my-folder-02>/settings/wcm/templates
  • /conf/global/settings/wcm/templates

The root node of the template is of type cq:Template with a skeleton structure of:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<template-name>
  initial
    jcr:content
      root
        <component>
        ...
        <component>
  jcr:content
    @property status
  policies
    jcr:content
      root
        @property cq:policy
        <component>
          @property cq:policy
        ...
        <component>
          @property cq:policy
  structure
    jcr:content
      root
        <component>
        ...
        <component>
      cq:responsive
        breakpoints
  thumbnail.png

The main elements are:

jcr:content

This node holds properties for the template:

  • Name: jcr:title
  • Name: status
    • Type: String
    • Value: draft, enabled or disabled

Structure

Defines the structure of the resultant page:

  • Is merged with the initial content (/initial) when creating a new page.
  • Changes made to the structure will be reflected in any pages created with the template.
  • The root (structure/jcr:content/root) node defines the list of components that will be available in the resulting page.
    • Components defined in the template structure cannot be moved on or deleted from any resultant pages.
    • Once a component is unlocked the editable property is set to true.
    • Once a component that already contains content is unlocked, this content will be moved to the initial branch.
  • The cq:responsive node holds definitions for the responsive layout.

Initial Content

Defines the initial content that a new page will have upon creation:

  • Contains a jcr:content node that is copied to any new pages.
  • Is merged with the structure (/structure) when creating a new page.
  • Any existing pages will not be updated if the initial content is changed after creation.
  • The root node holds a list of components to define what will be available in the resulting page.
  • If content is added to a component in structure mode and that component is subsequently unlocked (or vice versa), then this content is used as initial content.

Layout

Content Policies

The content (or design) policies define the design properties of a component. For example, the components available or minimum/maximum dimensions. These are applicable to the template (and pages created with the template). Content policies can be created and selected in the template editor of the touch-optimized UI.

  • The property cq:policy, on the root node
    /conf/<your-folder>/settings/wcm/templates/<your-template>/policies/jcr:content/root
    Provides a relative reference to the content policy for the page’s paragraph system.
  • The property cq:policy, on the component-explicit nodes under root, provide links to the policies for the individual components.
  • The actual policy definitions are stored under:
    /conf/<your-folder>/settings/wcm/policies/wcm/foundation/components

Note:

The paths of policy definitions depend on the path of the component. cq:policy holds a relative reference to the configuration itself.

Note:

Pages created from editable templates do not offer a Design mode in the page editor.

The policies tree of an editable template has the same hierarchy as the design mode configuration of a static template under:

    /etc/designs/<my-site>/jcr:content/<component-name>

The design mode configuration of a static template was defined per page component.

Page Policies

Page policies allow you to define the content policy for the page (main parsys), in either the template or resultant pages.

Enabling and Allowing a Template for Use

  • Enable the Template

    Before a template can be used it must be enabled by either:

    • Enabling the template from the Templates console.
    • Setting the status property on the jcr:content node.
      • For example, on:
        /conf/<your-folder>/settings/wcm/templates/<your-template>/jcr:content
      • Define the property:
        • Name: status
        • Type: String
        • Value: enabled
  • Allowed Templates

    For example, with a value of:

    /conf/<your-folder>/settings/wcm/templates/.*

Resultant Content Pages

Pages created from editable templates:

  • Are created with a subtree that is merged from structure and initial in the template
  • Have references to information held in the template and template type. This is achieved with a jcr:content node with the properties:
    • cq:template
      Provides the dynamic reference to the actual template; enables changes to the template to be reflected on the actual pages.
    • cq:templateType
      Provides a reference to the template type.
chlimage_1

The above diagram shows how templates, content, and components interrelate:

  • Controller – /content/<my-site>/<my-page>
    The resultant page that references the template. The content controls the entire process. According to the definitions it accesses the appropriate template and components.
  • Configuration – /conf/<my-folder>/settings/wcm/templates/<my-template>
    The template and related content policies define the page configuration.
  • Model – OSGi bundles
    The OSGI bundles implement the functionality.
  • View – /apps/<my-site>/components
    On both the author and publish environments the content is rendered by components.

When rendering a page:

  • Templates:

    • The cq:template property of its jcr:content node will be referenced to access the template that corresponds to that page.
  • Components:

    • The page component will merge the structure/jcr:content tree of the template with the jcr:content tree of the page.
    • The page component will only allow the author to edit the nodes of the template structure that have been flagged as editable (as well as any children).
    • When rendering a component on a page, the relative path of that component will be taken from the jcr:contentnode; the same path under the policies/jcr:content node of the template will then be searched.
      • The cq:policy property of this node points to the actual content policy (i.e. it holds the design configuration for that component).
      • This allows you to have multiple templates that re-use the same content policy configurations.

    Page Templates – Static

    A Template is used to create a Page and defines which components can be used within the selected scope. 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.

    Note:

    Editable templates are also available.

    Properties and Child Nodes of a Template

    A template is a node of type cq:Template and has the following properties and child nodes:

    Name
    Type
    Description
    .  cq:Template Current template. A template is of node type cq:Template.
     allowedChildren  String[] Path of a template that is allowed to be a child of this template.
     allowedParents  String[] Path of a template that is allowed to be a parent of this template.
     allowedPaths  String[] Path of a page that is allowed to be based on this template.
     jcr:created  Date Date of creation of the template.
     jcr:description  String Description of the template.
     jcr:title  String Title of the template.
     ranking  Long Rank of the template. Used to display the template in the User Interface.
     jcr:content  cq:PageContent Node containing the content of the template.
     thumbnail.png  nt:file Thumbnail of the template.
     icon.png  nt:file Icon of the template.

    A template is the basis of a page.

    To create a page, the template must be copied (node-tree /apps/<myapp>/template/<mytemplate>) to the corresponding position in the site-tree: this is what happens if a page is created using the Websites tab.

    This copy action also gives the page its initial content (usually Top-Level Content only) and the property sling:resourceType, the path to the page component that is used to render the page (everything in the child node jcr:content).

    How Templates are structured

    There are two aspects to be considered:

    • the structure of the template itself
    • the structure of the content produced when a template is used

    The structure of a Template

    A Template is created under a node of type cq:Template.

    Various properties can be set, in particular:

    • jcr:title – title for the template; appears in the dialog when creating a page.
    • jcr:description – description for the template; appears in the dialog when creating a page.

    This node contains a jcr:content (cq:PageContent) node which be used as the basis for the content node of resulting pages; this references, using sling:resourceType, the component to be used for rendering the actual content of a new page.

    This component is used to define the structure and design of the content when a new page is created.

    The content produced by a Template

    Templates are used to create pages of type cq:Page (as mentioned earlier, a page is a special type of component). Each AEM 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

    Default Templates

    AEM comes with a number of default templates available out of the box. In some cases, you may want to use the templates as is. In that case, you need to ensure that the template is available for your web site.

    For example, AEM comes with several templates including a contentpage and home page.

    Title Component Location Purpose
    Home Page homepage geometrixx The Geometrixx home page template.
    Content Page contentpage geometrixx The Geometrixx content page template.

    Displaying Default Templates

    To see a list of all templates in the repository, proceed as follows:

    1. In CRXDE Lite, open the Tools menu and click Query.
    2. In the Query tab
    3. As Type, select XPath.
    4. In the Query input field, enter following string:
      //element(*, cq:Template)
    5. Click Execute. The list is displayed in the result box.

    In most cases, you will take an existing template and develop a new one for your own use. See Developing Page Templates for more information.

    To enable an existing template for your website and you want it 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(/.*)?

    Developing Page Templates

    AEM page templates are simply models used to create new pages. They can contain as little, or as much, initial content as needed, their role being to create the correct initial node structures, with the required properties (primarily sling:resourceType) set to allow editing and rendering.

    Creating a new Template (based on an existing template)

    Needless to say a new template can be created completely from scratch, but often an existing template will be copied and updated to save you time and effort. For example, the templates within Geometrixx can be used to get you started.

    To create a new template based on an existing template:

  • Copy an existing template (preferably with a definition as close as possible to what you want to achieve) to a new node.

    Templates are usually stored in /apps/<website-name>/templates/<template-name>.

    Note:

    The list of available templates depends on the location of the new page and the restrictions on placement specified in each template. See Template Availability.

  • Change the jcr:title of the new template node to reflect its new role. You can also update the jcr:description if appropriate. Be sure to change the template availability of the page as appropriate.

    Note:

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

    chlimage_1

  • Copy the component on which the template is based (this is indicated by the sling:resourceType property of the jcr:contentnode within the template) to create a new instance.

    Components are usually stored in /apps/<website-name>/components/<component-name>.

  • Update the jcr:title and jcr:description of the new component.

  • Replace the thumbnail.png if you want a new thumbnail picture to be shown in the template selection list (size 128 x 98 px).

  • Update the sling:resourceType of the template’s jcr:content node to reference the new component.

  • Make any further changes to the functionality or design of the template and/or its underlying component.

    Note:

    Changes made to the /apps/<website>/templates/<template-name> node will affect the template instance (as in the selection list).

    Changes made to the /apps/<website>/components/<component-name> node will affect the content page created when the template is used.

    You can now create a page within your website using the new template.

  • Note:

    The editor client library assumes the presence of the cq.shared namespace in content pages, and if it is absent the JavaScript error Uncaught TypeError: Cannot read property ‘shared’ of undefined will result.

    All sample content pages contain cq.shared, so any content based on them automatically includes cq.shared. However, if you decide to create your own content pages from scratch without basing them on sample content, you must make sure to include the cq.shared namespace.

    See Using Client-Side Libraries for further information.

    Note:

    The editor client library assumes the presence of the cq.shared namespace in content pages, and if it is absent the JavaScript error Uncaught TypeError: Cannot read property ‘shared’ of undefined will result.

    All sample content pages contain cq.shared, so any content based on them automatically includes cq.shared. However, if you decide to create your own content pages from scratch without basing them on sample content, you must make sure to include the cq.shared namespace.

    See Using Client-Side Libraries for further information.

    Making an Existing Template Available

    This example illustrates how to allow a template to be used for certain content paths. The templates that are available to the page author when creating new pages are determined by the logic defined in Template Availability.

  • In CRXDE Lite, navigate to the template you want to use for your page, for example, the Newsletter template.

  • Change the allowedPaths property and other properties used for template availabillity. For example, allowedPaths: /content/geometrixx-outdoors/[^/]+(/.*)? means that this template is allowed in any path under /content/geometrixx-outdoors.

    chlimage_1
Create your own website, free on WordPress.com.Create your own website.
Start free