Monday, July 9, 2018

How to display custom site specific error(404,403 and 500) pages in multi site Adobe Experience Manager(AEM) setup?

How to display custom site specific error(404,403 and 500) pages in multi site Adobe Experience Manager(AEM) setup?


This post explains the approach to handle custom site specific error handling for Adobe Experience Manager(AEM) sites in a multi site environment

Sling Model to identify the error page:


Create a Sling model ErrorHandlerRequestModel.java in core module withe the below code - This will help to identify the site specific error page path specific to the error code.

package com.errorhandler.core.models;

import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.models.annotations.Default;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.Self;

import javax.annotation.PostConstruct;
import javax.inject.Inject;

@Model(adaptables = SlingHttpServletRequest.class)
public class ErrorHandlerRequestModel {

    private static final String DEFAULT_ERROR_PAGE = "/content/geometrixx-outdoors";
    private static final String ERROR_CODE_404 = "404";
    private static final int MAX_DEPTH = 2;
    private static final String PATH_SEPERATOR = "/";

    @Self
    private SlingHttpServletRequest slingRequest;

    @Inject
    @Default(values = ERROR_CODE_404)
    private String errorCode;

    private String pagePath;
 
    @PostConstruct
    protected void init() {
    pagePath = DEFAULT_ERROR_PAGE + errorCode;
        final String requestURI = slingRequest.getRequestPathInfo().getResourcePath();
        if (requestURI!=null && !requestURI.equals("")) {
          pagePath = getErrorPageFromRequestedUrl(errorCode, requestURI);
    }
    }

    private String getErrorPageFromRequestedUrl(final String errorCode, final String requestURI) {
        final Page resolvedPage = getPageFromPath(requestURI);
        if (resolvedPage != null) {
            return getErrorPathFromPage(errorCode, resolvedPage);
        }
        return null;
    }

    private Page getPageFromPath(String requestURI) {
        final PageManager pageManager = slingRequest.getResourceResolver().adaptTo(PageManager.class);
        while (requestURI.contains(PATH_SEPERATOR)) {
            Page page = pageManager.getContainingPage(requestURI);
            if (page != null) {
                return page;
            } else {
                requestURI = requestURI.substring(0, requestURI.lastIndexOf(PATH_SEPERATOR));
            }
        }
        return null;
    }

    private String getErrorPathFromPage(final String errorCode, final Page resolvedPage) {
    if (resolvedPage.hasChild(errorCode)) {
        return resolvedPage.getPath() + PATH_SEPERATOR + errorCode;
        }
        if (resolvedPage.getParent() != null && resolvedPage.getDepth() >= MAX_DEPTH) {
            return getErrorPathFromPage(errorCode, resolvedPage.getParent());
        }
        return null;
    }

    public String getPagePath() {
        return pagePath;
    }
}

Configure the DEFAULT_ERROR_PAGE(the content folder in which the default 404, 403 and 500 error pages are available) in the above code  - the error pages that will be displayed if the the site specific 404, 403 and 500 pages are missing.
Add the below instruction into core module pom.xml - to notify the package in which the sling models are available for registration

<Sling-Model-Packages>com.errorhandler.core.models</Sling-Model-Packages>


<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>                   
<Import-Package>javax.inject;version=0.0.0,*</Import-Package>
<Sling-Model-Packages>com.errorhandler.core.models</Sling-Model-Packages>
</instructions>
</configuration>
</plugin>

Configure Error Handlers:


Create 403.html, 404.html and Exception.html(error handler to handle all the Internal Server Exceptions) under /apps/sling/servlet/errorhandler

aem-error-handler-scripts


Add the below contents to 403.html, 404.html and Exception.html respectively

403.html

<sly data-sly-use.errorPage="${'com.errorhandler.core.models.ErrorHandlerRequestModel'@ errorCode='403'}"/>
<sly data-sly-resource="${errorPage.pagePath}.html"/>

404.html

<sly data-sly-use.responseStatus="apps.sling.servlet.errorhandler.ResponseStatus">
    <sly data-sly-use.errorPage="${'com.errorhandler.core.models.ErrorHandlerRequestModel'@ errorCode='404'}"/>
    <sly data-sly-resource="${errorPage.pagePath}.html"/>
</sly>

Exception.html

<sly data-sly-use.errorPage="${'com.errorhandler.core.models.ErrorHandlerRequestModel'@ errorCode='500'}"/>
<sly data-sly-resource="${errorPage.pagePath}.html"/>


Create ResponseStatus.java under /apps/sling/servlet/errorhandler and add the below content

package apps.sling.servlet.errorhandler;

import com.adobe.cq.sightly.WCMUse;

public class ResponseStatus extends WCMUse {
 
    @Override
    public void activate() throws Exception {
        getResponse().setStatus(404);
    }
}


Configure Error Pages:


Create site specific error files 403, 404 and 500(the files can be created in any level - the minimum depth should be 2 i.e under /content/sitename), the files will be taken based on the level where the exception occurred.

aem-site-specific-error-pages


Exception directly under /content/geometrixx-outdoors consider the error pages under /content/geometrixx-outdoors
Exception under /content/geometrixx-outdoors/en consider the error pages under /content/geometrixx-outdoors/en

Configure the local error pages - 404, 403 and 500 for all the required sites.

Now the user will be displayed the corresponding error file content based on the error code.


This implementation has been tested in AEM 6.2 version.

Monday, July 2, 2018

HTTPS URL is resulting with 404 - Adobe Experience Manager

HTTPS URL is resulting with 404 - Adobe Experience Manager


Recently, we have faced the issue with https URL's, the URL's with masked path (/en/test.html) is not working with https protocol.

However, the unmasked (/content/site/en/test.html) URL is working, also http URL is working without any issues.

Based on our analysis, it looks to be the system is not honoring the /etc/map.publish/https mapping for https request and due to that the content path(without full path - /en/test.html) is not accessible and 404 is displayed

Our case the request is https from browser and the Load Balancer terminate the SSL and forward the request to dispatcher - Load Balancer notify the dispatcher that the initial request is https via header X-Forwarded-Proto (this header value differs based on the load balancer)

The dispatcher send the request to publisher with required headers and publisher consider the request as https based on the above header and match the Resource Mapping accordingly - /etc/map.publish/https

The 404 will be displayed for masked URL's if publisher not able to match the /etc/map.publish/https for incoming request.

How to resolve?


Option1:


  • Match the SSL Filter settings to those expected from the entity where SSL is terminated (Load Balancer). You can check these values forwarded in the dispatcher.log file and make sure they match to those of the SSL Filter. Configure the SSL Filter (Apache Felix Http Service SSL Filter) in Publisher with SSL forward header and value
SSL_Filter_https_aem

  • Allow the following headers in dispatcher farm file /clientheaders section, if /clientheaders section is not set to allow all

          X-Forwarded-Proto (this header value change based on the Load balancer)
               - other known values X-FORWARDED-SSL, X-Forwarded-Protocol and Front-End-Https
          X-Forwarded-Port
  • White list the SSL headers mentioned above in CDN, if CDN is enabled in the flow.

Option2:


