Wednesday, 21 December 2016

Spring Framework

What is the difference between Spring and Struts?

1. Framework Difference -
Spring -
Its application framework in which spring MVC is one of the modules of Spring Framework.
             Spring can be used for all layer implementation unlike Struts (only front end related) and Hibernate (only database related). 
Note**-
Application framework means Spring can be used for any Java application development such as
1.Desktop application
2. Enterprise application (using EJB)
3.Mobile application
4.Web application.
5.Games
Struts -
Its web application framework.
Struts Framework is designed for development of only web applications.

2. Design Pattern Difference -
Spring -
Spring implements IOC Design Pattern.
Spring -
Struts implements  MVC Design Pattern.

3.Invasion Difference -
Spring -
Spring is non-invasive , means Spring does not force us to extend or implement default Spring API Classes or Interfaces.
Struts -
Struts is invasive ,means Struts force us to extends or implement  Struts API Base Classes or Interfaces such as Action.

4. Integration 
Spring -
Spring allows easy integration of JDBC ,ORM.
We do not need to write manual code for this.It is readily available in Spring just need configure it.
Struts -
Struts does not allow easy integration of JDBC, ORM.
We have to write code for this manually.

5. API Weight Difference -
Spring -
It is light weight framework.
Minimum required module is Spring core.
Other modules such as AOP, MVC are need based and can be added when needed.
Struts -
It is heavy weight framework.
All Spring API is needed to be added before developing Spring application.

6.Coupling Difference-
Spring -
Spring is loose coupled because of Dependency Injection.
Struts -
It is tightly coupled because of lack of Dependency Injection.

7. Inbuilt Middle-ware -
Spring -
Spring provides in built middle-ware services such as Transaction,Logging and Connection Pooling. 
Struts -
It does not provide in built middle-ware.

Reference link --->
http://myjourneyonjava.blogspot.in/2014/02/difference-between-spring-and-struts.html

Modules in Spring -
There are main 6 modules -
1.Spring Core      -  Mandatory to use
2.Spring Context -  J2EE
3.Spring JDBC    -  JDBC
4.Spring ORM      -
5.Spring AOP       -  Aspect Oriented Programming
6.Spring Web-MVC -for web app

1.Spring Core -
It's the Heart of Spring.
Tight coupling and Loose coupling of java objects is the main concept of of Spring core.
Eg.
public class Traveller {
Car c = new Car();    //Tight coupled.(when change Car object ,we have to change every object of car)
public startJourney(){
      c.move();        
  }
}

Above problem is resolved by loose coupling which uses Dependency Injection to achieve it.
This is achieved by using Interface.

Interface Vehicle {
void move();
}

class Car Implements Vehicle {
public void move(){
//code
  }
}

class Bike Implements Vehicle {
public void move(){
//code
  }
}

class Traveler{
Vehicle v;
public void setV(Vehicle v){ // Car or Bike is injected by calling SetV() method.
this.v =v;                               //so,when object is replaced we do not need to change in Traveller class.
}
public void startJourney(){
v.move();
}
}

In short, DI is a mechanism,which Object is configured with fields by external entity. (not by Dependent class but by Spring IOC container.)
one more eg.
public class MyDao {

    protected DataSource dataSource =
    new DataSourceImpl("driver", "url", "user", "password");

    //data access methods...
    public Person readPerson(int primaryKey) {...}

  }
    
here, myDao needs to instantiate DataSourceImpl to get DataSource. Hence it is dependent on both
DataSourceImpl class and DataSource interface.
Also 4 strings passed as parameter also hard coded.
This arrangement is very tightly coupled.
Suppose,
We have to change the database, in this case we have to change DataSource in every class ,which is implemented this way.This is bad practice.

Solution is -
public class MyDao {

  protected DataSource dataSource = null;

  public MyDao(String driver, String url, String user, String password){
    this.dataSource = new DataSourceImpl(driver, url, user, password);
  }


  //data access methods...
  public Person readPerson(int primaryKey) {...}

}

Use constructor to instantiate dataSource.
Though myDao depends on dataSource and DataSourceImpl ,it does not need to instantiate them itself.
The class whichever is going to use myDao instance will initiate it using required parameter.

more better solution is -

public class MyDao {

    protected DataSource dataSource = null;
    
    public MyDao(DataSource dataSource){
      this.dataSource = dataSource;
    }

    
    //data access methods...
    public Person readPerson(int primaryKey) {...}

  }

