Tuesday, September 10, 2013

Desing Patterns

Design patterns are solutions to general problems that software developers faced during software development. Design patterns are primarily based on the following principles of object orientated design
  1. Program to an interface not an implementation
  2. Favor object composition over inheritance.
Design patterns are of following categories:-
  1. Creational Patterns:- These design patterns provides way to create objects while hiding the creation logic and instantiating objects directly using new operator
    • Factory pattern   
      public
      interface Shape { void draw(); }
      public class Rectangle implements Shape {
         @Override
         public void draw() {
            System.out.println("Inside Rectangle::draw() method.");
         }
      }
      public class Square implements Shape {
         @Override
         public void draw() {
            System.out.println("Inside Square::draw() method.");
         }
      }
      public class Circle implements Shape {
         @Override
         public void draw() {
            System.out.println("Inside Circle::draw() method.");
         }
      }

      public
      class ShapeFactory { //use getShape method to get object of type shape
      public
      Shape getShape(String shapeType){ if(shapeType == null){ return null; } if(shapeType.equalsIgnoreCase("CIRCLE")){ return new Circle(); } else if(shapeType.equalsIgnoreCase("RECTANGLE")){ return new Rectangle(); } else if(shapeType.equalsIgnoreCase("SQUARE")){ return new Square(); } return null; } }
      
      
      public class FactoryPatternDemo {
         public static void main(String[] args) {
            ShapeFactory shapeFactory = new ShapeFactory();
            //get an object of Circle and call its draw method.
            Shape shape1 = shapeFactory.getShape("CIRCLE");
            //call draw method of Circle
            shape1.draw();
            //get an object of Rectangle and call its draw method.
            Shape shape2 = shapeFactory.getShape("RECTANGLE");
            //call draw method of Rectangle
            shape2.draw();
            //get an object of Square and call its draw method.
            Shape shape3 = shapeFactory.getShape("SQUARE");
            //call draw method of circle
            shape3.draw();
         }
      }
    •  Abstract Factory patterns It works as a super-factory which creates other factories
      public interface Shape { void draw(); }
      public class Rectangle implements Shape {
         @Override
         public void draw() {
            System.out.println("Inside Rectangle::draw() method.");
         }
      }
      public class Square implements Shape {
         @Override
         public void draw() {
            System.out.println("Inside Square::draw() method.");
         }
      }
      public class Circle implements Shape {
         @Override
         public void draw() {
            System.out.println("Inside Circle::draw() method.");
         }
      }
      
      public class ShapeFactory {
         //use getShape method to get object of type shape 
         public Shape getShape(String shapeType){
            if(shapeType == null){
               return null;
            }  
            if(shapeType.equalsIgnoreCase("CIRCLE")){
               return new Circle();
            } else if(shapeType.equalsIgnoreCase("RECTANGLE")){
               return new Rectangle();
            } else if(shapeType.equalsIgnoreCase("SQUARE")){
               return new Square();
            }
            return null;
         }
      }
      public class FactoryPatternDemo {
         public static void main(String[] args) {
            ShapeFactory shapeFactory = new ShapeFactory();
            //get an object of Circle and call its draw method.
            Shape shape1 = shapeFactory.getShape("CIRCLE");
            //call draw method of Circle
            shape1.draw();
            //get an object of Rectangle and call its draw method.
            Shape shape2 = shapeFactory.getShape("RECTANGLE");
            //call draw method of Rectangle
            shape2.draw();
            //get an object of Square and call its draw method.
            Shape shape3 = shapeFactory.getShape("SQUARE");
            //call draw method of circle
            shape3.draw();
         }
      }
      public interface Color {
         void fill();
      }
      public class Red implements Color {
         @Override
         public void fill() {
            System.out.println("Inside Red::fill() method.");
         }
      }
      public class Green implements Color {
         @Override
         public void fill() {
            System.out.println("Inside Green::fill() method.");
         }
      }
      public class Blue implements Color {
         @Override
         public void fill() {
            System.out.println("Inside Blue::fill() method.");
         }
      }
      public abstract class AbstractFactory {
         abstract Color getColor(String color);
         abstract Shape getShape(String shape);
      }
      public class ShapeFactory extends AbstractFactory { 
         @Override
         public Shape getShape(String shapeType){
            if(shapeType == null){
               return null;
            }  
            if(shapeType.equalsIgnoreCase("CIRCLE")){
               return new Circle();
            } else if(shapeType.equalsIgnoreCase("RECTANGLE")){
               return new Rectangle();
            } else if(shapeType.equalsIgnoreCase("SQUARE")){
               return new Square();
            }
            return null;
         }
         @Override
         Color getColor(String color) {
            return null;
         }
      }
      public class ColorFactory extends AbstractFactory { 
         @Override
         public Shape getShape(String shapeType){
            return null;
         } 
         @Override
         Color getColor(String color) {
            if(color == null){
               return null;
            }  
            if(color.equalsIgnoreCase("RED")){
               return new Red();
            } else if(color.equalsIgnoreCase("GREEN")){
               return new Green();
            } else if(color.equalsIgnoreCase("BLUE")){
               return new Blue();
            }
            return null;
         }
      }
      public class FactoryProducer {
         public static AbstractFactory getFactory(String choice){
            if(choice.equalsIgnoreCase("SHAPE")){
               return new ShapeFactory();
            } else if(choice.equalsIgnoreCase("COLOR")){
               return new ColorFactory();
            }
            return null;
         }
      }
      public class AbstractFactoryPatternDemo {
         public static void main(String[] args) {
            //get shape factory
            AbstractFactory shapeFactory = FactoryProducer.getFactory("SHAPE");
            //get an object of Shape Circle
            Shape shape1 = shapeFactory.getShape("CIRCLE");
            //call draw method of Shape Circle
            shape1.draw();
            //get an object of Shape Rectangle
            Shape shape2 = shapeFactory.getShape("RECTANGLE");
            //call draw method of Shape Rectangle
            shape2.draw();
            //get an object of Shape Square 
            Shape shape3 = shapeFactory.getShape("SQUARE");
            //call draw method of Shape Square
            shape3.draw();
            //get color factory
            AbstractFactory colorFactory = FactoryProducer.getFactory("COLOR");
            //get an object of Color Red
            Color color1 = colorFactory.getColor("RED");
            //call fill method of Red
            color1.fill();
            //get an object of Color Green
            Color color2 = colorFactory.getColor("Green");
            //call fill method of Green
            color2.fill();
            //get an object of Color Blue
            Color color3 = colorFactory.getColor("BLUE");
            //call fill method of Color Blue
            color3.fill();
         }
      } 
    •  Singleton pattern:- This pattern involves a single class which is responsible to creates own object while making sure that only single object get created.
      • Eager Initialization:- This is a design pattern where an instance of a class is created much before it is actually required.
        public class EagerSingleton {
            private static volatile EagerSingleton instance = new EagerSingleton();
            private EagerSingleton() {
            }
        public static EagerSingleton getInstance() {
            return instance;
            }
        }
      • LazyInitialization:- it restricts the creation of instance until requested first time.
        public final class LazySingleton {
            private static volatile LazySingleton instance = null;
            private LazySingleton() {
            }

            public static LazySingleton getInstance() {
                if (instance == null) {
                    synchronized (LazySingleton.class) {
                    instance = new LazySingleton();
                }
            }
            return instance;
            }
        }
      •  Double Checked Locking:- (see instance == null used twice)
        public final class LazySingleton {
            private static volatile LazySingleton instance = null;
            private LazySingleton() {
            }
            public static LazySingleton getInstance() {
                if (instance == null) {
                    synchronized (LazySingleton.class) {
                    if (instance == null) {
                        instance = new LazySingleton();
                    }
                }
            }
            return instance;
            }
        }
      • Static block initialization:-It makes use of the fact that static blocks are executed during the loading of class and even before the constructor is called.
        public class StaticBlockSingleton {
            private static final StaticBlockSingleton INSTANCE;
            static {
                try {
                    INSTANCE = new StaticBlockSingleton();
                } catch (Exception e) {
                    throw new RuntimeException("Uffff, i was not expecting this!", e);
                }
            }
            public static StaticBlockSingleton getInstance() {
                return INSTANCE;
            }
            private StaticBlockSingleton() {
            }
        }
      • Bill Pugh Solution:-The LazyHolder class will not be initialized until required and you can still use other static members
        public class BillPughSingleton {
            private BillPughSingleton() {
            }
            private static class LazyHolder {
                private static final BillPughSingleton INSTANCE = new BillPughSingleton();
            }
            public static BillPughSingleton getInstance() {
                return LazyHolder.INSTANCE;
            }
        }
    •  Builder pattern:- It builds a complex object using simple object.
      public interface Item {
         public String name();
         public Packing packing();
         public float price();   
      }
      public interface Packing {
         public String pack();
      }
      public class Wrapper implements Packing {
         @Override
         public String pack() {
            return "Wrapper";
         }
      }
      public class Bottle implements Packing {
         @Override
         public String pack() {
            return "Bottle";
         }
      }
      public abstract class Burger implements Item {
         @Override
         public Packing packing() {
            return new Wrapper();
         }
         @Override
         public abstract float price();
      }
      public abstract class ColdDrink implements Item {
          @Override
          public Packing packing() {
                    return new Bottle();
          }
          @Override
          public abstract float price();
      }
      public class VegBurger extends Burger {
         @Override
         public float price() {
            return 25.0f;
         }
         @Override
         public String name() {
            return "Veg Burger";
         }
      }
      public class ChickenBurger extends Burger {
         @Override
         public float price() {
            return 50.5f;
         }
         @Override
         public String name() {
            return "Chicken Burger";
         }
      }
      public class Coke extends ColdDrink {
         @Override
         public float price() {
            return 30.0f;
         }
         @Override
         public String name() {
            return "Coke";
         }
      }
      public class Pepsi extends ColdDrink {
         @Override
         public float price() {
            return 35.0f;
         }
         @Override
         public String name() {
            return "Pepsi";
         }
      }
      import java.util.ArrayList;
      import java.util.List;

      public class Meal {
         private List<Item> items = new ArrayList<Item>();   
         public void addItem(Item item){
            items.add(item);
         }
         public float getCost(){
            float cost = 0.0f;
            for (Item item : items) {
               cost += item.price();
            }       
            return cost;
         }
         public void showItems(){
            for (Item item : items) {
               System.out.print("Item : "+item.name());
               System.out.print(", Packing : "+item.packing().pack());
               System.out.println(", Price : "+item.price());
            }       
         }   
      }
      public class MealBuilder {
         public Meal prepareVegMeal (){
            Meal meal = new Meal();
            meal.addItem(new VegBurger());
            meal.addItem(new Coke());
            return meal;
         }  
         public Meal prepareNonVegMeal (){
            Meal meal = new Meal();
            meal.addItem(new ChickenBurger());
            meal.addItem(new Pepsi());
            return meal;
         }
      }
      public class BuilderPatternDemo {
         public static void main(String[] args) {
            MealBuilder mealBuilder = new MealBuilder();
            Meal vegMeal = mealBuilder.prepareVegMeal();
            System.out.println("Veg Meal");
            vegMeal.showItems();
            System.out.println("Total Cost: " +vegMeal.getCost());
            Meal nonVegMeal = mealBuilder.prepareNonVegMeal();
            System.out.println("\n\nNon-Veg Meal");
            nonVegMeal.showItems();
            System.out.println("Total Cost: " +nonVegMeal.getCost());
         }
      }
    • Prototype pattern:- It refers to creating duplicate object while keeping performance in mind.
  2. Structural Patterns:- These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities.
  3. Behavioral Patterns