Disallow the SSL forward headers in dispatcher farm file /clientheaders section; disallow the following header - X-Forwarded-Proto in /clientheaders section, review the "Apache Felix Http Service SSL Filter" in publisher to identify the exact header value used to identify the forwarded SSL request.

This allow the publisher to consider the request as http and match the /etc/map.publish/http node for incoming requests. 

In cases the SSL is terminated at the Web server, follow the below steps:


At the bottom of the httpd.conf add the following configuration: RequestHeader set X-Forwarded-Port "-1"

Allow the X-Forwarded-Port header in dispatcher farm file if /clientheaders section is not set to allow all 

Wednesday, June 13, 2018

Resolving the issues while migrating the packages between Adobe Experience Manager instances(AEM)

Resolving the issues while migrating the packages between Adobe Experience Manager instances(AEM)


This is a common scenario to migrate the packages between AEM instances, some times we may face issues while building or uploading the big packages.

This post explains the details to resolve the issues observed while building or uploading the big packages between AEM instances

java.io.IOException: No space left on device while building the package:


The "java.io.IOException: No space left on device" error will be thrown while building big packages in AEM server without having sufficient space available in /tmp folder.

java.io.IOException: No space left on device
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java:326)
at java.util.zip.DeflaterOutputStream.deflate(DeflaterOutputStream.java:253)
at java.util.zip.DeflaterOutputStream.write(DeflaterOutputStream.java:211)
at java.util.zip.ZipOutputStream.write(ZipOutputStream.java:331)
at org.apache.commons.io.output.ProxyOutputStream.write(ProxyOutputStream.java:90)
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1793)
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1769)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:1744)
at org.apache.jackrabbit.vault.fs.io.JarExporter.writeFile(JarExporter.java:128)
at org.apache.jackrabbit.vault.fs.io.AbstractExporter.export(AbstractExporter.java:216)
at org.apache.jackrabbit.vault.fs.io.AbstractExporter.export(AbstractExporter.java:214)
at org.apache.jackrabbit.vault.fs.io.AbstractExporter.export(AbstractExporter.java:214)
at org.apache.jackrabbit.vault.fs.io.AbstractExporter.export(AbstractExporter.java:214)
at org.apache.jackrabbit.vault.fs.io.AbstractExporter.export(AbstractExporter.java:214)
at org.apache.jackrabbit.vault.fs.io.AbstractExporter.export(AbstractExporter.java:214)
at org.apache.jackrabbit.vault.fs.io.AbstractExporter.export(AbstractExporter.java:214)
at org.apache.jackrabbit.vault.fs.io.AbstractExporter.export(AbstractExporter.java:214)
at org.apache.jackrabbit.vault.fs.io.AbstractExporter.export(AbstractExporter.java:214)
at org.apache.jackrabbit.vault.fs.io.AbstractExporter.export(AbstractExporter.java:214)
at org.apache.jackrabbit.vault.fs.io.AbstractExporter.export(AbstractExporter.java:184)
at org.apache.jackrabbit.vault.packaging.impl.PackageManagerImpl.assemble(PackageManagerImpl.java:142)
at org.apache.jackrabbit.vault.packaging.impl.PackageManagerImpl.assemble(PackageManagerImpl.java:96)
at org.apache.jackrabbit.vault.packaging.impl.JcrPackageManagerImpl.assemble(JcrPackageManagerImpl.java:594)
at org.apache.jackrabbit.vault.packaging.impl.JcrPackageManagerImpl.assemble(JcrPackageManagerImpl.java:574)
at com.day.crx.packaging.impl.J2EEPackageManager.consoleBuild(J2EEPackageManager.java:291)
at com.day.crx.packaging.impl.J2EEPackageManager.doPost(J2EEPackageManager.java:176)
at com.day.crx.packaging.impl.PackageManagerServlet.doPost(PackageManagerServlet.java:156)

no_space_left_on_device_aem_package

Wednesday, May 30, 2018

Exceptions/Issues while configuring SAML Authentication Handler - Adobe Experience Manager(AEM)

Exceptions/Issues while configuring SAML Authentication Handler - Adobe Experience Manager(AEM)


This post explains the Exceptions/Issues received while configuring the SAML authentication handler and the fixes to overcome the issues.

Issue1:


Problem accessing /saml_login. Reason:
com.adobe.granite.keystore.KeyStoreNotInitialisedException: Uninitialised system trust store.

uninitialized-system-trust-store


14.05.2018 11:24:39.988 *WARN* [qtp1134377453-62] org.eclipse.jetty.servlet.ServletHandler /saml_login
com.adobe.granite.keystore.KeyStoreNotInitialisedException: Uninitialised system trust store.
at com.adobe.granite.keystore.internal.KeyStoreServiceImpl.internalGetTrustStore(KeyStoreServiceImpl.java:462)
at com.adobe.granite.keystore.internal.KeyStoreServiceImpl.getTrustStore(KeyStoreServiceImpl.java:151)
at com.adobe.granite.auth.saml.SamlAuthenticationHandler.handleLogin(SamlAuthenticationHandler.java:577)
at com.adobe.granite.auth.saml.SamlAuthenticationHandler.extractCredentials(SamlAuthenticationHandler.java:348)
at org.apache.sling.auth.core.impl.AuthenticationHandlerHolder.doExtractCredentials(AuthenticationHandlerHolder.java:75)
at org.apache.sling.auth.core.impl.AbstractAuthenticationHandlerHolder.extractCredentials(AbstractAuthenticationHandlerHolder.java:60)
at org.apache.sling.auth.core.impl.SlingAuthenticator.getAuthenticationInfo(SlingAuthenticator.java:709)
at org.apache.sling.auth.core.impl.SlingAuthenticator.doHandleSecurity(SlingAuthenticator.java:461)
at org.apache.sling.auth.core.impl.SlingAuthenticator.handleSecurity(SlingAuthenticator.java:446)
at org.apache.sling.engine.impl.SlingHttpContext.handleSecurity(SlingHttpContext.java:121)
at org.apache.felix.http.base.internal.context.ServletContextImpl.handleSecurity(ServletContextImpl.java:339)
at org.apache.felix.http.base.internal.handler.ServletHandler.doHandle(ServletHandler.java:334)
at org.apache.felix.http.base.internal.handler.ServletHandler.handle(ServletHandler.java:297)
at org.apache.felix.http.base.internal.dispatch.ServletPipeline.handle(ServletPipeline.java:93)
at org.apache.felix.http.base.internal.dispatch.InvocationFilterChain.doFilter(InvocationFilterChain.java:50)
at org.apache.felix.http.base.internal.dispatch.HttpFilterChain.doFilter(HttpFilterChain.java:31)
at org.apache.sling.i18n.impl.I18NFilter.doFilter(I18NFilter.java:129)


Problem accessing /saml_login. Reason:
com.adobe.granite.keystore.KeyStoreNotInitialisedException: Uninitialised key store for user authentication-service

Uninitialised-Keystore-authentication-service

Thursday, May 3, 2018

io.jsonwebtoken,version=[0.7,1) -- Cannot be resolved - Adobe Experience Manager(AEM)

io.jsonwebtoken,version=[0.7,1) -- Cannot be resolved - Adobe Experience Manager(AEM) 

