Wednesday, June 18, 2014

SOAP vs REST

Constraints

SOAP(simple object access protocol)

RESTful (Representational State Transfer)

Protocol
XML based protocol defines rules of message type/format on top running on any protocol (SMTP, HTTP, FTP, TCP/IP)
Describes architectural principles which runs on HTTP/HTTPS and have no additional message layer/formats
Data Type
Standard format of XML
No standard set of format and can be any type i.e., XML, JSON, HTML, Plain Text
State
State is maintained
Stateless and preferred for single operations. (GET, CREATE, READ, DELETE, Update)
Adding web services in existing application
Existing web application needs to be modified and need more effort to add web services into the application
Existing web application need not any modification and additional very less effort needed to add web services.
Lightweight
Heavyweight
Lightweight
Speed
Slow because of XML formats
Fast because of no additional message layers
Security
More secured as data going as XML with secured headers, encryption available.
Less secured data transfer.
Caching
Not available
Available for HTTP GET resources
Implementation and Client creation
Little bit complex
Implementation is easy and client creation also easy if we know the input/output data format.
Access Type
WSDL defines messages, bindings, operations and locations of web services.
Simple Unique URI for each resource and no further complex definitions
When to use?
1.   More reliable and secured as SOAP has more standard set of rules
2.   Both server and client has mutual contract between them
3.   If want to have state-full transactions
4.   Supports any transport protocol SMTP, TCP/IP, JMS and HTTP
5.   Best choice for combined and distributed and dependent services
6.   Complex and development needs learning
1.   If low bandwidth with high performance
2.   If you want to have CRUD kind of applications or expose resources and not fit business operations
3.   If you like to cache some static resources
4.   Supports only HTTP/HTTPs
5.   Best choice for direct point to point services like sharing IT assets or CRUD operations
6.   Easy to learn and implement

Friday, June 6, 2014

Best Example Code for synchronized method

Synchronization in Java: 

                    In mulch-threaded programming we must consider synchronization of commonly shared resources/operations, to improve performance and avoid weird behavior of programming to get expected result. Why it is important means, if a common resource is used by more than one thread, then there is possibility of changing of state/values of commonly shared resources when another thread also working on the same. So it will lead to unexpected behavior.

                   Let us see the example program which counts the numbers from 1-3000 and prints them. But it is called by two persons(threads) to count. We have two methods one is synchronized and another one is non-synchronized normal method. 

Note : Difference between synchronizing method and block in a method

1. If you are overriding a method which is not synchronized in its declaration then you cover the code part inside the method by using synchronized keyword so the part of the code becomes synchronized.

2. If you synchronize method it is not accessible for other till the thread release control, but if you have synchronized block then the others will get access to the method and only wait to execute particular lines of code only. This will improve performance of the whole system because many objects can acquire the system.

  Output of Normal method : (public void incrementAndPrintInt) is shown below when two persons Thread_1 and Thread_2 called them.

Thread_1 0
Thread_2 0
Thread_1 1
Thread_2 2
Thread_2 4
Thread_2 5
Thread_2 6
Thread_1 3
Thread_2 7
Thread_1 8
Thread_2 9
Thread_1 10


 Output of Synchronized method : (public synchronized void incrementAndPrintInt) is shown below when two persons Thread_1 and Thread_2 called them.

Thread_2 0
Thread_2 1
Thread_2 2
Thread_2 3
Thread_2 4
Thread_2 5
Thread_2 6
Thread_2 7
Thread_2 8
Thread_2 9
Thread_2 10

 

Explanation: 

In the normal method it is accessed by both the persons and called so the count values is affected by both of them, ie., the values increased by Thread_1 is unknown to Thread_2. So Thread_1 missed to count 2,4,5,6,7. And the counting also not in order. This is a unwanted/unexpected behavior of the Counter. 

But if you see the output of the Synchronized method then count is in order like 1,2,3,4....10. And Thread_1 is not interrupted the method while Thread_2 is counting. This is what we want. When one person is working with one resource don't let the others disturb. So here the Thread_2 locked the method and releases if after completing its job to another thread. During the lock period no one disturbs the counter.

Code 1 : Main Class instantiates counter and shares it to threas objects and triggers them

public class SynchronizedTest {

    public static void main(String[] args) {
        MyCounter c = new MyCounter();
        Thread1 t1 = new Thread1(c);
        Thread2 t2 = new Thread2(c);
        t1.start();
        t2.start();
    }
}

Code 2: MyCounter class has method incrementAndPrintInt is given here as non-synchronized. But to see the output of synchronized please add synchronized keyword in the method signature and compare the difference.

public class MyCounter {

    int count =0;

     // put synchronized before void for output two
    public void incrementAndPrintInt(String s) {
        while (count < 1000) {
            System.out.println(s+" "+count);
            count++;
        }
    }
}