Springs

Dependency Injection :- Adding dependency at run time using setters or constructors using IOC

OOP :- Unit of modularity is CLASS

AOP :- Unit of modularity is ASPECT

ASPECTS and CROSS CUTTING CONCERNS:- These are the functions that are used at different points in an application like logging, declarative transactions, security, and caching etc.

Dependency Injection :- It is used to decouple an application objects from each other.

AOP :- It is used to decouple aspects from the objects they are affecting.

Springs Framework:- It consists of around 20 modules
  1. Core Container:-
    1. The Core module provides the fundamental parts of the framework, including the IoC and Dependency Injection features.
    2. The Bean module provides BeanFactory which is a sophisticated implementation of the factory pattern.
    3. The Context module builds on the solid base provided by the Core and Beans modules and it is a medium to access any objects defined and configured. The ApplicationContext interface is the focal point of the Context module.
    4. The Expression Language module provides a powerful expression language for querying and manipulating an object graph at runtime.
  2.  Data Access/Integration:-
    1. The JDBC module provides a JDBC-abstraction layer that removes the need to do tedious JDBC related coding.
    2. The ORM module provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis.
    3. The OXM module provides an abstraction layer that supports Object/XML mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream.
    4. The Java Messaging Service JMS module contains features for producing and consuming messages.
    5. The Transaction module supports programmatic and declarative transaction management for classes that implement special interfaces and for all your POJOs. 
  3. Web:-
    1.  The Web module provides basic web-oriented integration features such as multipart file-upload functionality and the initialization of the IoC container using servlet listeners and a web-oriented application context.
    2. The Web-Servlet module contains Spring's model-view-controller (MVC) implementation for web applications.
    3. The Web-Struts module contains the support classes for integrating a classic Struts web tier within a Spring application.
    4. The Web-Portlet module provides the MVC implementation to be used in a portlet environment and mirrors the functionality of Web-Servlet module.
  4. Miscellaneous:-
    1. The AOP module provides aspect-oriented programming implementation allowing you to define method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated.
    2.  The Aspects module provides integration with AspectJ which is again a powerful and mature aspect oriented programming (AOP) framework.
    3. The Instrumentation module provides class instrumentation support and class loader implementations to be used in certain application servers.
    4. The Test module supports the testing of Spring components with JUnit or TestNG frameworks.
