Sunday, October 13, 2013

ANT

Apache Ant is a Java based build tool to automate the manual steps used in compiling and deploying a JAVA application

It involves a build file that should be inside the project directory. This build file must have
  • A project element
  • At least one target element

<?xml version="1.0"?> 
 <project name="PROJECT_NAME" default="info" basedir="BASE_DIRECTORY"> 

 <property name="PROPERTY_NAME" value="PROPERTY_VALUE" /> 
 <property file="PROPERTY_FILE_NAME"/>

<patternset id="PATTERN_SET_ID"> 
<include name="PATTERN_OF_FILES_TO_BE_INCLUDED"/>  
<exclude name="PATTERN_OF_FILES_TO_BE_EXCLUDED"/>
 </patternset>


<filelist id="FILELIST_ID" dir="DIRECTORY_OF_FILES"> 
 <file name="FILE_l"/>  
<file name="FILE_2"/> 
 </filelist>
 
 <target name="TARGET_NAME" depends="TARGET_1, TARGET_2, TARGET_3,.." description="TARGET_DESCRIPTION" if="IF_CONDITION" unless="UNLESS_CONDITION"> 

 <echo>Hello World - Welcome to Apache Ant! $(PROPERTY_NAME)</echo> 

<delete>
<fileset dir="${PROPERTY_NAME}" casesensitive="YES_NO">  
<include name="PATTERN_OF_FILES_TO_BE_INCLUDED"/>  
<exclude name="PATTERN_OF_FILES_TO_BE_EXCLUDED"/> 
 </fileset>
 </delete>


<delete>
<fileset dir="DIRECTORY_OF_FILES" casesensitive="yes"> 
 <patternset refid="PATTERN_SET_ID"/> 
 </fileset>
</delete>
 </target>

 <target name="TARGET_NAME">
 <zip destfile="DESTINATION_FILE_NAME" >
 <filelist refid="
FILELIST_ID" />
 </zip>
 </target








   <target name="TARGET_NAME">
   <copy todir="DESTINATION_DIRECTORY">
   <fileset dir="SOURCE_DIRECTORY" includes="FILTER_PATTERN"></fileset>   
   <filterset>
   <filter token="TOKEN" value="REQUIRED_VALUE_OF_TOKEN"></filter>
   </filterset>
   </copy>
   </target>


  </project>

PROJECT_NAME:- is optional and is the name of the project.
PROPERTY_NAME: is optional and is used to set the name for a variable/property.
PROPERTY_VALUE: is optional and is used to set the value for a variable/property.
PROPERTY_FILE_NAME: is optional and is used to set the name for properties file. 
DEFAULT:- is mandatory and is used to set the default target 
BASE_DIRECTORY:- is optional and used to set the base directory for the project.
TARGET_NAME: is madatory and used to set the name of the target.
TARGET_1, TARGET_2, TARGET_3,..; are optional and are comma separated list of targets on which the TARGET_NAME depends.
TARGET_DESCRIPTION:- is optional and is used to describe a target
DIRECTORY_OF_FILES:-It is used to set the directory where the filelist or fileset is to be generated.
PATTERN_OF_FILES_TO_BE_INCLUDED:- It is used to set the pattern of the files to be included in the datatype.
PATTERN_OF_FILES_TO_BE_EXCLUDED:- It is used to set the pattern of the files to be exceluded in the datatype.
PATTERNS can be set as:-
  1. To match one character we can use ?.java which will include files like A.java, B.java but not AB.java
  2. To match or or more charates we can use  *.java which will includes ny file with extension .java
  3. To match zero or more directories recursively we can use ** 
PATTERN_SET_ID:- It can be used to provide a name to a pattern set so that it may be used again and again in build file.
FILELIST_ID:- It can be used to provide a name to a file list so that it may be used again and again in build file.
TOKEN:- It can be string in the file that is surrounded by separators @ e.g. @VERSION@. It is replaced by the value as given in the attribute value of the filter tag.
Predefined properties in ANT:-
  1. ant.file = The full location of the build file.
  2. ant.version = The version of the Apache Ant installation.
  3. basedir = The basedir of the build, as specified in the basedir attribute of the project element.
  4. ant.java.version = The  version of the JDK that is used by Ant.
  5. ant.project.default-target = The default target of the current project
  6. ant.project.invoked-targets = Comma separated list of the targets that were invoked in the current project
  7. ant.core.lib = The full location of the ant jar file
  8. ant.home = The home directory of Ant installation
  9. ant.library.dir = The home directory for Ant library files - typically ANT_HOME/lib folder.