I was getting the below exception while using the io.jsonwebtoken dependency in the bundle and the bundle was in Installed state.

org.osgi.framework.BundleException: Unresolved constraint in bundle com.test [452]: Unable to resolve 452.5: missing requirement [452.5] osgi.wiring.package; (&(osgi.wiring.package=io.jsonwebtoken)(version>=0.7.0)(!(version>=1.0.0)))
at org.apache.felix.framework.Felix.resolveBundleRevision(Felix.java:4095)
at org.apache.felix.framework.Felix.startBundle(Felix.java:2114)
at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:977)
at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:964)
at org.apache.sling.installer.core.impl.tasks.BundleStartTask.execute(BundleStartTask.java:93)
at org.apache.sling.installer.core.impl.OsgiInstallerImpl.doExecuteTasks(OsgiInstallerImpl.java:847)
at org.apache.sling.installer.core.impl.OsgiInstallerImpl.executeTasks(OsgiInstallerImpl.java:689)
at org.apache.sling.installer.core.impl.OsgiInstallerImpl.run(OsgiInstallerImpl.java:265)
at java.lang.Thread.run(Unknown Source)

The below dependency is added into pom.xml

<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>


Steps to fix:


Configure the maven-bundle-plugin as shown below

<plugin>
    <groupId>org.apache.felix</groupId>
    <artifactId>maven-bundle-plugin</artifactId>
    <extensions>true</extensions>
<configuration>
<instructions>
<Import-Package>
!android.util;resolution:=optional,
!com.fasterxml.jackson.core;resolution:=optional,
!com.fasterxml.jackson.databind;resolution:=optional,
!org.bouncycastle.jce;resolution:=optional,
!org.bouncycastle.jce.spec;resolution:=optional,
javax.inject;version=0.0.0,*
</Import-Package>
<Embed-Dependency>jjwt;inline=true</Embed-Dependency>
<Embed-Transitive>true</Embed-Transitive>
</instructions>
    </configuration>
</plugin>

Tuesday, April 24, 2018

How to handle the request parameter encoding(charset) in Adobe Experience Manager(AEM)

How to handle the request parameter encoding(charset) in Adobe Experience Manager(AEM)


The default value for the parameter encoding in AEM is UTF8 — The default request parameter encoding used to decode request parameters into strings.

The configured parameter encoding value e.g UTF8 is used to decode the request parameters to string.

Sometimes we may need to change the default parameter encoding in Adobe Experience Manager(AEM) to handle different language characters.

This tutorial explains the approach to change the default parameter encoding to required values e.g UTF8, ISO-8859–1 etc

The request parameter can be changed by following either one of the below approach
  • Apache Sling Request Parameter Handling
  • Change the encoding for specific form

Apache Sling Request Parameter Handling


The request parameter encoding can be changed through the following OSGI configuration — “Apache Sling Request Parameter Handling”. This is the global configurations and impact all the request parameter handling(decoding)

“Default Parameter Encoding” — The default request parameter encoding used to decode request parameters into strings. If this property is not set the default encoding is ‘ISO-8859–1’ as mandated by the Servlet API spec. This default encoding is used if the ‘_charset_’ request parameter is not set to another (supported) character encoding. Applications being sure to always use the same encoding (e.g. UTF-8) can set this default here and may omit the ‘_charset_’ request parameter (sling.default.parameter.encoding)

The AEM server configures UTF-8 as the default parameter, ‘ISO-8859–1’ is considered as default encoding if this field is empty.



Change the value of “Default Parameter Encoding” to required values — e.g UTF-8/ISO-8859–1

Change the encoding for specific form


The request parameter can be changed to specific form by following the below steps

Add the parameter “_charset_” as a hidden field with required encoding value inside the form.

<form role=”form” id=”test” action=”xxxxx” method=”POST” accept-charset=”ISO-8859–1" onsubmit=”document.charset = ‘ISO-8859–1’”>
<input type=”hidden” id=”_charset_” name=”_charset_” value=”ISO-8859–1"/>
……..
……..
</form>

accept-charset=”ISO-8859–1" — specifies the character encoding that to be used for the form submission(non IE browsers)

“document.charset = ‘ISO-8859–1’” — specifies the character encoding that to be used for the form submission(Configuration for IE browser)

This will change the encoding of this particular form, different encoding can be specified page level and form level only to handle the data.

Wednesday, April 18, 2018

How to implement extension-less URL's in Adobe Experience Manager(AEM)

How to implement extension-less URL's in Adobe Experience Manager(AEM)

As per the SEO best practices it is better to define extension less URL's to boost the ranking, AEM require the extension to understand and serve incoming request.

This post explains the approach to achieve the extension less URL in Adobe Experience Manager(AEM)

There are two steps

- Rule Configuration Dispatcher
       Remove .html extension from incoming URL with /
Append the .html while invoking the publisher for the URL's ending with /

- AEM etc/map configuration
      Reverse mapping to rewrite the html URL in the pages to extension less
      Forward mapping to map the incoming request to resource

This is tested in AEM 6.2 version

Apache configurations:


#Handle the landing page
RewriteRule ^/$ /en/ [R=301,L]
#Mask the /content/geometrixx-outdoors path
RewriteRule ^/content/geometrixx-outdoors/(.*)(\.html)?$ /$1 [NE,L,R=301]

#Replace the .html with /
RewriteCond %{REQUEST_URI} \.html$
RewriteRule ^/(.*).html$ /$1/ [R=301,L,QSA]

#Append the .html for those URL's ending with / before sending to publisher
RewriteCond %{REQUEST_URI} !^/$
RewriteRule ^/(.*)/$ /$1.html [PT,L,QSA]

Publisher etc/map configurations:


Create a node localhost.8080(replace with required DNS and port) of type sling:Mapping under /etc/map/http or /etc/map/https based on the protocol used

Add the following property

sling:internalRedirect[] - /content/geometrixx-outdoors

<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
    jcr:primaryType="sling:Mapping"
    sling:internalRedirect="[/content/geometrixx-outdoors]">
    <redirect/>
    <reverse/>
</jcr:root>

AEM-extension-less-URL


Sunday, April 1, 2018

Different approaches to perform Vanity/Redirect URL management in Adobe Experience Manager(AEM)

Different approach to perform Vanity/Redirect URL management in Adobe Experience Manager(AEM)

In Adobe Experience Manager there is no centralized management UI to manage the Vanity/Redirect URL's also the vanity/Redirects are added into multiple places like Apache and AEM.

This post will explain the different approach to manage the Vanity/Redirect URL through centralized management UI.

Option1: Manage the Vanity URL's through VanityPath page property

  • Build a UI application to read vanityPath properties from the repository content nodes and enable management options - Add, Delete, Modification
  • Refer the following URL for details on this approach - https://helpx.adobe.com/experience-manager/using/vanitypath.html(only working in 6.1)
  • Whitelist vanity paths in dispatcher - https://helpx.adobe.com/experience-manager/dispatcher/using/dispatcher-configuration.html#EnablingAccesstoVanityURLsvanityurls
The same approach can be followed to manage the redirect path enabled in AEM

Vanity URL's are handled in AEM so all the request reaches AEM publisher

Option2 - Manage the Vanity/redirects through AEM UI on XML and redirect through Java Filter