Spring provides following two distinct types of containers.
  1. Spring BeanFactory Container
  2.  Spring ApplicationContext Container
The ApplicationContext container includes all functionality of the BeanFactory container, so it is generally recommended over the BeanFactory.  

Spring Configuration:-
There are following three important methods to provide configuration metadata to the Spring Container:
  1. XML based configuration file.
  2. Annotation-based configuration
  3. Java-based configuration 
XML based configuration file:-

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd" default-init-method="DEFAULT_INIT_METHOD" default-destroy-method="DEFAULT_DESTROY_METHOD">
<!-- A simple bean definition -->
    <bean id="BEAN_NAME" class="CLASS_NAME" scope="SCOPE" init-method = "METHOD_AT_BEAN_INITIALIZATION" destroy-method = "METHOD_AT_BEAN_DESTRUCTION" parent="PARENT_BEAN_ID" abstract = "ABSTRACT_TRUE_FALSE"
>
<constructor-arg ref="ARGUMENT_FIRST"/>
<constructor-arg ref="ARGUMENT_SECOND"/>
       <!-- collaborators and configuration for this bean go here -->
    </bean>
</bean>


  1. DEFAULT_INIT_METHOD:- It is used to call the init method in case all the beans have init method of same name.
  2. DEFAULT_DESTROY_METHOD:-It is used to call the destroy method in case all the beans have destroy method of same name.
  3. BEAN_NAME:- It is the unique name used to identify the bean.
  4. CLASS_NAME; It is the POJO class that will be used to instantiate the bean variables and methods.
  5. SCOPE:- It is used to define the scope of the bean. The valid values are:-
    1. singleton:- This scopes the bean definition to a single instance per Spring IoC container (default).
    2. prototype:- To force Spring to produce a new bean instance each time one is needed, you should declare the bean's scope attribute to be prototype.
    3. request:- This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
    4. session:- This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
    5. global-session:- This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
  6. METHOD_AT_BEAN_INITIALIZATION:- The name of method to be called during bean initialization.
  7. METHOD_AT_BEAN_DESTRUCTION:- The name of method to be called during bean destruction. Destroy method is not called for beans of scope prototype. This is because the context doesn't keep track of the prototype scope objects (if it does, it will cause a memory leak as spring doesn't know when to dispose it). 
  8. PARENT_BEAN_ID:- It is used to inherit the properties from some other bean.
  9. ABSTRACT_TRUE_FALSE:- abstract can be set to true if we want to create a bean definition template for bean inheritance explained below. It is false by default. The class attribute should not be given in case abstract is set to true i.e. if bean template is being created. 
