Sunday, 4 September 2016

ATG | Internationalizing the repository items

Here I am going to explain internationalization "best-practice" strategy provided by ATG.

Here are the steps :

1. Identify properties for translation in given item-descriptor. In below example title,content, location.

2. Now create new properties in base item-descriptor [article]. These properties will point to existing properties database column. For example we have created contentDefault property to refer long_description column. This column was initially referred by content property. Name these properties in such a way so that these can bee easily differentiate from derived property [postfix property name with Default].

3. Create the helper item descriptor to store the translated data. This item-descriptor will contain all the translated properties from main item-descriptor. Here articleTranslation used for this purpose.

4. Now add map type property in base item-descriptor which is map of locale to translated item [defined in above step]. In below example translations property is used to map locale to articleTranslation.

5. Change the definitions of the translatable properties in the existing item types. The new definitions should specify that each translatable property is a derived property. Here atg.repository.dp.LanguageTranslation class used to implement the derivation.

Below mechanism is used to find the values of translatable property.
  •  Use the current locale to look up a corresponding baseTypeTranslation [articleTranslation] item in the translations property map. The property derivation attempts to find a best match. First, it searches the locale keys for a match on the entire locale with a variant, then it searches for a match on the locale without a variant, and finally it searches on just the language code.
  •  If a baseTypeTranslation [articleTranslation] item exists for the current locale, use its value for the property.
  • If a baseTypeTranslation [articleTranslation] item does not exist for the current locale, or its value for the property is null, use the translatablePropertyDefault [stored in base item-descriptor] value instead.
Below is the example of internationalization : Here we have article repository item [with 3 properties title,content, location]. Here articleTranslation item-descriptor is used to translate these properties.
==========================================================================
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<gsa-template>

    <!--///////////////////////////////-->
    <!--     article                         -->
    <!--///////////////////////////////-->
   
    <item-descriptor name="article" display-property="titleDefault" display-name="article">
   
        <table name="shop_article" type="primary" id-column-name="article_id">
            <property name="id" data-type="string" column-name="article_id"  display-name="article_id"/>
            <property name="titleDefault" data-type="string" column-name="title" 

                     display-name="titleDefault"/>   
            <property name="contentDefault" data-type="big string" column-name="long_description" 

                    display-name="contentDefault"/>
            <property name="locationDefault" data-type="string" column-name="article_location" 

                    display-name="location"/>   
        </table>
       
        <property name="title" data-type="string" writable="false" hidden="true" queryable="true" 

                    display-name="title">
            <derivation user-method="atg.repository.dp.LanguageTranslation">
                <expression>titleDefault</expression>
            </derivation>
            <attribute name="defaultProperty" value="titleDefault" />
            <attribute name="defaultLocale" value="en" />
        </property>
       
        <property name="content" data-type="big string" writable="false" hidden="true" queryable="true"
            display-name="content">
            <derivation user-method="atg.repository.dp.LanguageTranslation">
                <expression>contentDefault</expression>
            </derivation>
            <attribute name="defaultProperty" value="contentDefault" />
            <attribute name="defaultLocale" value="en" />
        </property>
       
        <property name="location" data-type="string" writable="false" hidden="true" queryable="true"
            display-name="location">
            <derivation user-method="atg.repository.dp.LanguageTranslation">
                <expression>locationDefault</expression>
            </derivation>
            <attribute name="defaultProperty" value="locationDefault" />
            <attribute name="defaultLocale" value="en" />
        </property>
       
        <table name="shop_article_translations" type="multi" multi-column-name="locale" 

                     id-column-names="article_id">
            <property name="translations" display-name="Translations" 

                    column-name="translation_id"      data-type="map"  
                    component-item-type="articleTranslation"  display-name="translations">
            </property>
        </table>
       
    </item-descriptor>
   
    <!--///////////////////////////////-->
    <!--     articleTranslation      -->
    <!--///////////////////////////////-->

    <item-descriptor name="articleTranslation" id-space-name="articleTranslation" 

         display-name="articleTranslation"  display-property="title">
       
        <table name="shop_article_xlate" type="primary" id-column-name="translation_id">
            <property name="title" column-name="title" data-type="string"  display-name="Title" />
            <property name="content" data-type="big string" column-name="long_description" 

                      display-name="content"/>
            <property name="location" data-type="string" column-name="article_location"

                     display-name="location" />
        </table>
       
    </item-descriptor>