DI Types -
1.Setter methods (Traveller eg 1)
2.Constructor     (both above eg)
3.Interface          (both above  eg)

Note-** In Spring each java class is called as Spring Beans. 

How to create Basic Spring Project ?
Spring has jar file for each module.
Or Spring.jar contains all modules.It depends on commons-logging.jar
Spring does not provide commons-logging.jar we have to download it .
In short, we need -
1.Spring.jar
2.commons-logging.jar

1. Spring environment starts by loading Spring config xml file in Resource interface object.

           Resource res = new ClassPathResource(config.xml); 

2. Now Spring IOC Container object is created after reading xml file by Resource object.
            IOC container is called as BeanFactory becuase it creates bean objects (java classes) and injects whenever asked.
  
          BeanFactory factory = new XmlBeanFactory(res);

3. Now we can get required bean object from IOC Container calling getBean().

         Object ob = factory.getBean(“bean1″);
         FirstBean fb = (FirstBean)ob;


Hello Spring Program -
1.Welcome Bean (Welcome Class)


package java4s;
public class WelcomeBean {
   private String message;
   public void setMessage(String message)
   {
   this.message = message;
   }
   public void show()
   {
   System.out.println(message);
   }
}

2. Main Class To Test Spring
package java4s;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class ClientLogic {
public static void main(String[] args)
{
Resource res = new ClassPathResource("spconfig.xml");
BeanFactory factory = new XmlBeanFactory(res);
Object o = factory.getBean("id1");
WelcomeBean wb = (WelcomeBean)o;
wb.show();
}
}
3.Spring Config xml

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="id1" class="java4s.WelcomeBean">
<property name="message" value="Welcome to spring" />
</bean>
</beans>


The above is example of setter method for primitive Spring (DI Type 1)
              Here. String message is injected on calling from main() from Main class.

http://www.java4s.com/spring/setter-injection-with-objects-spring-dependency-in-the-form-of-objects/



Saturday, 17 December 2016

BigData and Hadoop

What is Big Data ?
In general, word or excel documents can have data in range of  MB.
Movies,application code can  have data in range of GB.
But data of the size of PB(10^15 -Peta Bytes) is called as Big Data.

Almost 90% of data have been generated in the last 3-4 years.

Sources of Big Data -
1.Social Networking Sites such as Facebook,Google,Twitter etc.
2.E-commerce Sites such as Amazon, Flipkart, Alibaba etc.
3.Weather Stations
4.Telecom Companies
5.Share Market

3 V's of Big Data -
1.Velocity - The rate of increase of Big Data - Doubles in Every 2 years
2.Veracity-  The Data can be structured such as RDBMS or NON-SQL like MongoDB
Bank Transaction is structured data stored in tables.
Log File or CCTV footage is unstructured data.
3.Volume  - The Size of the data.

Realtime application of Big Data -
A E-commerce company wants to reward with $200 Gift Voucher to its top 10 customers who have spent most in last 1 year. Moreover, company wants to find the trend of these customers so that it can suggest more related items to them.

Problem -
Huge  amount of data  needs to be stored, analyzed, processed,




Friday, 16 December 2016

JDBC Basics

JDBC - Java DataBase Connecetion

Java Reflection

Reflection is the process of Examining or Modifying the run time behaviour of class at run time.
               Class (java.lang,Class) provides many methods to examine or change run time behaviour of class.

Reflection Application -
1.IDE  eg. Eclipse ,Net-Beans etc. 
2.Debugger
3.Test Tools
  
Class "Class" usage -
1.gives methods to get meta-data of Class at runtime.
2.gives methods to examine or change runtime behaviour of class.

How to get Class class object?
1.forName() of class Class
Class c = Class.forName("com.tush.pat.Test");
syso(c.getName());   //prints class name

2.getClass() of Any Object
Simple sm = new Simple();
Class c = sm.getClass();
syso(c.getName());   //prints class name

3..class syntax
  Class c = Simple.class;
  syso(c.getName());   //prints class name

Imp Methods of class Class -
1.newInstance()   -gives new instance of Class

How to get Field ,Constructor and Methods from Class?
Reflection usage Reflect class and Class class. 

       Field f[] = c.getDeclaredFields();
        for(int i=0;i<f.length;i++){
            System.out.println(f[i]);
        }
       
        Method  m[] = c.getDeclaredMethods();
        for(int i=0;i< m.length;i++){
            System.out.println(f[i]);
        }

       
         Constructor c[] = c.getDeclaredMethods();
        for(int i=0;i< c.length;i++){
            System.out.println(f[i]);
        }
 