VanityURL_Redirect_Java_Filter


Store the vanity and redirects mapping in a XML file with in AEM repository

<rules>
<rule>
<siteName></siteName>
<code></code>
<sourcePath></sourcePath>
<target></target>

</rule>
<rules>

  • Build a UI application to manage the redirects in the file - modify/remove and add new rules
  • Replicate the mapping XML to publisher on every modification through replication API
  • Build a Java filter that will redirect to the target URL if the vanity path is defined in the XML file(the filter should be restricted only required path)
  • Whitelist the vanitypaths in Apache – Expose the vanitypaths through custom URL(Servlet expose the list of vanity URLs by parsing the XML) and configure the URL in Apache for whitelisting(Refer https://helpx.adobe.com/experience-manager/dispatcher/using/dispatcher-configuration.html#EnablingAccesstoVanityURLsvanityurls for apache configuration, the vanity list URL should be custom)

Vanity/Redirects are handled in AEM so all the request reaches AEM publisher

Wednesday, March 21, 2018

How to resolve Adobe Experience Manager(AEM) pointing to Search and Promote(S&P) Stage environment?

How to resolve Adobe Experience Manager(AEM) pointing to Search and Promote(S&P) Stage environment?


Recently i have faced a issues on AEM publisher pointing to Search and Promote(S&P) stage environment irrespective of the environment configuration in OSGI configuration( Adobe Search&Promote Integration )

Search_and_Promote_integration_config

How to confirm AEM is pointing to S&P stage environment:


Check the content of searchformxml property from /etc/cloudservices/search-promote/<<S&P Config Name>>/jcr:content and check the <action> URL

Stage - <action>http://stage.xxxxx.guided.ss-omtrdc.net</action>
Live - <action>http://xxxxx.guided.ss-omtrdc.net</action>

Search_and_Promote_cloud_config_searchformxml


The following steps can be followed as a workaround:


Decode the data if it is already encoded(HTML Decoder) - searchformxml property from /etc/cloudservices/search-promote/<<S&P Config Name>>/jcr:content

Remove <input type="hidden" name="sp_staged" value="1" />

Change the following URLs to point to live configuration

//content.atomz.com/xxxxx/stage/autocomplete_data.js to //content.atomz.com/xxxxx/publish/autocomplete_data.js
//content.atomz.com/xxxxx/stage/autocomplete_styles.css to //content.atomz.com/xxxxx/publish/autocomplete_styles.css

Change the action to point to live URL

<action>http://stage.xxxxx.guided.ss-omtrdc.net</action> to <action>http://xxxxx.guided.ss-omtrdc.net</action>


e.g - this will be different based on your S&P configuration

<searchform>
<autocomplete>
<enabled>1</enabled>
<css><![CDATA[<link rel="stylesheet" type="text/css" href="//content.atomz.com/xxxxxx/publish/autocomplete_styles.css?sp_css_param=1" />]]></css>
<form-content><![CDATA[<div id="autocomplete"></div>]]></form-content>
<javascript><![CDATA[<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/yui/2.8.0r4/build/utilities/utilities.js" ></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/yui/2.8.0r4/build/datasource/datasource-min.js" ></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/yui/2.8.0r4/build/autocomplete/autocomplete-min.js"></script>
<script type="text/javascript" src="//content.atomz.com/xxxxxx/publish/autocomplete_data.js?sp_js_param=5"></script>]]></javascript>
</autocomplete> <tnt> <enabled>0</enabled> <form-content><![CDATA[<div id="tntMBox"></div>]]></form-content> <javascript><![CDATA[<script type="text/javascript">
(function(){var searchTextBoxId='q';var mboxContainerId='tntMBox';var mboxName='searchParamMbox';function removeEventSimple(obj,evt,fn)
{if(obj.removeEventListener)
obj.removeEventListener(evt,fn,false);else if(obj.detachEvent)
obj.detachEvent('on'+evt,fn);}
function addEventSimple(obj,evt,fn)
{if(obj.addEventListener)
obj.addEventListener(evt,fn,false);else if(obj.attachEvent)
obj.attachEvent('on'+evt,fn);}
function setSearchFormMbox()
{mboxDefine(mboxContainerId,mboxName);mboxUpdate('searchParamMbox');removeEventSimple(el,'keydown',setSearchFormMbox);}
var el=document.getElementById(searchTextBoxId);if(el)
addEventSimple(el,'keydown',setSearchFormMbox);})();</script>
]]></javascript> </tnt> <form>
<name>searchform</name>
<id>searchform</id>
<action>http://xxxxxx.guided.ss-omtrdc.net</action>
<inputs>
<input>
<type><![CDATA[text]]></type>
<id><![CDATA[q]]></id>
<name>q</name>
<value></value>
</input>
<input>
<type><![CDATA[submit]]></type>
<value><![CDATA[Search]]></value>
</input>
</inputs>
</form>
</searchform>

If the same S&P configuration with live option is enabled in any other server then copy and replace the value of searchformxml in /etc/cloudservices/search-promote/<<S&P Config Name>>/jcr:content

I have faced this issue in Adobe Experience Manager(AEM) 6.2 version

Tuesday, March 20, 2018

Different approaches to calculate content/DAM folders size in Adobe Experience Manager(AEM)

Different approaches to calculate content/DAM folders size in Adobe Experience Manager(AEM)

In Adobe Experience Manager(AEM), there is no direct approach to get the size of the specific content node or DAM.

This post explains the different approach to calculate the size for specific content or DAM path

Creating package through package manager:


Create the package through package manager for specific content/DAM path.
Build and download the package and calculate the size.

AEM_create_package_calculate_size


AEM_create_package_calculate_size

This approach will create space issue in server while creating the packages.

Calculate size through WebDav client:


Use any WebDav client to calculate the size of the DAM folders, I have used WinScp tool for size calculation

AEM_Webdav_client_calculate_size


AEM_Webdav_client_calculate_size


AEM_Webdav_client_calculate_size


This approach
- Can be only used for DAM assets as HTML contents are mapped as folders in WedbDav(AEM configuration)
- Can be only used in WebDav enabled AEM instances

Monday, March 12, 2018

Exception in thread "main" java.lang.NoSuchMethodError: org.slf4j.helpers.MessageFormatter.format(Ljava/lang/String;Ljava/lang/Object;)Lorg/slf4j/helpers/FormattingTuple;Jcr2davRepositoryFactory

I was getting the below exception while connecting to AEM JCR repository through Java API(JCR webdav) using Jcr2davRepositoryFactory.

Exception in thread "main" java.lang.NoSuchMethodError: org.slf4j.helpers.MessageFormatter.format(Ljava/lang/String;Ljava/lang/Object;)Lorg/slf4j/helpers/FormattingTuple;
at org.slf4j.impl.Log4jLoggerAdapter.debug(Log4jLoggerAdapter.java:229)
at org.apache.jackrabbit.jcr2spi.Jcr2spiRepositoryFactory$RepositoryConfigImpl.getCacheBehaviour(Jcr2spiRepositoryFactory.java:272)
at org.apache.jackrabbit.jcr2spi.Jcr2spiRepositoryFactory$RepositoryConfigImpl.<init>(Jcr2spiRepositoryFactory.java:229)
at org.apache.jackrabbit.jcr2dav.Jcr2davRepositoryFactory.getRepository(Jcr2davRepositoryFactory.java:104)
at org.apache.jackrabbit.jcr2dav.Jcr2davRepositoryFactory.getRepository(Jcr2davRepositoryFactory.java:87)
at workarea.core.GetRepositorySize.main(GetRepositorySize.java:25)

To fix the issue add the slf4j-log4j12 with lower version and also exclude jcl-over-slf4j from jackrabbit-jcr2dav dependency.

<dependency>
<groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.5.0</version>
</dependency>
 
<!-- https://mvnrepository.com/artifact/org.apache.jackrabbit/jackrabbit-jcr2dav -->
<dependency>
    <groupId>org.apache.jackrabbit</groupId>
    <artifactId>jackrabbit-jcr2dav</artifactId>
    <version>2.17.1</version>
    <scope>provided</scope>
    <exclusions>     
        <exclusion>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Wednesday, February 21, 2018

Caused by: java.lang.NoClassDefFoundError: javax/management/InstanceAlreadyExistsException while connecting to Oracle Database from OSGI - Adobe Experience Manager(AEM)

Caused by: java.lang.NoClassDefFoundError: javax/management/InstanceAlreadyExistsException while connecting to Oracle Database from OSGI - Adobe Experience Manager(AEM)

I was getting the below exception while connecting to the Oracle 11g database using ojbdc6.jar from OSGI in Adobe Experience Manager(AEM)

20.02.2018 15:43:39.259 *INFO* [CM Event Dispatcher (Fire ConfigurationEvent: pid=com.day.commons.datasource.jdbcpool.JdbcPoolService.c26da860-d7f1-4e63-9b2c-1138a6bafaeb)] day.commons.datasource.jdbcpool Configuring and activating data source with name=SampleOracleDS
20.02.2018 15:43:39.260 *ERROR* [CM Event Dispatcher (Fire ConfigurationEvent: pid=com.day.commons.datasource.jdbcpool.JdbcPoolService.c26da860-d7f1-4e63-9b2c-1138a6bafaeb)] day.commons.datasource.jdbcpool [com.day.commons.datasource.jdbcpool.JdbcPoolService(2238)] The activate method has thrown an exception (java.lang.IllegalArgumentException: Cannot initialize driver 'oracle.jdbc.driver.OracleDriver')
java.lang.IllegalArgumentException: Cannot initialize driver 'oracle.jdbc.driver.OracleDriver'
at com.day.commons.datasource.jdbcpool.JdbcPoolService.initalizeDriver(JdbcPoolService.java:301)
at com.day.commons.datasource.jdbcpool.JdbcPoolService.setupDataSource(JdbcPoolService.java:227)
at com.day.commons.datasource.jdbcpool.JdbcPoolService.activate(JdbcPoolService.java:174)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.felix.scr.impl.helper.BaseMethod.invokeMethod(BaseMethod.java:222)
at org.apache.felix.scr.impl.helper.BaseMethod.access$500(BaseMethod.java:37)
at org.apache.felix.scr.impl.helper.BaseMethod$Resolved.invoke(BaseMethod.java:615)
at org.apache.felix.scr.impl.helper.BaseMethod.invoke(BaseMethod.java:499)
at org.apache.felix.scr.impl.helper.ActivateMethod.invoke(ActivateMethod.java:295)
at org.apache.felix.scr.impl.manager.SingleComponentManager.createImplementationObject(SingleComponentManager.java:302)
at org.apache.felix.scr.impl.manager.SingleComponentManager.createComponent(SingleComponentManager.java:113)
at org.apache.felix.scr.impl.manager.SingleComponentManager.getService(SingleComponentManager.java:832)
at org.apache.felix.scr.impl.manager.SingleComponentManager.getServiceInternal(SingleComponentManager.java:799)
at org.apache.felix.scr.impl.manager.SingleComponentManager.getService(SingleComponentManager.java:749)
at org.apache.felix.framework.ServiceRegistrationImpl.getFactoryUnchecked(ServiceRegistrationImpl.java:343)
at org.apache.felix.framework.ServiceRegistrationImpl.getService(ServiceRegistrationImpl.java:243)
at org.apache.felix.framework.ServiceRegistry.getService(ServiceRegistry.java:357)
at org.apache.felix.framework.Felix.getService(Felix.java:3671)
at org.apache.felix.framework.BundleContextImpl.getService(BundleContextImpl.java:470)
at org.apache.felix.scr.impl.manager.SingleRefPair.getServiceObject(SingleRefPair.java:72)
at org.apache.felix.scr.impl.helper.BindMethod.getServiceObject(BindMethod.java:576)
at org.apache.felix.scr.impl.manager.DependencyManager.getServiceObject(DependencyManager.java:2037)
at org.apache.felix.scr.impl.manager.DependencyManager.invokeUnbindMethod(DependencyManager.java:1712)
at org.apache.felix.scr.impl.manager.SingleComponentManager.invokeUnbindMethod(SingleComponentManager.java:392)
at org.apache.felix.scr.impl.manager.DependencyManager$MultipleDynamicCustomizer.removedService(DependencyManager.java:372)
at org.apache.felix.scr.impl.manager.DependencyManager$MultipleDynamicCustomizer.removedService(DependencyManager.java:303)
at org.apache.felix.scr.impl.manager.ServiceTracker$Tracked.customizerRemoved(ServiceTracker.java:1518)
at org.apache.felix.scr.impl.manager.ServiceTracker$Tracked.customizerRemoved(ServiceTracker.java:1413)
at org.apache.felix.scr.impl.manager.ServiceTracker$AbstractTracked.untrack(ServiceTracker.java:1273)
at org.apache.felix.scr.impl.manager.ServiceTracker$Tracked.serviceChanged(ServiceTracker.java:1452)
at org.apache.felix.framework.util.EventDispatcher.invokeServiceListenerCallback(EventDispatcher.java:987)
at org.apache.felix.framework.util.EventDispatcher.fireEventImmediately(EventDispatcher.java:838)
at org.apache.felix.framework.util.EventDispatcher.fireServiceEvent(EventDispatcher.java:545)
at org.apache.felix.framework.Felix.fireServiceEvent(Felix.java:4547)
at org.apache.felix.framework.Felix.access$000(Felix.java:106)
at org.apache.felix.framework.Felix$1.serviceChanged(Felix.java:436)
at org.apache.felix.framework.ServiceRegistry.unregisterService(ServiceRegistry.java:165)
at org.apache.felix.framework.ServiceRegistrationImpl.unregister(ServiceRegistrationImpl.java:140)
at org.apache.felix.scr.impl.manager.AbstractComponentManager$3.unregister(AbstractComponentManager.java:883)
at org.apache.felix.scr.impl.manager.AbstractComponentManager$3.unregister(AbstractComponentManager.java:857)
at org.apache.felix.scr.impl.manager.RegistrationManager.changeRegistration(RegistrationManager.java:140)
at org.apache.felix.scr.impl.manager.AbstractComponentManager.unregisterService(AbstractComponentManager.java:925)
at org.apache.felix.scr.impl.manager.AbstractComponentManager.doDeactivate(AbstractComponentManager.java:774)
at org.apache.felix.scr.impl.manager.AbstractComponentManager.deactivateInternal(AbstractComponentManager.java:757)
at org.apache.felix.scr.impl.manager.SingleComponentManager.reconfigure(SingleComponentManager.java:601)
at org.apache.felix.scr.impl.manager.SingleComponentManager.reconfigure(SingleComponentManager.java:552)
at org.apache.felix.scr.impl.config.ConfigurableComponentHolder.configurationUpdated(ConfigurableComponentHolder.java:419)
at org.apache.felix.scr.impl.config.ConfigurationSupport.configurationEvent(ConfigurationSupport.java:297)
at org.apache.felix.cm.impl.ConfigurationManager$FireConfigurationEvent.sendEvent(ConfigurationManager.java:2032)
at org.apache.felix.cm.impl.ConfigurationManager$FireConfigurationEvent.run(ConfigurationManager.java:2002)
at org.apache.felix.cm.impl.UpdateThread.run(UpdateThread.java:103)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NoClassDefFoundError: javax/management/InstanceAlreadyExistsException
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at com.day.commons.datasource.jdbcpool.JdbcPoolService.initalizeDriver(JdbcPoolService.java:299)
... 54 common frames omitted
Caused by: java.lang.ClassNotFoundException: javax.management.InstanceAlreadyExistsException not found by com.jdbc.oracle [446]
at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1557)
at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:79)
at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1998)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 59 common frames omitted