</gsa-template>

==========================================================================

Advantages of this approach : 
  • Applications can switch between international and non-international modes without requiring any JSP  page changes. 
  • No database schema changes are required to add additional languages.

Friday, 19 August 2016

Hidden Power of ATG | Service Cache

As we all know the importance of cache in web application performance. In the case of ATG most of the developers  are aware of repository and cache droplet.


While working on one of the Oracle commerce application. I came across new cache from ATG (called service cache). 

Below are the limitations of the above mentioned caches [repository/droplet].

1. Cache Droplet : Accessible through JSP pages. This caches the generated html fragments which includes whites space, this results in increased cache size [comparatively big cache].
2. Repository Cache : Applicable when accessing Database through repository layer.

This cache [Service Cache] is useful in number of scenarios like when you want to access database directly but still want to cache the results. You can also cache data like from other systems like third party response of some call or result of Endeca presentation API.

Here I am going to explain to configure this cache for caching the results in droplet call.

1. Create Cache Key Class : This class will represent the cache key object. Optionally you can directly create the string cache key in droplet itself. But this approach is useful when cache key is complex [includes language/local/segments]. This is also helpful to easily extend the cache key in future [add more fields]. Here you need to override the equals and hashCode methods [Internally used to compare cache keys].

=========================================================================
public class DropletCacheKey {

private String mLanguage;
private String mSegment;
private String mKey; 

public String getLanguage() {
        return mLanguage;
    }

public void setLanguage(String pLanguage) {
        this.mLanguage = pLanguage;
    }

public String getSegment() {
        return mSegment;
    }

public void setSegment(String pSegment) {
        this.mSegment = pSegment;
    }    

 public String getKey() {
        return mKey;
    }

public void setKey(String pKey) {
        this.mKey = pKey;
    }

 private boolean isSameRecordKey(DropletCacheKey pObject) {
        return (this.mKey == null && pObject.getKey() == null) ||
        (this.mKey!= null && pObject.getKey()!= null && pObject.getKey().equals(this.mKey)); 
    }

private boolean isSameRecordLanguage(DropletCacheKey pObject) {
        return (this.mLanguage == null && pObject.getLanguage() == null) ||
                  (this.mLanguage!= null && pObject.getLanguage()!= null
                  && pObject.getLanguage().equals(this.mLanguage)); 
    }

private boolean isSameRecordSegment(DropletCacheKey pObject) {
        return (this.mSegment == null && pObject.getSegment() == null) ||
                  (this.mSegment!= null && pObject.getSegment()!= null 
                 &&   pObject.getSegment().equals(this.mSegment)); 
    }

@Override
    public boolean equals(Object pObject){
        if(pObject instanceof
DropletCacheKey){
           
DropletCacheKey cacheKey = (DropletCacheKey) pObject;
            return (isSameRecordKey(
cacheKey)
                      && isSameRecordLanguage(cacheKey) && isSameRecordSegment(cacheKey));
        }
        return false;
    }

@Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("KEY : [ ");
        builder.append(mKey).append("|");
        builder.append(mLanguage).append("|");
        builder.append(mSegment);
        builder.append(" ]");
        return builder.toString();
    }

@Override
public int hashCode() {
        int PRIME = 31;
        int result = 1;
        result = PRIME * result + ((StringUtils.isBlank(mKey)) ? 0 : mKey.hashCode());
        result = PRIME * result + ((StringUtils.isBlank(mLanguage)) ? 0 : mLanguage.hashCode());
        result = PRIME * result + ((StringUtils.isBlank(mSegment)) ? 0 : mSegment.hashCode());
        return result;
    }
}
=========================================================================