BeanPostProcessor:- Its is an interface that is used to provide own instantiation logic before or after bean initialization. The class is mapped in config file.

Bean Definition Inheritance:-We can define a bean in config file and this bean definition can be inherited by other beans as shown below.

Dependency Injection:-
Consider you have an application which has a text editor component and you want to provide spell checking. Your standard code would look something like this:
 
public class TextEditor {
   private SpellChecker spellChecker;
   public TextEditor() {
      spellChecker = new SpellChecker();
   }
}
 
What we've done here is create a dependency between the TextEditor and the SpellChecker.

Now consider the code as 
 
public class TextEditor {
   private SpellChecker spellChecker;
   public TextEditor(SpellChecker spellChecker) {
      this.spellChecker = spellChecker;
   }
}
 
Here TextEditor should not worry about SpellChecker implementation. The SpellChecker will be implemented independently and will be provided to TextEditor at the time of TextEditor instantiation and this entire procedure is controlled by the Spring Framework.
Here, we have removed the total control from TextEditor and kept it somewhere else (ie. XML configuration file) and the dependency ( ie. class SpellChecker) is being injected into the class TextEditor through a Class Constructor. Thus flow of control has been "inverted" by Dependency Injection (DI) because you have effectively delegated dependances to some external system.

Second method of injecting dependency is through Setter Methods of TextEditor class where we will create SpellChecker instance and this instance will be used to call setter methods to initialize TextEditor's properties.

So there are two ways in which Dependency can be injected
  1. Via constructor
    1.  
  2. Via setter methods
Benefits of using Springs framework:-
  1.  Very loose coupling between objects.
  2. POJO based so not forced in any way to implement unwanted methods.
  3.  

Minimum Jars required for Struts, Springs, Hibernate to work :-
Controller org.springframework.context
RequestMapping org.springframework.web
RequestMethod org.springframework.web
ModelMap org.springframework.context
DispatcherServlet                                                                org.springframework.web.servlet
BeansException                                                                  org.springframework.beans
NestedRuntimeException                                                    org.springframework.core
LogFactory                                                                        commons-logging
ClassVisitor                                                                       org.springframework.asm
PropertyAccessor                                                                org.springframework.expression

javax.servlet.jsp.jstl.core.Config                     javax.servlet.jsp.jstl
org.apache.commons.dbcp.BasicDataSource                          commons-dbcp
org.apache.commons.pool.impl.GenericObjectPool         commons-pool.jar
JdbcTemplate                                           org.springframework.jdbc
org.springframework.dao.DataAccessException            springs-dao.jar


Saturday, September 22, 2012

Dependable drop downs in Struts 2 using database


 JSP PAGE IS :-