Based on the analysis the classes required by the ojdbc.jar is missing in the generated bundle.

Steps to fix the issue -

Refer the following post for complete steps to integrate Adobe Experience Manager(AEM) with Oracle Database - https://www.albinsblog.com/2015/03/how-to-connect-to-oracle-database-using.html

Add the below Import-Package in META-INF\MANIFEST.MF file

Import-Package: javax.sql, javax.naming, javax.management, org.ietf.jgss


import-package-oracle-osgi-driver


  • Generate the bundle by adding the above configuration(Export --> Deployable plug-ins and fragments)
  • Delete the bundle if already exist in the server
  • Install the updated bundle
  • Restart the server
  • Test the integration

How to extend the OOB Adobe Experience Manager(AEM) Hybris connector

How to extend the OOB Adobe Experience Manager(AEM) Hybris connector

This video explains the details on extending the OOB Adobe Experience Manager(AEM) Hybris connector with custom functionalities


Saturday, February 17, 2018

Approach to implement content preview environment in Adobe Experience Manager(AEM)

Approach to implement content preview environment in Adobe Experience Manager(AEM)


By default Adobe Experience Manager(AEM) not provides the preview instance to preview the content before publishing to live environment but most of the cases preview is required before publishing the content to live environment.

This post explain the approach to preview and approve the content before publishing to live environment.