2. Create Cache Adapter Class : This class contains the business logic to fetch actual result.

=========================================================================
public class DropletCacheAdapter extends GenericService implements CacheAdapter {

@Override
public Object getCacheElement(Object pKey) throws Exception {
     if (pKey != null) {
        // Write business logic here to fetch actual result and return the same
     }
}

@Override
    public int getCacheElementSize(Object pArg0, Object pArg1) {
        return 0;
    }

@Override
    public Object[] getCacheElements(Object[] pKeys) throws Exception {
        vlogDebug("Entering Object[] getCacheElements(Object[] pKeys) : " );
        if (pKeys != null) {
            int keyLength = pKeys.length;
            vlogDebug("Key Length :: " + keyLength);
            Object elements[] = new Object[keyLength];
            for (int i = 0; i < keyLength; i++) {
                elements[i] = getCacheElement(pKeys[i]);
            }
            return elements;
        } else {
            return null;
        }
    }

@Override
    public int getCacheKeySize(Object pArg0) {
        return 0;
    }

@Override
    public void removeCacheElement(Object pArg0, Object pArg1) {
    }
}
========================================================================= 
3. Create Cache Adapter Component : Configure cache adapter component using above class.

=========================================================================
# /com/cache/DropletCacheAdapter
 $class=com.cache.DropletCacheAdapter 
 $scope=global
cache=/atg/service/cache/Cache
=========================================================================
 
4. Create Cache Component : Now its time to configure cache component

=========================================================================
 # /com/cache/DropletCache
$class=atg.service.cache.Cache
$scope=global

# injecting caching adapter
cacheAdapter=
/com/cache/DropletCacheAdapter
#Configure below values as per your application need
maximumCacheEntries=10000
maximumCacheSize=10485760
maximumEntryLifetime=43200000
=========================================================================
 
5. Inject Cache component as property in droplet component : This is required as we need to refer cache inside the droplet code.

=========================================================================
 $class=com.search.droplet.StoreDroplet
$scope=global
dropletCache=
/com/cache/DropletCache
#inject other required component
=========================================================================

6. Update Droplet code to use this cache : Here first of all you need to create cachekey object based on input parameter [in this case language, segment and key]. Then invoke the get method on cache component [injected in above step].

=========================================================================
 public class StoreDroplet extends DynamoServlet {    

    private Cache  mDropletCache;

    public Cache
getDropletCache() {
        return
mDropletCache;
    }

   public void
setDropletCache(Cache pDropletCache) {
        this.
mDropletCache= pDropletCache;
    }

public void service(DynamoHttpServletRequest pRequest, DynamoHttpServletResponse pResponse) throws ServletException, IOException { 

// Create cache key using custom method here you need to write method that will return populated object
// of type DropletCacheKey you can modify definition of this object [class] as per your need.

// next fetch the result from cache using this key. This will automatically take care of adding object to cache 
// if already not done. And fetch object from cache if it is available there.
// Here you can also type cast the result. This type cast must be same as retuned type object of //getCacheElement method of cache adapter.
getDropletCache.get(dropletCacheKey);

//further you can utilize the retuned object 

}

}
=========================================================================

Note : You can monitor this cache from dyn/admin.

Monday, 15 August 2016

ATG request pipeline servlets vs J2EE servlets

Below are two major differences between ATG Request pipeline servlets and J2EE servlets.

1. ATG servlets exist in the servlet pipeline, which executes before the request reaches the J2EE web container. J2EE servlets are executed by the web container.

2. ATG servlets themselves determine the order in which they execute. The application deployment descriptor web.xml describes the order and conditions in which J2EE servlets execute.

Wednesday, 10 August 2016

ATG | Configure request handling pipeline servlets [Customize request handling pipeline]

Below are the two common ways to configure [create] request handling pipeline servlets in ATG.

1. Extend atg.servlet.pipeline.PipelineableServletImpl.
2. Extend atg.servlet.pipeline.InsertableServletImpl.

1. Extend atg.servlet.pipeline.PipelineableServletImpl 

