ATG Repository Basic Description

Repositories (a.k.a. Data Anywhere Architecture) is the mechanism that ATG uses to access data primarily stored in relational databases, but also LDAP or other backend systems. ATG applications are required to be very high performance, and data access is critical in that if not handled properly, it could create a bottleneck. ATG's repository functionality has been around for a long time - it's proven to be extremely scalable. Developers new to ATG need to understand how repositories work as this is a critical aspect of the ATG architecture.

Repositories essentially map relational tables to objects in ATG, as well as handle caching. ATG defines many repositories out of the box (i.e. user profile, catalog, orders, etc), and this is comprised of both the underlying database schema along with the associated repository definition files (XML). It is fully expected that implementations will extend / change the out of the box repository definitions, so there is a prescribed approach to doing this. The first thing to be sure of is to encapsulate your repository definition additions / changes within your own module (as described above). 
The other important best practice is to never modify the out of the box schema - in other words, don't add columns to existing ATG tables, just create your own new tables. These will help ensure you can easily upgrade your application at a later date.

Type of Repository:

1. SQL Repositories: GAS (GAS Stands for “Generic SQL Adapter”) repository connected to SQLdatabase and access contains, user profile, application security information.

2. SQL Profile Repository: include the ATG personalization module.
3. LDAP Repository: Uses the dynamo LDAP connector to access user data in an LDAP directory.

4. Composite Repository: provides a means for using more than one data store as source for single repository.

5. Versioned Repositories: it is extension of SQL repository used in ATG publishing. It has versions for every data.(new entry will be made with a new version number instead of editing)


ATG Commerce Order, Shipping, Payment Status Code

Order States: The status of an order indicates where the order is in the order process. You can view the order order’s status in the commerce service canter on the order Details page.

Order Statuses
Description
Approved
The order has been approved by either an approver of the organization or an agent.
Remove
The Order has been cancelled. It will not be shipped to customer.
Submit
The order has been submitted to the warehouse staff to begin fulfilment.
Incomplete
The Order is unfinished and has not been checked out by the customer.
No Pending Action
The order has shipped.
Pending Approval
The Order requires the approval of an approval of the organization or the agent before it can complete the checkout process.
Pending Remove
The Order is in the process of being cancelled.
Processing
The Order is being packed and prepared for shipment to the customer.


Shipping Group Statuses: The Status of a shipping group indicates where the individual shipping group is in the shipping process. Note that for orders with multiple shipping addresses, each shipping address has its own states. The following table describes each shipping group states.

Shipping Status
Description
Initial
The beginning state of a shipping group.
No Pending Action
The items in the shipping group have shipped. They are en route to the designed shipping address.
Pending Shipment Action
The items in the shipping group are packages and ready to ship.
Processing
The items in the shipping group are being prepared for shipment
   
Payment Group Statuses: The status of a payment group indicates where the payment group, typically a credit card, is in the payment process. You can view the status of each payment group for an order on the Order Payment page. The following table describes each payment group status.

Payment Status
Description
Authorized
Authorization for a charge to the credit card has succeeded.
Authorize Failed
Authorization for a charge to the credit card has failed.
Credit Failed
A credit of a specific amount has failed to be applied to the credit card.
Initial
The beginning state of a credit card.
Settle Failed
A charge of a specific amount has failed to be applied to the credit card.
Settled
A charge of a specific amount has been applied successfully to the credit card.

Design Pattern - Front Controller

 The front controller design pattern means that all requests that come for a resource in an application will be handled by a single handler and then dispatched to the appropriate handler for that type of request. The front controller may use other helpers to achieve the dispatching mechanism. 
In ActionServlet in Struts 1 or Dispatchers in Struts 2. Both of them are implementations of Front controller design pattern. The Front Controller design pattern is applicable and useful for all kind of applications be it web or desktop applications and is not limited to any single programming language or framework.

Several web-tier application frameworks implement the Front Controller pattern, among them:MVC frameworks (Struts and Spring),.Front controllers can be reduce duplication of code in JSP pages, see in below diagram, determining the user view with a from controller.


Design Pattern - Facade

Facades as the name suggests means the face of the building ,Operating System are one such example, You don't see all the inner workings of your computer, but the OS provides a simplified interface to use the machine, buildings also have a facade-the exterior of the building.
Facades design pattern hides the complexities of the system and provide one interface to the client for where the client can access the system, In Java JDBC can be called facade, we a users or clients create connection using the “java.sql.Connection” interface, the implementation of which we are not concerned about. The implementation is left to the vender of drive. 
Following sequence diagram illustrates how the pattern is used by a client:



Facade makes the API and libraries to use which is good for maintenance and readability .It can also collate and abstract various poorly designed APIs with a single simplified API.
Code Example:

ShippingGroup.java
public class ShippingGroup{
  public String checkShippingGroup(String OrderId) {
       return 'ShippingGroup checked';
   }
 }
PaymentGroup.java
public class PaymentGroup {
   public String deductPaymentGroup(String orderID) {
       return 'Payment deducted successfully';  
   }
}
OrderManager.java
public class OrderManager{
   private PaymentGroup pymt = new PaymentGroup();
   private ShippingGroup ship = new ShippingGroup();
 
   public void placeOrder(String orderId) {
       String step1 = ship.checkShippingGroup(orderId);
       String step2 = pymt.checkPaymentGroup(orderId);
       System.out.println('Following steps completed:' + step1  + ' & ' + step2);
   }
}
Client.java
public class Client {
  public static void main(String args[]){
    OrderManager ordermanager = new OrderManager();
    OrderManager.placeOrder('OR123456');
    System.out.println('Order processing completed');
  }
}

Design Pattern - MVC

In MVC are two types model (design Model)
1.MVC  1 Architecture
2.MCV  2 Architecture

MVC 1 Architectre:
Model 1 MVC architecture is easiest way of developing JSP based web application, It cannot get any easier. In model 1,the browser directly access JSP pages, in other words ,user requests are handled directly y the JSP .
Servlet and JSP are the main technologies to develop the web application. Servlet technology doesn’t create process, rather it create thread to handle request. The advantage of the creating thread over process is that it doesn’t allocate separate memory area and multiple subsequent request can be easily handled by the servlet.

Problem in this MVC-1 architecture presentation and business logic are mixed up,see in below flow of the model 1 Architecture.
Step 1: Browser send request for the JSP page.
Step 2: JSP accesses Java Bean and invokes business logic.
Step 3: Java Bean connect to database and make CURD operation.
Step 4: Response is send to browse which is generated by JSP 

MVC 2 Architecture:
In this short section I would try to provide a basic overview of the MVC framework.The MVC framework,is generally a term for a software architecture for implementing the user interface.You can separate the software's source code code onto different layers.
Model:This part of the framework is to store the data of the application,Such as database,text data,files and /or other web resource.
View: This is the graphical user interface of the application.That would could contain different button,text boxes and other controls to let the user interact with the application to complete his projects depending on sort of the software he is using
Controller: The actual back-end code constitutes the controller of the framework.A controller controls the data coming from the users or going to the user from a model,
In MVC-2 Architecture one very good feature framework is that is hides the data access layer from the users.That is,the data access layer or the data is never actually called directly by user;from the interface.



ATG Repository ,Item descriptor properties

Cascading Data relationship: The SQL repository uses the cascade attributes in a <property> tag to better handle hierarchical properties- that is, properties that have the attribute item-type or component-item-type. The Cascade attribute can be set to one or more of the value: insert, update delete
For Example:
<property name=”scenarios” item-type=”scenario” cascade=”update, delete”/>

In below ,whenever the author type repository item is created ,added, updated, or deleted ,the same actions apply to corresponding address repository ,see in below example:

<!-- The "author" item type -->
<item-descriptor name="author">
  <table name="author" id-column-names="author_id" type="primary">
    <property name="name"/>
    <property name="address" item-type="address" cascade="insert, update, delete"/>
  </table>
</item-descriptor>
<!-- The "address" item type -->
<item-descriptor name="address">
  <table name="address" id-column-names="address_id" type="primary">
    <property name="streetAddress"/>
    <property name="city"/>
    <property name="state"/>
    <property name="zip"/>
  </table>
</item-descriptor>

Inheritance: The SQL repository supports a simplified from of inheritance that uses an optional one-to-one relationship between the primary table and an auxiliary table. The sample repository can define one item descriptor that inherits property from another.
<!-- The "clothing" item type, a base type -->
<item-descriptor name="clothing" sub-type-property="type">

  <!-- This is the primary table that holds clothing data -->
  <table name="clothing" type="primary" id-column-names="id">
    <property name="type" data-type="enumerated">
      <option value="shirt"/>
      <option value="shorts"/>
    </property>
    <property name="name"/>
    <property name="description"/>
    <property name="color"/>
    <property name="size"/>
    <property name="shippingWeight"/>
  </table>
</item-descriptor>

<!-- The "shirt" item type is a subclass of "clothing" -->
<item-descriptor name="shirt" super-type="clothing" sub-type-value="shirt">
  <table name="shirt" type="auxiliary" id-column-names="id">
    <property name="season"/>
  </table>