<%@ include file="../others/includes.jsp"%>
<script type="text/javascript">
function populateCountries(){
    var selectedRegion = $('#register_region').val();
    $("#register_country").empty().append('<option value="0">Select your country</option');
    $("#register_state").empty().append('<option value="0">Select your state</option');
    $("#register_city").empty().append('<option value="0">Select your city</option');
    $.ajax({
        url: "../views/getCountries",
        type: "POST",
        async: true,
        data: {regionId: selectedRegion},
        cache: false,
        dataType: "json",
        success: function(result){
            if (result.length == 0){
                $('#register_country').append('<option value="0">No data found</option>');
            }
            else{
                for (var key in result) {
                    $('#register_country').append('<option value="'+result[key].countryId+'">'+result[key].countryName+'</option>');
                 }
            }
        },
        error: function(xhr, ajaxOptions, thrownError){
            alert("An error occured: " + thrownError  +" "+ajaxOptions+" "+xhr.status + " " + xhr.statusText);
        }
    });  
}
function populateStates(){
    var selectedCountry = $('#register_country').val();
    $("#register_state").empty().append('<option value="0">Select your state</option');
    $("#register_city").empty().append('<option value="0">Select your city</option');
    $.ajax({
        url: "../views/getStates",
        type: "POST",
        async: true,
        data: {countryId: selectedCountry},
        cache: false,
        dataType: "json",
        success: function(result){
            if (result.length == 0){
                $('#register_state').append('<option value="0">No data found</option>');
            }
            else{
                for (var key in result) {
                    $('#register_state').append('<option value="'+result[key].stateId+'">'+result[key].stateName+'</option>');
                 }
            }
        },
        error: function(xhr){
            alert("An error occured: " + xhr.status + " " + xhr.statusText);
        }
    });  
}

function populateCities(){
    var selectedState = $('#register_state').val();
    $("#register_city").empty().append('<option value="0">Select your city</option');
    $.ajax({
        url: "../views/getCities",
        type: "POST",
        async: true,
        data: {stateId: selectedState},
        cache: false,
        dataType: "json",
        success: function(result){
            if (result.length == 0){
                $('#register_city').append('<option value="0">No data found</option>');
            }
            else{
                for (var key in result) {
                    $('#register_city').append('<option value="'+result[key].cityId+'">'+result[key].cityName+'</option>');
                 }
            }
        },
        error: function(xhr){
            alert("An error occured: " + xhr.status + " " + xhr.statusText);
        }
    });      
}
</script>
<body id="main" onload="document.formname.reset();">
<s:form action="getRegions" name="formname">
<s:select cssStyle="WIDTH:300px"  list="region" listKey="regionId" listValue="regionName" label="Select your region" headerKey="0" headerValue="Select your region" name="register_region" id="register_region" onchange="populateCountries();"></s:select>
<s:select cssStyle="WIDTH:300px" list="country" listKey="countryId" listValue="countryName" label="Select your country" headerKey="0" headerValue="Select your country" name="register_country" id="register_country" onchange="populateStates();" ></s:select>
<s:select cssStyle="WIDTH:300px" list="state" listKey="stateId" listValue="stateName" label="Select your state" headerKey="0" headerValue="Select your state" name="register_state" id="register_state" onchange="populateCities();"></s:select>
<s:select cssStyle="WIDTH:300px" list="city" listKey="cityId" listValue="cityName" label="Select your city" headerKey="0" headerValue="Select your city" name="register_city" id="register_city" onchange=""></s:select>

</s:form>
</body>


ACTION CLASS IS :-

package com.aih.projects.actions.sd;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import net.sf.json.JSONArray;

import com.aih.projects.beans.City;
import com.aih.projects.beans.Country;
import com.aih.projects.beans.Region;
import com.aih.projects.beans.State;
import com.aih.projects.beans.sd.Food;
import com.aih.projects.commons.sd.Constants;
import com.aih.projects.commons.sd.Parent;
import com.aih.projects.dao.sd.DBInteractionForFood;
import com.aih.projects.dao.sd.DBInteractionForMember;
import com.aih.projects.dao.sd.DBInteractionForWorldLocations;
import com.aih.projects.utility.SendEmail;
import com.aih.projects.utility.UtilityFunctions;

public class DatabaseAction extends Parent implements SessionAware{   
    private static final long serialVersionUID = 1L;
    private JSONArray jArray;
    private String dbHitCounter;
    private String noOfRecords;
    private String email;
    private String password;
    private String zip;
    private InputStream inputStream;
    private Map<String, Object> session;
    private String text;
    private ArrayList<Region> region;
    private ArrayList<Country> country;
    private ArrayList<State> state;
    private ArrayList<City> city;
    private String regionId;
    private String countryId;
    private String stateId;
    private String cityId;
   
    private JSONArray jArrayRegions;
    private JSONArray jArrayCountries;
    private JSONArray jArrayStates;
    private JSONArray jArrayCities;
   


    public JSONArray getJArrayRegions() {
        return jArrayRegions;
    }