Follow below steps to configure servlet using PipelineableServletImpl.
  • Extend atg.servlet.pipeline.PipelineableServletImpl.
  • Define the servlet as a globally scoped Nucleus component.
  • Reset the previous servlet’s nextServlet property to point to the new servlet.
  • Set the new servlet’s nextServlet property to point to the next servlet in the pipeline.
  • Add the servlet’s path to the initialServices property of /atg/dynamo/servlet/Initial. 

 2. Extend atg.servlet.pipeline.InsertableServletImpl

Follow below steps to configure servlet using InsertableServletImpl.
  • Extend atg.servlet.pipeline.InsertableServletImpl.
  • Define the servlet as a globally scoped Nucleus component.
  • Set the insertAfterServlet property of your servlet to point to the path of the pipeline servlet you want your servlet to follow. 
    For example, you can insert a servlet after StoreServlet as follows :
    insertAfterServlet=/atg/dynamo/servlet/dafpipeline/StoreServlet
  • Add the servlet’s path to the initialServices property of /atg/dynamo/servlet/Initial
Advantage of second approach is you no need to make any change in the existing servlets.

Wednesday, 27 July 2016

Behind the Scenes | ATG Droplet [Servlet Bean] Internal Processing

Today found some interested information about ATG droplet processing.


When a JSP executes a servlet bean, the dsp:droplet cycles through its code internally several times in order to arrange the servlet bean code in a manner that is cohesive with the expectations of open parameters.

For example below code.
<dsp:droplet name="/atg/dynamo/droplet/ForEach"> 
  <dsp:param name="array" bean="/samples/Employees"/>
     <dsp:oparam name="output">
        <dsp:valueof param="element.name"/>
     </dsp:oparam>
 </dsp:droplet>

Processing Steps :

1. The dsp:droplet tag is called.

2. dsp:droplet allows its body to be executed once. During that execution, the nested input parameter tags (in this case, just array) pass their information back to dsp:droplet, which uses it to construct a table of input parameter names (array) and values. The open parameter tags are ignored during this phase.

3. dsp:droplet finds the servlet bean referenced by the dsp:droplet “name=" property (forEach) and calls the servlet bean’s service() method with the input parameter values collected during step 2.

4. As the servlet bean executes, it halts calls to setParameter and serviceParameter, and instead records them as a list of DropletActions. These methods are organized in a manner that is readable by the open parameters that process them and are made available to open parameters for execution.

5. The dsp:droplet parses through each setParameter and serviceParameter method in DropletActions.
  • setParameter directs the dsp:droplet to set the specified request parameter to the recorded name (ouput) and value (element).
  • serviceParameter instructs the dsp:droplet to allow its body to be executed. This causes the related open parameter to run.
6. After the dsp:droplet finishes the DropletActions list, servlet bean execution ends.

Sunday, 10 July 2016

Debug\Change Log Levels of CAS Crawls

CAS service logs messages for crawls in cas-service.log.

Below are the valid logging levels.

     DEBUG, INFO [Default logging level], WARN, ERROR, FATAL, OFF 

You can easily change logging level for crawls using one of the below methods.

1. Workbench CAS Console.

From endeca Workbench CAS Console you can change log levels of particular crawl. Here no CAS service restart required. 

Select crawler from CAS Console. Then click on advance settings to change log level. Once log level is updated. Click on apply and save. Now run the crawl again.

CAS Crawl Log Configuration
CAS Crawl Log Configuration
 

2. CAS Log configuration file [Change here will impact all crawls].

<install path>\CAS\workspace\conf path contains property files for logging configuration.
  • cas-cmd.log4j.properties
  • cas-service-log4j.properties : For crawls modify this file[Change log4j.logger.com.endeca.itl=INFO].
  • component-manager-cmd.log4j.properties
  • recordstore-cmd.log4j.properties
After change in configuration file you need to restart the CAS service.

Log files location : <install path>\CAS\workspace\logs

Log Rolling : CAS Service log rolls once it exceeds a size of 100MB, and the CAS Service keeps 10 backups of its log.This is also configurable.