</item-descriptor>

<!-- The "shorts" item type, now a subclass of "clothing" -->
<item-descriptor name="shorts" super-type="clothing" sub-type-value="shorts">
  <table name="shorts" type="auxiliary" id-column-names="id">
    <property name="pleated" data-type="boolean"/>
  </table>
</item-descriptor>
Note: Instances of objects are associated with their superclasses by ID. So, in this example, a shirt ID always has a matching clothing ID.

Transient: this property not persisted in database.The Transient properties never store or read from the persistence data storage. They are readable, writable but not queryable.You can specify a transient property by define a <property> under Item Descriptor, the property tag has associated with table.
Example:
<item-descriptor name="user" sub-type-property="userType">
    <property name="loggedIn" data-type="boolean">
    <table name="user" type="primary" id-column-names="id">
    <property name=”UserType” data-type=”enumerated” coumn-name=”user_type” />

Derived Property: An SQL repository can define derived properties, where one repository item derives property values from another repository item or from another property in the same item. Derived properties are important to data models that use a tree structure, where certain property values are passed down from other properties.
Example: <item-descriptor name="employee">
   ...
   <property name="department" item-type="department"/>
   <property name="empSpendingLimit" data-type="int"/>
   <property name="spendingLimit" writable="false">
     <derivation>
       <expression>empSpendingLimit</expression>
       <expression>department.spendingLimit</expression>
     </derivation>
   </property>
 </item-descriptor>

ATG Repository API

ATG Repository handle task:

  1. Set of interfaces that are used for generic data access.
  2. Use to manipulate repository items within Java code, including retrieving, creating, updating, deleting, and querying for items.
  3. Provides generic data access calls that mask the underlying data store from the developer.(any database can be use as it convert the data in repository objects)

Interface
Method
Repository
getItem();getView();
RepositoryItem
getPropertyvalue( );
RepositoryView
executeQuery( );
MutableRepository
addItem,CreateItem,getItemForUpdate();updateItem(); removeItem();
MutableRepositoryItem
setPropertyValue();


  • Repository: Is used to gain access to a given RepositoryItem when the ID is known; is also used to obtain a RepositoryView
  • RepositoryItem: Returns the property values for an individual item from the repository.
  • RepositoryView: Used to execute queries to return an array of RepositoryItem objects
  • MutableRepository: Provides methods used to insert, update, and delete RepositoryItem objects
  • MutableRepositoryItem: Is used to change or set the values of a RepositoryItem
  • The API provides generic data access calls so that the ATG developer can use the same method calls for LDAP and SQL data stores.
  • MutableRepository
  • Repository and RepositoryItem provide a read-only view of repository elements.
  • MutableRepository is an extension that enables repository elements to be Created, Updated, Deleted.
  • MutableRepository also provides appropriate cache synchronization.


MutableRepository objects are copies of the real objects that can be altered by the application. Because changes are not written back on each change, performance is not affected. On a call to update the repository, a new transaction is started in which its contents are written back to the repository.

ATG CartModifierFromHandler And ShoppingCartfromHandler DIfference

CartModifierFormHandler: 
Used to modify the shopping cart by adding item, deleting items and modifying the item quantities of item in cart and preparing for checkout process. Typically when using this you would have to handle checkout flow yourself by ExpressChecoutFormHandler in case of express checkout and in case of full checkout by using ShippingGroup and PaymentGroup from handlers and finally CommitFormHanlder to confirm and commit the order.

ShoppingCartFormHandler: 
Used for handling cart management (add/remove/adjust item quantity) and checkout process (shipping, billing, committing order). This provides an easier and simpler interface than using CartModifierFormHandler along other form handlers because in ShoppingCartFormHandler various functions for cart management to checkout are exposed via different handleXXX methods each having a preXXX and postXXX to extend the functionality if required. There is one Full ShoppingCartFormHandler also which extends ShoppingCartFormHandler and adds the functionality like handling multiple payment groups, split shipping, express checkout.

To summarize, ShoppingCartFormHandler provides simpler cart management and checkout implementation all in itself. Whereas CartModifierFormHandler doesn't provide you the checkout flow and therefore CartModifierFormHandler based implementation would not be that simple and require other form handlers. But CartModifierFormHandler would provide some benefits like better handling and security for concurrent updates of orders, a more flexible payment/shipping group management for use with multiple shipping or payment groups along with other things.

ATG Custom Servlet Pipeline

The atg.servlet.pipeline package provide interfaces for creating request handling pipeline servlets, All classes are directly or indirectly implement interface atg.servlet.pipeline.PipelineableServlet.