Data Types in ANT:- Data types here mean the services that are provided by ANT by default
  1. FileSet:- It is used to define a collection of files using pattern set or wild cards .
  2. PatternSet :- It is used to create a pattern of files to be used in fileset.
  3. FileList :- It is used to define a collection of files using the explicit names and wild cards can not be used.
  4. FilterSet:-
  5. Path
Note:- Pattern set can be used inside fileset but filelist can not be.

To run a target go to the location of build file in command prompt and type 
ant TARGET_NAME

Features:-
  • It automates the;-
  1. Compilation of code
  2. Packaging of binaries
  3. Deployment to the server
  4. Test the change.
  • It is platform independent.

Wednesday, October 2, 2013

Inheritance in JAVA

Access Specifiers in JAVA

Access Specifiers in JAVA :-


Class Package Subclass in Same Package Subclass in Different Package World
public Y Y Y Y Y
protected Y Y Y Y
default Y Y Y
private Y


Public is accessible everywhere.
Protected can not be assessed in outside the subclasses or the same package.
Default can not be accessed in subclasses in different packages.
Private can be accessed in the class only.

The difference between the protected and default is that the protected can be accessed in subclasses in different class but default can not be.

Example

package com.anshul.projects.iwts.tutor.accessspecifier;

public class MyClass {
    public final static int public_variable= 5;
    protected final static int protected_variable = 5;
    final static int default_variable = 5;
    private final static int private_variable = 5;
  
    public void public_method(){
        System.out.println("public_method");
    }
  
    protected void protected_method(){
        System.out.println("protected_method");
    }
  
    void default_method(){
        System.out.println("default_method");
    }
  
    private void private_method(){
        System.out.println("private_method");
    }


   public static void main (String args[]){
        MyClass mclass = new MyClass();
        System.out.println(mclass.public_variable);
        System.out.println(mclass.protected_variable);
        System.out.println(mclass.default_variable);
        System.out.println(mclass.private_variable);
        mclass.public_method();
        mclass.protected_method();
        mclass.default_method();
        mclass.private_method();
    }
}


package com.anshul.projects.iwts.tutor.accessspecifier;

public class Package {
    public static void main (String args[]){
        MyClass mclass = new MyClass();
        System.out.println(mclass.public_variable);
        System.out.println(mclass.protected_variable);
        System.out.println(mclass.default_variable);
        System.out.println(mclass.private_variable);
        mclass.public_method();
        mclass.protected_method();
        mclass.default_method();
        mclass.private_method();
    }}

package com.anshul.projects.iwts.tutor.accessspecifier;

public class SubClass extends com.anshul.projects.iwts.tutor.accessspecifier.MyClass{
    public static void main (String args[]){
        MyClass mclass = new MyClass();
        System.out.println(mclass.public_variable);
        System.out.println(mclass.protected_variable);
        System.out.println(mclass.default_variable);
        System.out.println(mclass.private_variable);
        mclass.public_method();
        mclass.protected_method();
        mclass.default_method();
        mclass.private_method();
    }}

package com.anshul.projects.iwts.tutor.accessspecifier.subpackage;
import com.anshul.projects.iwts.tutor.accessspecifier.MyClass;

public class OtherPackageSubClass extends MyClass{
    public static void main (String args[]){
        MyClass mclass = new MyClass();
        System.out.println(mclass.public_variable);
        System.out.println(mclass.protected_variable);
        System.out.println(mclass.default_variable);
        System.out.println(mclass.private_variable);
        mclass.public_method();
        mclass.protected_method();
        mclass.default_method();
        mclass.private_method();
    }  }

package com.anshul.projects.iwts.tutor.accessspecifier.subpackage;
import com.anshul.projects.iwts.tutor.accessspecifier.MyClass;

public class World {
    public static void main (String args[]){
        MyClass mclass = new MyClass();
        System.out.println(mclass.public_variable);
        System.out.println(mclass.protected_variable);
        System.out.println(mclass.default_variable);
        System.out.println(mclass.private_variable);
        mclass.public_method();
        mclass.protected_method();
        mclass.default_method();
        mclass.private_method();
    }}

All the red highlighted lines will be giving compile time error "Method" or "Variable" is not visible



Wednesday, September 25, 2013

Exception Handling in JAVA

Custom Exception Example