Note : If you delete the log file, the Endeca CAS Service recreates the log only when you restart the service.

Saturday, 9 July 2016

ATG 11.1 | Create Endeca application based on CRS

Sometime you need to create Endeca application based on CRS.

Follow below steps as command line log to create new application [Here Store application created].

CRS deploy.xml location : <CRS Installation Folder>\Store\Storefront\deploy\deploy.xml
=========================================================================
C:\Endeca\ToolsAndFrameworks\11.1.0\deployment_template\bin>deploy.bat --app C:\ATG\ATG11.1\CommerceReferenceStore\Store\Storefront\deploy\deploy.xml

 ------------------------------------------------------------------------------
   Found a supported version of Platform Services installed in directory
   C:\Endeca\PlatformServices\11.1.0. If the location is incorrect, type 'Q' to
   quit and adjust your ENDECA_ROOT environment variable. Press enter to
   continue with these settings.

   Continue?
 ------------------------------------------------------------------------------
     Deployment Template installation script.

     This script creates the directory structure for your
     deployment and installs configuration files and scripts
     into the directory structure.

07/06/2016 17:02:47 [deploy.pl] INFO:  Starting deployment template installation.

 ------------------------------------------------------------------------------
   The following app modules were specified on the command line argument:

   C:\ATG\ATG11.1\CommerceReferenceStore\Store\Storefront\deploy\deploy.xml


   Modules may be deployed standalone or on top of a base deployment type. Do
   you want to install a base deployment with the specified module(s)?

   Install base deployment? [Y/N]:
Y
07/06/2016 17:02:51 [AppDescriptorReader] INFO:  Parsing application descriptor
   file
   C:\ATG\ATG11.1\CommerceReferenceStore\Store\Storefront\deploy\deploy.xml.
07/06/2016 17:02:51 [AppDescriptorReader] INFO:  Parsing application descriptor
   file
   C:\Endeca\ToolsAndFrameworks\11.1.0\deployment_template\app-templates\base_descriptor.xml.

 ------------------------------------------------------------------------------
   Enter a short name for your application.

   Note: The name must conform to this regular expression: ^[a-zA-Z0-9]+$
    [default: CRS]

   Choosing a different application name may require additional configuration on
   your web application.

   Application name:
Store

 ------------------------------------------------------------------------------
   Specify the path into which the application will be deployed. The specified
   directory must exist and cannot contain spaces.

   For example, to deploy into c:\apps\Store, specify the path as c:\apps.

   Deployment directory:
C:\Endeca\apps

 ------------------------------------------------------------------------------
   Specify the port on which the Endeca Application Controller is running. This
   is configured in the server.xml file in the workspace of the Endeca software
   install and should be the same for all applications deployed in this
   environment. Ports must be in the range 1024-65535 [default: 8888].

   EAC port:

07/06/2016 17:03:26 [deploy.pl] INFO:  Deploying application into
   C:\Endeca\apps\Store

 ------------------------------------------------------------------------------
   Enter the port where workbench is running. [Default: 8006]

 ------------------------------------------------------------------------------
   Enter the port to use for Dgraph1. [Default: 15000]


 ------------------------------------------------------------------------------
   Enter the port to use for AuthoringDgraph. [Default: 15002]


 ------------------------------------------------------------------------------
   Enter the port to use for LogServer. [Default: 15010]

 ------------------------------------------------------------------------------
   Please enter the CAS install directory using Unix-style forward slashes,
   including the version number (e.g. C:/Endeca/CAS/11.1.0).
C:/Endeca/CAS/11.1.0

 ------------------------------------------------------------------------------
   Please enter the version for CAS jar files (or hit 'enter' to use the
   default).  [Default: 11.1.0]

 ------------------------------------------------------------------------------
   Please enter the hostname where CAS is running (or hit 'enter' to use the
   default). [Default: localhost]

 ------------------------------------------------------------------------------
   Please enter the port where CAS is running (or hit 'enter' to use the
   default). [Default: 8500]

 ------------------------------------------------------------------------------
   Please enter the language code to use (or hit 'enter' to use the default).
   [Default: en]

 ------------------------------------------------------------------------------
   Please enter the fully-qualified Workbench hostname, including domain.