    public void setJArrayRegions(JSONArray arrayRegions) {
        jArrayRegions = arrayRegions;
    }

    public JSONArray getJArrayCountries() {
        return jArrayCountries;
    }

    public void setJArrayCountries(JSONArray arrayCountries) {
        jArrayCountries = arrayCountries;
    }

    public JSONArray getJArrayStates() {
        return jArrayStates;
    }

    public void setJArrayStates(JSONArray arrayStates) {
        jArrayStates = arrayStates;
    }

    public JSONArray getJArrayCities() {
        return jArrayCities;
    }

    public void setJArrayCities(JSONArray arrayCities) {
        jArrayCities = arrayCities;
    }

    public String getCountryId() {
        return countryId;
    }

    public void setCountryId(String countryId) {
        this.countryId = countryId;
    }

    public String getStateId() {
        return stateId;
    }

    public void setStateId(String stateId) {
        this.stateId = stateId;
    }

    public String getCityId() {
        return cityId;
    }

    public void setCityId(String cityId) {
        this.cityId = cityId;
    }

    public String getRegionId() {
        return regionId;
    }

    public void setRegionId(String regionId) {
        this.regionId = regionId;
    }

    public ArrayList<Region> getRegion() {
        return region;
    }

    public void setRegion(ArrayList<Region> region) {
        System.out.println("Here");
        this.region = region;
    }

    public ArrayList<Country> getCountry() {
        return country;
    }

    public void setCountry(ArrayList<Country> country) {
        this.country = country;
    }

    public ArrayList<State> getState() {
        return state;
    }

    public void setState(ArrayList<State> state) {
        this.state = state;
    }

    public ArrayList<City> getCity() {
        return city;
    }