package com.anshul.aih.projects.iwts.tests;
public class MyCustomException extends Exception{
    String status;
    MyCustomException(String status) {
         this.status=status;
    }
    public String toString(){
        return ("Exception thrown as status is "+status) ;
    }
}

package com.anshul.aih.projects.iwts.tests;
public class MyCustomExceptionDemo {
    public static void main(String args[]){
          String status;     
          status = "Inactive";
          if (status.equalsIgnoreCase("ACTIVE")){
              System.out.println("Active");     
          }
          else if (status.equalsIgnoreCase("INACTIVE")){
              System.out.println("Inactive");
              try {
                    throw new MyCustomException(status);
                } catch (MyCustomException e) {
                    e.printStackTrace();
                }
          }
          else {
              System.out.println("OK");
          }
    }
}

Tuesday, September 24, 2013

Comparator and Comparable Interfaces

Comparable:-
  1. It is inside java.lang package. 
  2. The class whose elements need to be sorted must implement this interface and override the compareTo(Object obj) method.
  3. The sort is done using either Collection.sort(List<T> list) or Arrays.sort(Array[] array)
Example 
package com.arsoft.tests;

public class Student implements Comparable<Student>{ //class is implementing Comparable
    private String name;
    private float marks;
   
    public Student (String name, float marks){
        this.name = name;
        this.marks = marks;
    }
   
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public float getMarks() {
        return marks;
    }
    public void setMarks(float marks) {
        this.marks = marks;
    }
   
    public int compareTo(Student student){ //Method needs to be overridden
        return this.name.compareTo(student.getName());
    }
 
   
}

package com.arsoft.tests;

import java.util.ArrayList;
import java.util.Collections;

public class StudentDemo {
    public static void main(String args[]){
        ArrayList<Student> students =  new ArrayList<Student>();
        Student student = new Student("Abhishek", 95);
        students.add(student);
        student = new Student("Anshul",93);
        students.add(student);
        student = new Student("Akhil",86);
        students.add(student);
        student = new Student("Rajeev",99);
        students.add(student);
        student = new Student("Ruchika", 67);
        students.add(student);
        for(Student st : students) {
            System.out.println(st.getMarks() + " : " + st.getName());
        }
        System.out.println("##################################");
        Collections.sort(students);
        for(Student st : students) {
            System.out.println(st.getMarks() + " : " + st.getName());
        }
       
    }
}


Comparator:-
  1. It is inside java.util package.
  2. The class whose elements need to be sorted must NOT implement this interface instead we can create a separate class implementing this interface and the override the compare(Object obj, Object obj1) method.
  3. The sort is done using either Collection.sort(List<T> list, Comparator comparator) or Arrays.sort(Array[] array, Comparator comparator) 
package com.arsoft.tests;

import java.util.Comparator;

public class NewStudent { //Class is not implementing Comparator
    private String name;
    private float marks;
   
    public NewStudent (String name, float marks){
        this.name = name;
        this.marks = marks;
    }
   
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public float getMarks() {
        return marks;
    }
    public void setMarks(float marks) {
        this.marks = marks;
    }
   
}

package com.arsoft.tests;

import java.util.Comparator;

public class NameComparator implements Comparator<NewStudent>{ //New comparator which //implements comparator is created

    @Override
    public int compare(NewStudent student1, NewStudent student2) { //Method is overridden
        return student1.getName().compareTo(student2.getName());
    }


}




package com.arsoft.tests;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class NameStudentDemo {
    public static void main(String args[]){
        ArrayList<NewStudent> students =  new ArrayList<NewStudent>();
        NewStudent student = new NewStudent("Abhishek", 95);
        students.add(student);
        student = new NewStudent("Anshul",93);
        students.add(student);
        student = new NewStudent("Akhil",86);
        students.add(student);
        student = new NewStudent("Rajeev",99);
        students.add(student);
        student = new NewStudent("Ruchika", 67);
        students.add(student);
        for(NewStudent st : students) {
            System.out.println(st.getMarks() + " : " + st.getName());
        }
        System.out.println("##################################");
        NameComparator nc = new NameComparator();
        Collections.sort(students, nc);
//an object of custom comparator class is being used in sorting
        for(NewStudent st : students) {
            System.out.println(st.getMarks() + " : " + st.getName());
        }
       
    }

}





Tuesday, September 10, 2013

JAVA Keywords

Volatile:- It is a keyword used to indicate Java compiler and thread that do not cache value of this variable and always read it from main memory.

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>

SpringBoot Application Event Listeners

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