Code 3: Thread1 is a class calls the counter count method.

 public class Thread1 extends Thread {

    MyCounter counter;
    Thread1(MyCounter counter) {
        this.counter = counter;
    }
    public void run() {
        counter.incrementAndPrintInt("Thread_1");
    }
}

 Code 4: Thread2 is a class calls the counter count method.

public class Thread2 extends Thread {

    MyCounter counter;
    Thread2(MyCounter counter) {
        this.counter = counter;
    }
    public void run() {
        counter.incrementAndPrintInt("Thread_2");
    }
}


Simple Runnable Implementation

Simple Thread Sample using Runnable interface Implementation

Here the sample code explains how to implement Runnable interface to create threads in Java. Please see previous post to know How to create threads by extending Thread class.

class 1: This MyPrinter is class, has method print() which will be called from multiple threads and is shared across multiple threads.

public class MyPrinter {
   
    public void print(String pName,int i)
    {
        System.out.println(pName+"_"+i);
    }
}

class 2: This is the class which implements Runnable interface and overrides the run methods, the job/task you want to perform in thread should be put inside the methods run(). 

public class Runnable1 implements Runnable {

    private MyPrinter printer;
    Runnable1(MyPrinter printer) {
        this.printer = printer;
    }
    public void run() {
        int i = 0;
        while (i < 200) {
            printer.print("Runnable_1", i);
            i++;
        }
    }
}


class 2: This is the another same as above class which implements Runnable interface and overrides the run methods, the another job/task you want to perform in thread should be put inside the methods run().

public class Runnable2 implements Runnable {

    private MyPrinter printer;
    Runnable2(MyPrinter printer) {
        this.printer = printer;
    }
    public void run() {
        int i = 0;
        while (i < 200) {
            printer.print("Runnable_2", i);
            i++;
        }
    }
}


class 4: The main class to be executed is described here. Please see the difference here, unlike instantiating the Runnable and calling start() method on it, we instantiate Runnable1 and Runnable2 objects and  passing those instance as argument to another Thread objects. So these are the real objects.

 
public class SimpleThreadTest {
    public static void main(String[] args) {
        MyPrinter p = new MyPrinter();
       
        Runnable1 t1= new Runnable1(p);
        Runnable2 t2= new Runnable2(p);
       
        new Thread(t1).start();
        new Thread(t2).start();
    }
}

Simple Thread in Java

Simple Thread using extending Thread and implementing Runnable

Multi-threading means a single code program with different parts executed at same time in parallel, those parts are threads. We here see how to create threads. 

Class 1:  The first class SimpleThreadTest here instantiate a common printer, which receives input strings from multiple threads and prints. And creates two threads for different thread classes Thread1 and Thread2. And starts them both. By running this class you will see the output console with Threads names in mixed order ie., the thread executes parallel with one another same time.

public class SimpleThreadTest {

    public static void main(String[] args) {
        MyPrinter p = new MyPrinter();
       
        Thread1 t1= new Thread1(p);
        Thread2 t2= new Thread2(p);
       
        t1.start();
        t2.start();
    }
}



Class 2: This is the Thread implementation which does some calculation and send the data to be printed to common printer class. The common printer instance is given here as constructor argument.

public class Thread1 extends Thread {

    private MyPrinter printer;

  Thread1(MyPrinter printer) {
        this.printer = printer;
    }
    public void run(){
        int i=0;
        while( i < 200 )        {
            printer.print("Thread 1", i);
            i++;
        }
    }
}


Class 3: This is the  (Thread2) Thread implementation which does some calculation and send the data to be printed to common printer class. The common printer instance is given here as constructor argument.

public class Thread2 extends Thread {

    private MyPrinter printer;

    Thread2(MyPrinter printer) {
        this.printer = printer;
    }

    public void run(){
        int i=0;
        while( i < 200 )        {
            printer.print("Thread 2", i);
            i++;
        }
    }
}


Class 4:  This is a common printer class has public method print called from different thread instances. Prints the thread name and data(i).

public class MyPrinter {
   
    public void print(String pName,int i)
    {
        System.out.println(pName+"_"+i);
    }
}

Thursday, June 5, 2014

hibernate: get vs load

The difference between get() and load() methods of class Session is


get(Student.class, 234) -  returns the entity instance of the class(Student) from  table student matched with the unique identifier value 234.

load(Student.class, 234) - returns the entity instance of the class(Student) from  table student matched with the unique identifier value 234.

But the exact difference between them is get returns null when there is no match in the DB table while,  the load method throws exception "org.hibernate.ObjectNotFoundException: No row with the given identifier exists".

Wednesday, June 4, 2014

Hibernate Session createQuery() vs createSQLSquery() vs get()

What are the difference between createQuery, createSQLSquery method of class Hibernate's Session class?


createQuery - uses HQL like "FROM Student" where "Student" is the mapping object class name.
Eg:       
        Session session = factory.openSession();
        Query query = session.createQuery("FROM Student where studentId="
                + studentId);
        Student ss = (Student) query.list().get(0);
        System.out.println(ss.getFirstName() + "    " + ss.getLastName());
        session.close();