The below diagram explains the preview flow

AEM_Preview_environment


  • Author creates the content in production author and start the workflow
  • Workflow sends the content to Stage author and Publishers
  • Workflow assign the task to approver group and send the notification email
  • Approver reviews the content in stage environment and approve or reject the content (workflow)t - provides the detailed information for rejection
  • if the content is approved 
    • Workflow sends the approved content to production publishers.
  • If the content is rejected
    • Workflow assign the task to author and sends the notification
    • Author review the details and completes the workflow
    • Start the process again by correcting the content

Define Replication process step with ECMA script:


Create ecma file replicate.ecma under /etc/workflow/scripts/<<application>>  e.g. /etc/workflow/scripts/blog - This ecma script helps to replicate the content to stage environments


var workflowData = workItem.getWorkflowData();
var path = workflowData.getPayload().toString();
var session = workflowSession.getSession();

var replicator = sling.getService(Packages.com.day.cq.replication.Replicator);
var options = new Packages.com.day.cq.replication.ReplicationOptions();

for(var i=0;i<args.length;i++) {
    var agent= args[i];
    var filter = new Packages.com.day.cq.replication.AgentIdFilter(agent);
    options.setFilter(filter);
    options.setSuppressStatusUpdate(true);
    try {
        replicator.replicate(session, Packages.com.day.cq.replication.ReplicationActionType.ACTIVATE, path, options);
} catch(e) {
    log.error("Cannot replicate page : " + path +"on publisher. (agentId: " + agent + "): " + e);
}
}

AEM_preview_environment_approver

Saturday, January 27, 2018

How to integrate Adobe Experience Manager(AEM) and SAP Hybris through OOB connector

How to integrate Adobe Experience Manager(AEM) and SAP Hybris through OOB connector


This post explains the detailed steps for AEM and Hybris integration through OOB connector. AEM comes with default Hybris connector and sample demo site(should be downloaded via package manager), the steps covered in the post is for integrating AEM 6.3 with Hybris 6.1 but the same steps works for other AEM and Hybris versions with minimal changes.

AEM Configuration:


Install JDK 8
Install AEM 6.3 server
Install cq-geometrixx-all-pkg-5.10.68.zip, cq-geometrixx-hybris-content-6.3.2.zip and cq-hybris-content-6.3.2.zip packages from package share (I am considering geo-metrixx for demo, we.retail should be the recommended one in AEM 6.3)

aem-hybris-integration-packages

Change the Hybris server version in "Day CQ Commerce Hybris Configuration", ignore to default value if the specified version is not listed.

aem-hybris-integration-hybris-version

Change the Hybris OAuth endpoint in "Hybris OAuth Handler" based on the Hybris version, /authorizationserver/oauth/token for Hybirs 6 and later and /rest/oauth/token for earlier Hybris versions   - This step can be ignored for AEM 6.3 as the connectes defaults the values based on the Hybris version selected in the previous step.

aem-hybris-integration-OAuth-url

If the OAuth URL is not configured with correct value then the below exception will be displayed in error log

com.adobe.cq.commerce.hybris.impl.OAuthHandler Server did not respond with 2xx -> authentication failed.

Saturday, January 20, 2018

How to use Re-Fetching Flush Agent in Adobe Experience Manager(AEM)

This tutorial explains the details on AEM re-fetching flush agent and how to use to flush the content through re-fetching flush agent.

Re-Fetching Flush Agent


With regular flush agent, the agent flush the cache and the flushed content would only be retrieved from the publisher again after first time requested. This will create issue if the multiple parallel requests hit the dispatcher after flush as the new page is not yet cached in the dispatcher.



The re-fetching flush agent in AEM make sure the pages are requested and cached on the dispatcher immediately after replication.

Using a re-fetching flush agent allows to pre-populate the cache as it instructs the dispatcher to retrieve the pages from publish instance immediately after the flush occurs. Re-fetching flush agent works same as normal flush agent in dispatcher, additionally dispatcher sends a GET request for the content paths in the flush requests to fetch the content and update the cache.



Re-fetching flush is slow when activating lot of pages, enable the re-fetching only for specific content that is frequently accessed and activated.

The re-fetching feature is available in dispatcher since version 4.0.9

Configure Re-Fetching Flush agent


As a first step, develop a content builder that will send the flush URL’s into the flush request part of request body. The flush agent uses POST method to invoke dispatcher flush.