localhost

 ------------------------------------------------------------------------------
   Please enter the production application server hostname. [Default: localhost]


 ------------------------------------------------------------------------------
   Please enter the production application server port number, Typical values
   are 7003 for WebLogic, 8080 for JBoss and Tomcat, and 9080 for WebSphere.
7003

 ------------------------------------------------------------------------------
   Please enter the preview hostname. [Default: localhost]

 ------------------------------------------------------------------------------
   Please enter the preview port number. Typical values are 7003 for WebLogic,
   8080 for JBoss and Tomcat, and 9080 for WebSphere.
7003

 ------------------------------------------------------------------------------
   Please enter the context root of the preview application. [Default: crs]
Store

 ------------------------------------------------------------------------------
   Enter the hostname of the user segment server. Oracle recommends using the
   Publishing server for this purpose. If your environment does not have a
   Publishing server, enter the Production server host name and refer to the
   Guided Search Integration Guide for additional configuration requirements.
   [Default: localhost]


 ------------------------------------------------------------------------------
   Enter the HTTP port of the user segment server. Oracle recommends using the
   Publishing server for this purpose. If your environment does not have a
   Publishing server, enter the Production server HTTP port and refer to the
   Guided Search Integration Guide for additional configuration requirements.
   [Default: 8080]

 ------------------------------------------------------------------------------
   Specify the path for the Oracle Wallet jps-config.xml file. [Default:
   C:\Endeca\ToolsAndFrameworks\11.1.0\server\workspace\credential_store\jps-config.xml]

 ------------------------------------------------------------------------------
   Which directory will application configuration archives be exported to.
   [Default: C:\Endeca\Apps\CRS\data\workbench\application_export_archive]
C:\Endeca\apps\Store\data\workbench\application_export_archive

 ------------------------------------------------------------------------------
   Specify the port on which Oracle Endeca Workbench is running: [Default: 8006]


 ------------------------------------------------------------------------------
   Specify the port to use for the Live Dgraph: [Default: 15000]


 ------------------------------------------------------------------------------
   Specify the port to use for the Authoring Dgraph: [Default: 15002]


 ------------------------------------------------------------------------------
   Specify the port to use for the Log Server Component: [Default: 15010]


 ------------------------------------------------------------------------------
   Specify the path for the Oracle Wallet jps-config.xml file: [Default:
   C:\Endeca\ToolsAndFrameworks\11.1.0\server\workspace\credential_store\jps-config.xml]

 ------------------------------------------------------------------------------
   Specify the path for the application configuration archives to be exported
   to: [Default:
   C:\Endeca\ToolsAndFrameworks\11.1.0\server\workspace\state\repository]

07/06/2016 17:08:13 [AppDescriptorReader] INFO:  Parsing application descriptor
   file
   C:\Endeca\ToolsAndFrameworks\11.1.0\deployment_template\app-templates\base_descriptor.xml.
07/06/2016 17:08:13 [deploy.pl] INFO:  Processing install with id 'Dgraph'
07/06/2016 17:08:15 [AppDescriptorReader] INFO:  Parsing application descriptor
   file
   C:\ATG\ATG11.1\CommerceReferenceStore\Store\Storefront\deploy\deploy.xml.
07/06/2016 17:08:15 [deploy.pl] INFO:  Processing install with id 'CRSApp'
07/06/2016 17:08:23 [deploy.pl] INFO:  Application successfully deployed.

C:\Endeca\ToolsAndFrameworks\11.1.0\deployment_template\bin>


=========================================================================
This will create application and supported directories. Next you need to initialize the application in order to provision it. Once application is provisioned you can proceed with indexing and other activities. Optionally you can export CRS record store content , dimension value id manager data and import in new application. In this case you also need to export index-config for ATG user and import in new application.