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



Design Pattern -Factory

In Modern programming language the factory design pattern is probable the mostly used in differnt varient and implementations.This type of design pattern come under creational pattern as this pattern provides one of best ways to create an object.
Factory design pattern is used when we have a super class with multiople sub-classes and based on input ,we need to return one of the sub-class.Factory design pattern takeout the responsibility of instantiation of a class from client program to the factory class.
We can apply Singleton on factory class or make the factory method static ,see in bellow example.


Design Pattern