where Field,Constructor and Method are members of  Reflect class.


How to access Private Fields and Methods in java using reflection ?
As discussed above we can use Reflect and Class classes.
Eg.
public class Simple{
      private void callMe(){
       syso("Hello From Private Method.")
      }
}

public class TestPrivate{
 main(){
          Class c = Class.forName("Simple");
          Object o= c.newInstance();    
          Method m =c.getDeclaredMethod("message"null);   
          m.setAccessible(true); 
          m.invoke(o, null);
      }
}

  same for private members.



 

Monday, 12 December 2016

SQL Basics

SQL is Structured Query Language used to interacts with RDBMS (Relational Database Management System)
The word Relational means the data is organized in such a way that there is clear relations between different tables.

SQL Constraints -
Constraint means specific rules for the data in the TABLE.
If there is any violation between constraint and data action, then data action is aborted by the constraint.

1.NOT NULL Constraint - makes column not to accept NULL values.
By default table column can hold NULL value.

2.UNIQUE Constrain - uniquely identifies each record in table
Primary Key and Unique both guarantees unique record.
Note*- Primary Key has automatically UNIQUE constraint defined on it.
Also, We can have many UNIQUE constraint per table but one Primary Key per Table.

3.PRIMARY KEY Constrain - UNIQUE, NOT NULL and one per table.

4.FOREIGN KEY Constrain - 
A FOREIGN KEY in one table points to  PRIMARY KEY in another table
Need** - 
1.Helps to prevent data action that would destroy links between table. 
2.Helps to prevent insertion of invalid data into table (with FK)  because other table(with PK) must have reference to it. 

5.CHECK Constraint - to limit range of value.

SQL Indexes - 
Indexes allow database application to find data fast,without reading full table.
Users cannot see Indexes.They are used to speed up the searches.
 Disadvantage - 
1. Updating table with indexes takes more time than table without indexes. 
Because indexes will also be updated
Note**-.
Hence use Index only on those tables which will be searched frequently 

 SQL Views -
This is Virtual Table based on the result-set of SQL Statement.
Its just like table with rows and column with data from one or more table.
 
 IS NULL and IS NOT NULL -
Whenever column has no value, by default its NULL.
Null values cannot be analyzed by operators such as =,>,<
 IS NULL - when column has no value for this record.
IS NOT NULL -  when column has value for this record.

Order By -
To sort the records based on one or more column.
By Default - Ascending Order
In case of order by multiple columns 'order of  sorting base on sequence on column.

 Like - used  for Pattern
s% -  starting with letter 's'
%s - ending with letter 's'
 %sassy% - containing pattern 'sassy'

Not Like - opposite of like.

SQL JOINS -
Joins are used to combine rows from one or more TABLES

JOIN (INNER JOIN) -
It returns all the rows from two table as long as JOIN Condition is met. 
Eg.
 SELECT ORDERS.AMOUNT,ORDERS.ORDER_ID,CUSTOMERS.FNAME
FROM ORDERS
JOIN CUSTOMERS
ON ORDERS.CUSTOMER_ID = CUSTOMERS.CUSTOMER_ID

As same as -
SELECT ORDERS.AMOUNT,ORDERS.ORDER_ID,CUSTOMERS.FNAME
FROM ORDERS
INNER JOIN CUSTOMERS
ON ORDERS.CUSTOMER_ID = CUSTOMERS.CUSTOMER_ID

Here the sequence of  tables ORDERS and CUSTOMERS does not matter.

LEFT JOIN -
It returns all the rows from LEFT Table and matching rows from RIGHT Table.
Eg.
SELECT ORDERS.AMOUNT,ORDERS.ORDER_ID,CUSTOMERS.FNAME
FROM ORDERS
LEFT JOIN CUSTOMERS
ON ORDERS.CUSTOMER_ID = CUSTOMERS.CUSTOMER_ID 


  Here the sequence of  tables ORDERS and CUSTOMERS does matter.

 LEFT Table  = ORDERS (So all rows from ORDERS Table)
 RIGHT Table= CUSTOMERS (matching rows if any)  
  