The sample content builder bundle can be downloaded from the below URL

https://github.com/techforum-repo/bundles/tree/master/refetching-flush-agent

The agent bundle is tested with AEM as Cloud Service Development Instance with aem-sdk-api dependency, the same can be modified to use uber-jar dependency.

Install the bundle to publisher as configuring the flush agent in the publish server is recommended— mvn clean install -PautoInstallBundle -Daem.port=4503

Now new serialization type “Re-fetch Dispatcher flush” is enabled while configuring the agents.


Define a re-fetching flush agent in publisher with required details, the process is same as normal flush agent with some additional configurations

In Settings tab select the “Serialization Type” as “Re-Fetch Dispatcher Flush”

In Extended tab add POST as the HTTP Method for sending the request to Dispatcher






In AEM Cloud Service, content is published using Sling Content Distribution . The replication agents used in previous versions of AEM are no longer used or provided, configure the required forward agent configurations to distribute the changes.

Refer the below URL for details on configuring forward distribution

https://medium.com/@techforum/sling-content-distribution-in-aem-part-1-35158614dc53

Now distribute/activate a page and verify the Re-Fetching Flush Agent, the activated page is updated in dispatcher before first time requesting the page.



The re-fetching flush agent will helps to improve the performance of the frequently used critical pages, be cautious while using this feature as so many page activation will impact the AEM performance.

Friday, January 19, 2018

Serving the static resources through different domains(Cookie less Domains) - Adobe Experience Manager(AEM)

Serving the static resources through different domains(Cookie less Domains) - Adobe Experience Manager(AEM) 


This post will explain the approach to improve the page load time of the websites through serving static resources via multiple cookie less domain.

The page load time of the website directly related to the number of resources requested to render the page in browser, most of the cases the browser makes multiple calls to receive the related resources.

The browser is restricted with number of default simultaneous connections per server, if the number of resources requested in the same domain is more then that will delay the page load time - the resources are loaded sequentially(this restriction is more for HTTP 1.1 but HTTP 2 protocol support parallel downloading). This issue can be addressed by distributing the static resources across multiple domains that will intern increase the parallel download of resources.

The static resource to be on a cookie-less domain that makes the content load faster. The Cookies are uploaded with every request on a domain although they are only required on dynamic pages. This will add additional overhead while requesting the static resources through a cookie aware domain and increases the page load time - loading the cookie to request and download the cookie from the response.

To avoid this problem as discussed above define multiple domains and those are cookie less.

To define a cookie less domain, create a multiple domains e.g static1.example.com, static2.example.com etc and CNAME points to the parent domain - Make sure the cookie is set in the server only specific to the parent domain.

In Adobe Experience Manager(AEM) this can be achieved in the below two approaches

Component level:


Changing the static resource URL's in individual components with newly defined domains based on the resource type - may be separate domain for images, scripts, css etc. This will required more effort and also every component level changes to assign the specific URL's for the static resources. There is a possibly the developer will not implement this in all the components and the resources will be served from main domain.


Sling Rewriter to change the static resource URL's:


Define a Static Resource Transformer that will rewrite the resource URL's with static domains defined - multiple domains can be used

The ACS Static Reference Rewriter can be used to change the static resource URL's - https://adobe-consulting-services.github.io/acs-aem-commons/features/utils-and-apis/static-reference-rewriter/index.html

I have defined a Static Resource rewriter based on the above one to add some additional functionalities to match our requirements, thought of sharing as this may help someone with same requirement.

  • Exclude the rewrite based on attribute name and values
  • Exclude the rewrite for external resources
  • Exclude based on the complete path and URL prefix 
  • Rewrite the URL's for all srcset URL's 
  • The Rewriter is invoked only for specific content path.

StaticResourceTransformFactory.java

import java.io.IOException;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Modified;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.PropertyUnbounded;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.apache.sling.rewriter.ProcessingComponentConfiguration;
import org.apache.sling.rewriter.ProcessingContext;
import org.apache.sling.rewriter.Transformer;
import org.apache.sling.rewriter.TransformerFactory;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.apache.felix.scr.annotations.ConfigurationPolicy;

@Component(
label = "Static Resources Transformer Factory",
description = "Static Resources Transformer Factory",
        metatype = true,policy = ConfigurationPolicy.REQUIRE)
@Service
@Properties({
    @Property(
            name = "pipeline.type", label = "Static Resources Transformer Pipeline Type",description ="Static Resources Transformer Pipeline Type"),
    @Property(
            name = "webconsole.configurationFactory.nameHint",
            value = "Static Resources Transformer: {pipeline.type}")
})