    public void setCity(ArrayList<City> city) {
        this.city = city;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Map<String, Object> getSession() {
        return session;
    }

    public void setSession(Map<String, Object> session) {
        this.session = session;
    }
   
    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getZip() {
        return zip;
    }

    public void setZip(String zip) {
        this.zip = zip;
    }

    public void setJArray(JSONArray jArray) {
        this.jArray = jArray;
    }

    public JSONArray getJArray() {
        return jArray;
    }
    public String getNoOfRecords() {
        return noOfRecords;
    }

    public void setNoOfRecords(String noOfRecords) {
        this.noOfRecords = noOfRecords;
    }
   
    public String getDbHitCounter() {
        return dbHitCounter;
    }

    public void setDbHitCounter(String dbHitCounter) {
        this.dbHitCounter = dbHitCounter;
    }

    public String populateFoods(){
        ArrayList<Food> foods = null;
        String dbQuery = null;
        try{
            foods = DBInteractionForFood.getAllAvailableFoods(Integer.parseInt(dbHitCounter), Integer.parseInt(noOfRecords));
        }catch (Exception e) {
            e.printStackTrace();
            SendEmail.postMail(new String[]{Constants.errorMail}  , "Error from "+Constants.projectName, "Query is "+dbQuery+"  and Method name is "+Thread.currentThread().getStackTrace()[2].getMethodName()+"\n\n\nError is" +UtilityFunctions.stackTraceToString(e));
        }
        jArray = UtilityFunctions.getListAsJsonArray(foods);
        //System.out.println(jArray);
        return SUCCESS;
    }
   
    public String registerMember(){
        inputStream = DBInteractionForMember.registerMember(email, password, zip);
        return SUCCESS;
    }
   
    public String logIn(){
        inputStream  = DBInteractionForMember.logIn(email, password);
        session.put("anshul", inputStream);
        return SUCCESS;
    }
   
    public String activateMember(){
        inputStream = DBInteractionForMember.activateMember(email);
        return SUCCESS;
    }
   
    public String getRegions(){
        region =  DBInteractionForWorldLocations.getRegions();
        country =  DBInteractionForWorldLocations.getCountries("0");
        state = DBInteractionForWorldLocations.getStates("0");
        city = DBInteractionForWorldLocations.getCities("0");
        jArrayRegions = UtilityFunctions.getListAsJsonArray(region);
        return SUCCESS;
    }
   
    public String getCountries(){
        country =  DBInteractionForWorldLocations.getCountries(regionId);
        jArrayCountries = UtilityFunctions.getListAsJsonArray(country);
        return SUCCESS;
    }
   
    public String getStates(){
        state = DBInteractionForWorldLocations.getStates(countryId);
        jArrayStates = UtilityFunctions.getListAsJsonArray(state);
        return SUCCESS;
    }
   
    public String getCities(){
        city = DBInteractionForWorldLocations.getCities(stateId);
        jArrayCities = UtilityFunctions.getListAsJsonArray(city);
       
        return SUCCESS;
    }
   
    public static void main(String args[]){
        DatabaseAction a = new DatabaseAction();
        System.out.println(a.getRegions());
    }

}


STRUTS.XML is:-

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <package name="test" namespace="/views" extends="struts-default, json-default">
           <action name="getRegions" class="com.aih.projects.actions.sd.DatabaseAction" method="getRegions">
            <result name="SUCCESS">test1.jsp</result>
           </action>
           <action name="getCountries" class="com.aih.projects.actions.sd.DatabaseAction" method="getCountries">
            <result type="json" name= "SUCCESS"><param name="root">jArrayCountries</param></result>
           </action>
           <action name="getStates" class="com.aih.projects.actions.sd.DatabaseAction" method="getStates">
            <result type="json" name= "SUCCESS"><param name="root">jArrayStates</param></result>
           </action>
           <action name="getCities" class="com.aih.projects.actions.sd.DatabaseAction" method="getCities">
            <result type="json" name= "SUCCESS"><param name="root">jArrayCities</param></result>
           </action>
    </package>

</struts>

Tuesday, August 14, 2012

LOG4J

1. Log4j simply inserts a log statement in the application code and manage them externally without going back to its application source code.
2. Programmer's can control the logging message with the help of external configuration file e.g. log4.xml or log4j.properties file.
3. The external properties file can be used to set the log format as well as the level of logging.
4. Three main component of Log4J are :-
        Logger
        Appender
        Layout
5. LOGGER:- It is responsible for capturing the logging information.
   There are few levels of logger:
        DEBUG : Most useful to debug an application.
        INFO  : It provides informational messages.
        WARN  : It provides that application may have harmful events.
        ERROR : It provides that application having error events but that might allow it to continue running.
        FATAL : It denotes the severe error events which lead the application to abort.
        ALL   : It is intended to turn on all logging.
        OFF   : It is intended to turn off all logging.
6. APPENDERS:- It is responsible for publishing the log to a destination. It controls how the logging provides the output.
   There are few list of appenders listed below:
        ConsoleAppender
        DailyRollingFileAppender
        FileAppender
        RollingFileAppender
        WriterAppender
        SMTPAppender
        SocketAppender
        SocketHubAppender
        SyslogAppendersends
        TelnetAppender
7. LAYOUT:- It is responsible for formatting the log output in different layouts. User can control the output format by modifying the Log4J configuration file.
   There are basically three types of Layout:
        HTMLLayout : It formats the output in the HTML table
        PatternLayout : It formats the output in the conversion pattern
        SimpleLayout : It formats the output in a simple manner, it prints the level then place a dash and then the user specified log message.
8. CONFIGURING LOG4J:- Put log4j.properties and log4j.xml in classpath i.e. directly under src folder of the application.
    Log4j looks for log4j.xml file first and then go for log4j.properties hence you must place both the files in your folder. We use log4j.xml since properties file does not provide some advanced configuration options such as Filter, some of ErrorHandlers, and few advanced Appenders.
  


STORED PROCEDURES IN MYSQL

http://www.mysqltutorial.org/mysql-stored-procedure-tutorial.aspx

A stored procedure is a segment of declarative SQL code, which is stored in the database catalog. A stored procedure can be invoked by a program, a trigger or even another stored procedure.

Declarative programming is where you say what you want without having to say how to do it. With procedural programming, you have to specify exact steps to get the result.

ADVANTAGES:-
    Stored procedure increases performance of application. Once created, stored procedure is compiled and stored in the database catalog. It runs faster than uncompiled SQL commands which are sent from application.
    Stored procedure reduces the traffic between application and database server because instead of sending multiple uncompiled lengthy SQL commands statements, the application only has to send the stored procedure's name and get the data back.
    Stored procedure is reusable and transparent to any application which wants to use it. Stored procedure exposes the database interface to all applications so developers don't have to program the functions which are already supported in stored procedure in all external applications.
    Stored procedure is secured. Database administrator can grant the access right to application which wants to access stored procedures in database catalog without granting any permission on the underlying database tables.

SIMPLE STORED PROCEDURE:-
    CREATE PROCEDURE getALL()
    BEGIN
    select * from update_commands;
    END//
    DELIMITER ;

PARAMETERS IN STORED PROCEDURES:-
    In MySQL, a parameter has one of three modes IN, OUT and INOUT.
   
IN :-
    send an input parameter only

    DELIMITER //
    CREATE PROCEDURE getAll(IN commandName varchar(50))
    BEGIN
    select * from update_commands where command_name = commandName;
    END//
    DELIMITER;
   
    call getAll('send_me')
   
OUT:-

    send an input parameter AND get back another output parameter.
   
    DELIMITER //
    CREATE PROCEDURE getAll(IN commandName varchar(50), OUT total int)
    BEGIN
    select count(*) into total from update_commands where command_name like orderStatus ;
    END//
    DELIMITER;

    call getAll(1,@set);
    select @set as total


INOUT:-

    send an input parameter AND get back the same as output parameter after modification.
   