Step 1:
Write your servlet, extending  atg.servlet.pipeline.PipelineableServletImpl.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import atg.servlet.*;
import atg.servlet.pipeline.*;

public class MyServlet extends PipelineableServletImpl {
  public MyServlet () {}
  public void service (DynamoHttpServletRequest request,
                       DynamoHttpServletResponse response)
       throws IOException, ServletException
  {
    String pathInfo = request.getPathInfo ();
    // Insert here own logic
    passRequest (request, response);
  }
}

Step 2:
Define global scope component in the Nucleus hierarchy. It does not really matter where you put your servlet in the component hierarchy (though the location affects references to other components if you use relative pathnames)
Step 3:
Set the nextServlet property of your servlet to point to the path of the pipeline servlet you want your servlet to follow. For example, if you want your servlet to follow the DynamoServlet in the pipeline, use: nextServlet=/atg/dynamo/servlet/dafpipeline/DynamoServlet
Step 4:
Add the path to your servlet to the initialServices property of /atg/dynamo/servlet/Inital.initialServices initialService+=/MyServlet


 The PipelineableServlet interface has two sub-interface that provide more fexibility for inserting new servlet into pipeline. See in below diagram.


Add InsertableServlet to the servlet pipeline:

Step 1:
Write your servlet by extending  atg.servlet.pipeline.InsertableServletImpl.see in below example
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import atg.servlet.*;
import atg.servlet.pipeline.*;
public class URIPrinter extends InsertableServletImpl{
public URIPrinter () {}
public void service (DynamoHttpServletRequest request, DynamoHttpServletResponse response) throws IOException, ServletException {
System.out.println ("Handling request for " +  request.getRequestURI ());passRequest (request, response);
  }
 }
Step 2:
Define the servlet as a globally scoped Nucleus component
Step 3:
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 DynamoServlet as follows:
      insertAfterServlet=/atg/dynamo/servlet/dafpipeline/DynamoServlet
Step 4:
Add the servlet’s path to the initialServices property of  /atg/dynamo/servlet/Initial:initialServices+=/URIPrinter 

ATG Commerce Purchase flow diagram

The basic checkout process allow a customer to send an order to single location using a single credit card as from of payment.
When an order is created,it has by default one shipping group and one payment group: atg.commerce.order.HardgoodShippingGroup and atg.commerce.order.CreditCart.If these are the only two group that exist when a user check out,then relationship object are created between the commerce Items in order and these groups.one important to understand the concept of the relationship althought they are usually hidden from the commerce user.   



Design Pattern - Singleton

Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine. The single class must provide a global access point to get the instance of the class. Singleton pattern is used for logging, driver object, and caching and thread pool. Singleton pattern is also used in other design pattern like as Abstract Factory and Facade.
 In Singleton, we have different approaches but all of them have same common concept.
  1. Private constructor to restrict instantiation of the class from other classes.
  2. Private static variable of the same class that is only instance of the class.
  3. Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class. 



 Different approaches of singleton pattern:
  1. Static block initialization
  2. Lazy initialization
  3. Thread Safe Singleton
  4. Serialization and singletone.
In Static block initialization ,the instance of Singleton class  is created  at the time of class loading  and that instance of class is created in the static block that provide option for exception handling.
Example :
Singleton Patter Example
This is not best practice to use, so in further section we will see how to create singleton class that supports lazy initialization.

In Lazy initialization, method to implement Singleton pattern create a instance in global access method, see in below example:
Lazy Initialized

In above the example is suitable for single threaded environment ,but when it comes to multi-threaded environment , it can cause issues if multiple threads are inside the if loop at the same time, it will be destroy the singleton pattern and both thread will get different instance of the singleton class. In next example. We will see different ways to create at thread-safe singleton class.  

In thread Safe Singleton, this is easier way to create a thread safe singleton class  is to make the global access method Synchronized so that only one thread can be execute this method at a time, See in below example.
Thread Safe

Above the example is thread- safe but it reduce the performance because of synchronized method, So that ,if the synchronized block is used inside the if condition with additional check to ensure that only one instance of the singleton class create.

public static ThreadSafeSingleton getInstanceUsingDoubleLocking(){
    if(instance == null){
        synchronized (ThreadSafeSingleton.class) {
            if(instance == null){
                instance = new ThreadSafeSingleton();
            }
        }
    }
    return instance;
}

In Serialization and Singleton, sometime in distributed system, we needed to implement serializable interface in Single class so that we can store it’s state in file system and retrieve it at later point to time.Here is a sample single class that implements serializable interface also.
Serialized Singleton