public final class StaticResourceTransformFactory implements TransformerFactory {
    public final class StaticResourceTransformer extends org.apache.cocoon.xml.sax.AbstractSAXPipe
    implements org.apache.sling.rewriter.Transformer {

    @Override
    public void startElement(String uri, String localName, String qname, Attributes attr) throws SAXException {

      final String[] includeElementAttributesArray =includeElementAttributes.get(localName);
    AttributesImpl attrs = new AttributesImpl(attr);
   
    boolean excludeAttributeValue=false;
   
    for (int i = 0; i < attrs.getLength(); i++) {
    final String[] excludeAttributeValuesArray = excludeAttributeValues.get(attrs.getLocalName(i));
    excludeAttributeValue=ArrayUtils.contains(excludeAttributeValuesArray, attrs.getValue(i));
    LOG.info("excludeAttributeValue:"+excludeAttributeValue);

    if(excludeAttributeValue)
    {
    break;
    }
    }

    for (int i = 0; i < attrs.getLength(); i++) {
    String name = attrs.getLocalName(i);
    String value = attrs.getValue(i);
   
    if (ArrayUtils.contains(includeElementAttributesArray, name)
    && !ArrayUtils.contains(excludePath, value) && !isExcludedPrefix(excludePrefix,value)
    &&!(value.startsWith("https") || value.startsWith("http") || value.startsWith("//")) && !excludeAttributeValue) {
    {
    if(name.equals("srcset"))
    {
    String[] srcset=value.split(",");
    String srcsetValue="";
    for(int j=0;j<srcset.length;j++)
    {
    if(!(value.startsWith("https") || value.startsWith("http") || value.startsWith("//")))
    {
    srcsetValue=!srcsetValue.equals("")?srcsetValue+","+ prependHostName(srcset[j].trim()):srcsetValue+prependHostName(srcset[j].trim());
    }else
    {
    srcsetValue=srcsetValue+","+srcset[j];
    }
    }
    attrs.setValue(i, srcsetValue);
   
    }else
    {
    attrs.setValue(i, prependHostName(value));
    }
    }
    }
    }

    super.startElement(uri, localName, qname, attrs);

    }


Monday, January 15, 2018

Developing a caching service to cache third part elements to improve performance in Adobe Experience Manage(AEM)

Developing a caching service to cache third part elements to improve performance in Adobe Experience Manage(AEM) 


This post will explain the approach to cache third party elements to improve performance.
In AEM sometime we may have to load the third party data e.g. country list, state list to drop-down lists or other components from external service call, the response will be static and changes occasionally over time.

To improve the performance the data can be cached in AEM and enable a JMX bean to clear the cache whenever the data is modified in the external system. This approach can be modified according to the requirement, if the volume of the cache data is more then better to integrate with external caching system like ehcache.

Define the cache manager to put/get the cache objects
Define JMX bean to clear the cache objects

1. Define  CacheManager  to put/get objects into cache and methods to clear the cache through JMX bean

public class CacheManager {

  private static java.util.HashMap<String,Object> cacheHashMap = new java.util.HashMap<String,Object>();

  public static void putCache(Object object, String identifier)
  {
    cacheHashMap.put(identifier, object);
  }

  public static Object getCache(String identifier)
  {
  Object object = cacheHashMap.get(identifier);  
      return object;  
  }

   public static String removeCacheWithKey(String identifier)
  {
    if(!cacheHashMap.containsKey(identifier))
    {
    return "Invalid Key..";
    }
cacheHashMap.remove(identifier);  
return "Removed cache with key "+identifier;
 
  }

   public static String removeCacheAll()
  {
    cacheHashMap.clear();
    return "Removed cache";
 
  }

}


2. Sample client to get/put object into cache

public class CacheCleint {

public static void main(String[] args) {

String[] countrylist=new String[]{"USA","UK","AUS","IN"};

CacheManager.putCache(countrylist, "country-list");

String[] cachedCountrylist=(String[])CacheManager.getCache("country-list");

System.out.println(cachedCountrylist[1]);
}

}

3. Define JMX mbean to clear the cache

Define JMX mbean that will help to clear cache from OSGI JMX console or other JMX client.

import com.adobe.granite.jmx.annotation.Description;
import com.adobe.granite.jmx.annotation.Name;

@Description("Cache Manager JMX Bean")
public interface CacheManagerMBean {

    @Description("Remove the cache with cache id - country-list,state-list")
    String removeCacheWithKey(@Name("cacheKey") @Description("Valid cache key") String Cachekey);

    @Description("Remove All Cache")
    String removeCacheAll();
}

import javax.management.NotCompliantMBeanException;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;

import com.adobe.granite.jmx.annotation.AnnotatedStandardMBean;

@Component(immediate = true)
@Property(name = "jmx.objectname", value = "com.packagegenerator.core:type=CacheManager")
@Service
public class CacheManagerMBeanImpl extends AnnotatedStandardMBean implements CacheManagerMBean {

    public CacheManagerMBeanImpl() throws NotCompliantMBeanException {
        super(CacheManagerMBean.class);
    }

    @Override
    public String removeCacheWithKey(String cacheKey) {
    return CacheManager.removeCacheWithKey(cacheKey);
    }

    @Override
    public String removeCacheAll() {   
    return CacheManager.removeCacheAll();   
    }
 
}

The cache objects specified to a key or complete cache can be cleared through JMX client.

This will enable to cache the static data from a external system into AEM and improve the performance, the cache can be cleared through JMX console whenever required.

jmx-bean-cache-clear

jmx-bean-cache-clear

jmx-bean-cache-clear

jmx-bean-cache-clear

Sunday, January 14, 2018

How to upload and install the packages through Java API - Adobe Experience Manager(AEM)

How to upload and install the packages through Java API - Adobe Experience Manager(AEM)


This post will explain the approach to upload and install the packages through JAVA.

Refer the post for details on creating the package through Java - https://www.albinsblog.com/2018/01/sling-scheduler-to-auto-create-packages-JcrPackageManager-api-aem.html

Sample Servlet to upload and install the package - Convert the servlet to scheduler and import/replicate the package based on the scheduled time

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

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

import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.jackrabbit.vault.fs.io.ImportOptions;
import org.apache.jackrabbit.vault.packaging.JcrPackage;
import org.apache.jackrabbit.vault.packaging.JcrPackageManager;
import org.apache.jackrabbit.vault.packaging.Packaging;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.sling.jcr.api.SlingRepository;
import org.apache.sling.settings.SlingSettingsService;

import com.day.cq.replication.ReplicationActionType;
import com.day.cq.replication.Replicator;

/**
 * Servlet that writes some sample content into the response. It is mounted for
 * all resources of a specific Sling resource type. The
 * {@link SlingSafeMethodsServlet} shall be used for HTTP methods that are
 * idempotent. For write operations use the {@link SlingAllMethodsServlet}.
 */
@SuppressWarnings("serial")
@SlingServlet(paths= "/services/packageupload")
public class PackageUploadServlet extends SlingSafeMethodsServlet {

@Reference
private Packaging packaging;

@Reference
private SlingRepository repository;

@Reference
private ResourceResolverFactory resolverFactory;

@Reference
private SlingSettingsService settingsService;

@Reference
Replicator replicator;

@Override
protected void doGet(final SlingHttpServletRequest req, final SlingHttpServletResponse resp)
throws ServletException, IOException {

Session session = null;
if (isRunMode("author") && isMasterRepository()) {//Only run in author - change the servlet to scheduler and import/replicate the package based on the scheduled time
try {

String packagePath = "C:\\Albin\\test12018-01-14-15-00-00-023-1.0.zip";
Map<String, Object> param = new HashMap<String, Object>();
param.put(ResourceResolverFactory.SUBSERVICE, "packageService");

ResourceResolver resolver;

resolver = resolverFactory.getServiceResourceResolver(param);

session = resolver.adaptTo(Session.class);
JcrPackageManager jcrPackageManager = packaging.getPackageManager(session);

JcrPackage inputPackage=jcrPackageManager.upload(new File(packagePath), false, true, "test12018-01-14-15-00-00-023-1.0");
ImportOptions importOption=new ImportOptions();//Specify the import configurations

inputPackage.install(importOption);

//Replicate the package to publishers
replicator.replicate(session, ReplicationActionType.ACTIVATE, inputPackage.getDefinition().getNode().getPath().split("/jcr:content")[0]);

resp.getOutputStream().println("This package successfully uploaded and installed to the server....");

} catch (Exception e) {
// TODO Auto-generated catch block
resp.getOutputStream().println("Excpetion while uploading/installing the package...."+e.getMessage());
e.printStackTrace();
}finally {
if(session!=null)
{
session.logout();
}
}
}
}

private Boolean isRunMode(String mode) {
Set<String> runModes = settingsService.getRunModes();
for (String runMode : runModes) {
if (runMode.equalsIgnoreCase(mode)) {
return true;
}
}
return false;
}

public boolean isMasterRepository() {
final String isMaster = repository.getDescriptor("crx.cluster.master");
return isMaster != null && !isMaster.equals("") && Boolean.parseBoolean(isMaster);
}
}

Sling scheduler to auto create the packages through JcrPackageManager API - Adobe Experience Manager(AEM)

Sling scheduler to auto create the packages through JcrPackageManager API - Adobe Experience Manager(AEM)


This post will explains the approach to define Sling scheduler to auto create the packages through JcrPackageManager API in Adobe Experience Manager(AEM).

Define a Service user:


Define a Service User with required access to create a  package.

Login to CRX explorer -  http://localhost:4502/crx/explorer/index.jsp
Click on User Administration

AEM-service-user

Click on Create System User

AEM-service-user

Enter the User Id - "packageassembler and the path - "system/packageassembler"

AEM-service-user