    DELIMITER //
    CREATE PROCEDURE getAll(INOUT a varchar(50))
    BEGIN
    select password into a from login where username = a;
    END//
    DELIMITER ;
   
    set @username = 'a';
    call getAll(@username);
    select @username as passsword
   
DECLARING A VARIABLE:-

    DECLARE variable_name datatype(size) DEFAULT default_value;
    e.g. DECLARE total_sale INT DEFAULT 0

VARIABLE SCOPE:-

    A variable has its own scope. If you declare a variable inside a stored procedure, it will be out of scope when the END of stored procedure reached. If you defined a variable inside block BEGIN/END inside a stored procedure it will be out of scope if the END reached. You can declare two variables or more variables with the same name in different scopes; the variable only is effective in its scope.

    A variable with the ‘@’ at the beginning is session variable. It exists until the session end.
   
CONDITIONAL CONTROL:-

    The IF Statement:-
        IF expression THEN commands
            ELSEIF expression THEN commands
            ELSE commands
        END IF;

    The CASE Statement:-
        CASE case_expression
            WHEN when_expression THEN commands
            WHEN when_expression THEN commands
            ELSE commands
        END CASE;
       
    The WHILE Statement:-
        WHILE expression DO
           Statements
        END WHILE
       
    The REPEAT Statement:-
        REPEAT
            Statements; UNTIL expression
        END REPEAT
   
    The LOOP loop, LEAVE and ITERATE Statment:-
       

Saturday, July 21, 2012

JQuery

JQuery

 $.ajax() function parameters are as below:-

async A Boolean value indicating whether the request should be handled asynchronous or not. Default is true
beforeSend(xhr) A function to run before the request is sent
cache A Boolean value indicating whether the browser should cache the requested pages. Default is true
complete(xhr,status) A function to run when the request is finished (after success and error functions).
contentType The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
context Specifies the "this" value for all AJAX related callback functions
data Specifies data to be sent to the server
dataFilter(data,type) A function used to handle the raw response data of the XMLHttpRequest
dataType The data type expected of the server response.
error(xhr,status,error) A function to run if the request fails.
global A Boolean value specifying whether or not to trigger global AJAX event handles for the request. Default is true
ifModified A Boolean value specifying whether a request is only successful if the response has changed since the last request. Default is: false.
jsonp A string overriding the callback function in a jsonp request
jsonpCallback Specifies a name for the callback function in a jsonp request
password Specifies a password to be used in an HTTP access authentication request.
processData A Boolean value specifying whether or not data sent with the request should be transformed into a query string. Default is true
scriptCharset Specifies the charset for the request
success(result,status,xhr) A function to be run when the request succeeds
timeout The local timeout (in milliseconds) for the request
traditional A Boolean value specifying whether or not to use the traditional style of param serialization
type Specifies the type of request. (GET or POST)
url Specifies the URL to send the request to. Default is the current page
username Specifies a username to be used in an HTTP access authentication request
xhr A function used for creating the XMLHttpRequest object

Difference between Struts 1 and Struts 2

Struts1 extends the abstract base class by its action class. The problem with struts1 is that it uses the abstract classes rather than interfaces. 

While in Struts 2, an Action class implements an Action interface, along with other interfaces use optional and custom services. Struts 2 provides a base ActionSupport class that implements commonly used interfaces. Although an Action interface is not necessary, any POJO object along with an execute signature can be used as an Struts 2 Action object. 
                                                      

Friday, July 20, 2012

Scroller in JQuery

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="../../scripts/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
var c;
var data=["A","B","C","D","E","F", "G","H","I", "J","K","L", "M","N","O", "P","Q","R", "S","T","U"];
$(document).ready(function(){
      setInterval("asd(c)",1000);
});

function asd(c){
      if(!asd.c)asd.c = 1;
      for (var i = 1; i <= asd.c ; i++){
            for (var j = i ; j > 0 ; j-- ){
                  $("#div"+j).html(data[i-j]);
            }
      }
      asd.c++;
      if (asd.c > data.length){
            asd.c =1;
            $("#div5").html('');
            $("#div4").html('');
            $("#div3").html('');
            $("#div2").html('');
            $("#div1").html('');
      }
}
</script>
</head>
<body>
<input id ="v" value="1" style="display: none;"/>
<table border="1" cellpadding="1" cellspacing="1">
<tr><td height="30px" width="30px"><div id="div5"></div></td></tr>
<tr><td height="30px" width="30px"> <div id="div4"></div></td></tr>
<tr><td height="30px" width="30px"><div id="div3"></div></td></tr>
<tr><td height="30px" width="30px"><div id="div2"></div></td></tr>
<tr><td height="30px" width="30px"><div id="div1"></div></td></tr>
</table>
</body>
</html>

SpringBoot Application Event Listeners

When a spring boot application starts few events occurs in below order ApplicationStartingEvent ApplicationEnvironmentPreparedEvent Applicat...