RIGHT JOIN -
It returns all the rows from RIGHT Table and matching rows from LEFT Table.
Eg.
SELECT ORDERS.AMOUNT,ORDERS.ORDER_ID,CUSTOMERS.FNAME
FROM ORDERS 

RIGHT JOIN CUSTOMERS
ON ORDERS.CUSTOMER_ID = CUSTOMERS.CUSTOMER_ID 


 Here the sequence of  tables ORDERS and CUSTOMERS does matter.

 LEFT Table  = ORDERS (matching rows if any)
 RIGHT Table= CUSTOMERS (So all rows from CUSTOMERS Table )  

FULL JOIN -
It returns all the rows from RIGHT Table and all rows from LEFT Table whether joining condition is met or not .
Eg.
SELECT ORDERS.AMOUNT,ORDERS.ORDER_ID,CUSTOMERS.FNAME
FROM ORDERS 

FULL JOIN CUSTOMERS
ON ORDERS.CUSTOMER_ID = CUSTOMERS.CUSTOMER_ID 


 Here the sequence of  tables ORDERS and CUSTOMERS does matter.

 LEFT Table  = ORDERS (So all rows from ORDERS Table )
 RIGHT Table= CUSTOMERS (So all rows from CUSTOMERS Table )  

SELF JOIN - 
It is used to join a table to itself as if there were two tables.
Eg.
SELECT O.ORDER_ID,O.CUSTOMER_ID
FROM ORDERS O,  ORDERS C
WHERE O.AMOUNT < C.AMOUNT


No use of Keywords ON ,JOIN etc

  
 
  
 

Design pattern Basics

What is Design Pattern?
These are well proved solutions to any specific problem/task.

Eg. 
Suppose you want to create a class for which only a single instance (or object) should be created and that single object can be used by all other classes.
Ans -Singleton Design Pattern

Advantages -
1.Reusable
2.Define System Architecture 
3.Better System
4.Easy to scale and maintain app 

When to use Design Pattern?
During the analysis and requirement phase of SDLC(Software Development Life Cycle). 

Classification -
1.Core Java Design Pattern 
2.J2EE Design Pattern

A.Core Java Design Patterns-
1.Creational Design Pattern -
  
Singleton Design Pattern -
It defines a class that has only one instance and provide global access to it.
It has two types -
1.Early Initialization  - Instance creation when class is loaded
2.Lazy Initialization - Instance creation when required(on calling getInstance())

How to create?
Private & Static variable - To get memory once.
Private Constructor -  To prevent instance creation from outside class
Static Factory Method - For global access to user to the Singleton Object

With Early Initialization
With lazy Initialization
 Above eg. Singleton is A class

Significance Of Classloader in Singleton -
If singleton is loaded by two classloader then 2 instances of Singleton will be created.
Each singleton instance per each Classloader.


Significance Of Serialization in Singleton -
We can serialize and deserialize Singleton instance.
But on deserializing it will not return Singleton object.

Solution -
Override readResolve() to enforce to give Singleton Object.

Singleton Real Life Example  from JDK -
1.Runtime (java.lang.Runtime). There is only one Runtime instance for Java Application.
2.Toolkit (java.awt.Toolkit)
3.Desktop (java.awt.Desktop)

Which class can be made Singleton ?
The class which can be available for whole application and only one instance is available throughout application.
Eg.
Real Life example could be  GUI Popup.
We can make sure that at a time only one popup is available on the screen.  
 

Factory Method Pattern -
It defines an Interface or Abstract class to create object but let sub-classes decide which  class to be instantiated.
In short, subclasses are responsible for creation on object.
 
Advantages -
1.It let subclasses choose which object to create
2.It promotes loose-coupling by eliminating the need to bind classes into code.
It means code interacts with Interface or Abstract Classes.

Eg.Electricity Bill Calculation
http://www.javatpoint.com/factory-method-design-pattern 

Prototype Design Pattern -
It helps in cloning of existing object instead of creating new one.
And new cloned object can be customized as per requirement.

When to use?
When price of creating object using new keyword is expensive.

Advantages -
1.Hides complexities for creating new object.
2.You can add or remove object at runtime.

Eg.Employee Record
http://www.javatpoint.com/prototype-design-pattern


Proxy Design Pattern -
Proxy means object representing another object.
It provides control over access of original object

Advantage-
It protects original object from outside world.

When to use-
Protective proxy server

Eg.Proxy Internet Access
http://www.javatpoint.com/proxy-pattern