createSQLQuery -uses native SQL like "select * from student" where student is the table name.
Eg:
        Session session = factory.openSession();
        SQLQuery query = session.createSQLQuery("select * from student where student_id="
                        + studentId);
        query.addEntity(Student.class);
        List list = query.list();
        for (Object object : list) {
            System.out.print(((Student) object).getFirstName()+"     "+((Student) object).getLastName());
        }   
        session.close();

You need to mention the entity class for which class you are looking for.

get  - returns the persistent instance of the given entity class with the given identifier (mentioned in mapping Student.hbm.xml as id (student_id column)).
Eg:
        Session session = factory.openSession();
        Student ss = (Student) session.get(Student.class,student_id);
        System.out.println(ss.getFirstName() + "    " + ss.getLastName());
        session.close();

Hibernate sample code save()



This is the Hibernate sample code which inserts a record set into a table.
Create a Java project HibernateCRUDSampel in Eclipse project explorer.

1.    Create a folder structure.



2.    Create hibernate.cfg.xml. 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
      <session-factory>
            <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
            <property name="connection.url">jdbc:mysql://localhost/testapp</property>
            <property name="connection.username">root</property>
            <property name="connection.password">password</property>
            <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
            <property name="connection.show_sql">true</property>
            <mapping resource="resource/Student.hbm.xml" />
      </session-factory>
</hibernate-configuration>
 

3.    Create a Student mapping file.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
      <class name="sample.hiber.crud.model.Student" table="student">
            <id name="studentId" type="java.lang.Integer">
                  <column name="student_id" />
                  <generator class="identity" />
            </id>
            <property name="regNo" type="java.lang.Long">
                  <column name="reg_no" />
            </property>
            <property name="firstName" type="string">
                  <column name="first_name" />
            </property>
            <property name="lastName" type="string">
                  <column name="last_name" />
            </property>
            <property name="age" type="java.lang.Integer">
                  <column name="age" />
            </property>
            <property name="sex" type="java.lang.Character">
                  <column name="sex" />
            </property>
            <property name="mailId" type="string">
                  <column name="mail_id" />
            </property>
            <property name="mobileNo" type="string">
                  <column name="mobile_no" />
            </property>
      </class>
</hibernate-mapping>
 

 

4.    Create a table student in MySQL with following structure





5.    Create a mapping object Class Student.java


public class Student implements Serializable{

      private static final long serialVersionUID = -1097973765295431159L;
      private int studentId;
      private long regNo;
      private String firstName;
      private String lastName;
      private int age;
      private char sex;
      private String mailId;
      private String mobileNo;
      // Constructor
      public Student() {
      }
      // Constructor
      public Student(int studentId, long regNo, String firstName,
                  String lastName, int age, char sex, String mailId, String mobileNo) {
            this.studentId = studentId;
            this.regNo = regNo;
            this.firstName = firstName;
            this.lastName = lastName;
            this.age = age;
            this.sex = sex;
            this.mailId = mailId;
            this.mobileNo = mobileNo;
      }
      public int getStudentId() {
            return studentId;
      }
      public void setStudentId(int studentId) {
            this.studentId = studentId;
      }
      public long getRegNo() {
            return regNo;
      }
      public void setRegNo(long regNo) {
            this.regNo = regNo;
      }
      public String getFirstName() {
            return firstName;
      }
      public void setFirstName(String firstName) {
            this.firstName = firstName;
      }
      public String getLastName() {
            return lastName;
      }
      public void setLastName(String lastName) {
            this.lastName = lastName;
      }
      public int getAge() {
            return age;
      }
      public void setAge(int age) {
            this.age = age;
      }
      public char getSex() {
            return sex;
      }
      public void setSex(char sex) {
            this.sex = sex;
      }
      public String getMailId() {
            return mailId;
      }
      public void setMailId(String mailId) {
            this.mailId = mailId;
      }
      public String getMobileNo() {
            return mobileNo;
      }
      public void setMobileNo(String mobileNo) {
            this.mobileNo = mobileNo;
      }
      public static long getSerialversionuid() {
            return serialVersionUID;
      }

}

6.    Create class to run the sample application


import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

import sample.hiber.crud.model.Student;

public class MainTest {
      private static SessionFactory factory;

      public static void main(String[] args) {
      MainTest m = new MainTest();
      try {
            factory = new Configuration().configure().buildSessionFactory();
      } catch (Throwable ex) {
      System.err.println("Failed to create sessionFactory object." + ex);
      throw new ExceptionInInitializerError(ex);
      }
      m.addStudent(new Student(1012012, 123123123l, "John", "Peter", 35, 'M',
      "pjohn@gmai.com", "5678902324"));
      }

      private void addStudent(Student s) {
            Session session = factory.openSession();
            session.beginTransaction();
            session.save(s);
            session.flush();
            session.getTransaction().commit();
            session.close();
      }

}