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


SpringBoot Application Event Listeners

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