Tuesday, December 31, 2013

JDBC Connectivity

You can not do everything in RAM. You need persistence.


Persistence can be achieved by writing to files or using Serilization too but Database is a more flexible way. Some of my friends are searching a way to connect to DB. This post is dedicated to them.

 I am assuming that the DB is Oracle. Following is a program to connect to a DB. Unfortunately I don't have a DB installed. So could not test it either but this will run accordingly with your DB.

1. Get the driver from http://www.oracle.com/technetwork/database/features/jdbc/index-091264.html
2. Add this jar to your program classpath
3. Get the database parameters such as, database host, database port, database service name, database user name, database password
4. Edit the following program with required details as I mentioned in point 2


 import java.io.IOException;  
 import java.sql.Connection;  
 import java.sql.DriverManager;  
 import java.sql.PreparedStatement;  
 import java.sql.ResultSet;  
 import java.sql.SQLException;  
 /**  
  *   
  */  
 /**  
  * @author Palash  
  *   
  */  
 public class MySecondProgram {  
      /**  
       * @param args  
       * @throws ClassNotFoundException  
       * @throws SQLException  
       * @throws IOException  
       */  
      public static void main(String[] args) throws ClassNotFoundException,  
                SQLException {  
           // Loads the driver and register it.  
           Class.forName("oracle.jdbc.driver.OracleDriver");  
           // Gets the connection  
           Connection conn = DriverManager.getConnection(  
                     "jdbc:oracle:thin:@DB_HOST:DB_PORT:DB_SERVICE_NAME",  
                     "USER_NAME", "PASSWORD");  
           // Prepare a statement to run on the connection  
           PreparedStatement statement = conn  
                     .prepareStatement("SELECT 'a' FROM DUAL");  
           // Run the qury in DB and get results  
           ResultSet rs = statement.executeQuery();  
           // Now, extract data from result set  
           while (rs.next()) {  
                String data = rs.getString(0);  
                System.out.println(data);  
           }  
      }  
 }  

5. Compile and run it.

Hope this helps you out.
Don't just stop here, if this article helped you out, spread the word.
Next
Palash Kanti Kundu

Monday, December 30, 2013

JDBC Drivers...

After the article on JDBC connectivity, I thought of providing my readers with the drivers required for some commonly used database. Which also can serve the purpose of a quick reference.
So, no more descriptions on it, let's get to the point.

Following are the databases Java connects with their Drivers,

DatabaseTested
Versions
JDBC DriverDatabase Specific
Support
Supported
Features
DB2 LUW8.2+, 9.7, 10.xInfoRead MoreList
H21.3, 1.4InfoRead MoreList
Informix9, 10, 11, 12InfoRead MoreList
JavaDB/Derby10InfoRead MoreList
Microsoft SQL Server2000-2014InfoRead MoreList
Mimer SQL9.1, 9.2, 9.3, 10InfoRead MoreList
MySQL3.23, 4, 5InfoRead MoreList
NuoDB2.0.4InfoRead MoreList
Oracle8i, 9i, 10g, 11g, 12cInfoRead MoreList
PostgreSQL8, 9InfoRead MoreList
SQLite3.6, 3.8.6InfoRead MoreList
Sybase ASE12.5, 15InfoRead MoreList
Vertica6.1.3, 7.0, 7.1InfoRead MoreLis

Hope this quick reference help you...
Don't just stop here, if this article helped you out, spread the word.

Palash Kanti Kundu

Monday, December 2, 2013

Introduction to Object Relational mapping...

We hear about Objects, we hear about relational databases. What is ORM then ?

We use relational databases as a backbone of our middle tier applications written in Object Oriented Programming Languages. In most of the scenarios we manipulate over data through our applications. To design the functionality of the application we generally use high level languages such as C++, Java, VB.net, C# etc. Now, to deal with relational database in back-end we need specific language which are based on relational tables, widely known as SQL (Structured Query Language).

Like java applications understand only objects, databases understand only tables and relations between them.

Hey wait, I have a question here, if they can talk different languages, how do they exchange information ?
Yes you are right, there is a gap between these two. To address this gap between  object oriented and relational model in traditional way we used JDBC. Java to Database Connectivity can be successfully achieved through JDBC but JDBC returns data in form of  resultset which have certain limitations like it will be more complex for large projects where we have multiple database tables and multiple objects to synchronize. Always programatically developer has to change relational data to java objects. Same functionality we can achieve in an effective way through ORM. Object relational mapping is the technique to convert data between relational data and object oriented data.
Now, we can go for a formal definition of ORM,
ORM - ORM is a technique to convert Objects into Database relations and vice-versa. That's it. Following is a visual representation for t he same,
ORM technique


Hmmm...(Awww...), it makes things simpler. Interesting. So, how do we do it ?
In the world of Java, Object relational mapping can be achieved through many tools such as Hibernate, Java Data Objects (JDO),Spring ORM and many more.
These tools are highly configurable, thus they are highly maintainable, reusable and really makes life easy while working with data.

So, which tool is the best ?
Well, every one has its own pros and cons. All come in different features and functionality. Each has their own implementations and . I will be talking about Hibernate here. So, you are free to chose anyone based on your application requirement.

Now, I have an example on how Hibernate helps in achieving this feature,

Lets say you are an Odia guy and you want some books from your friend who is a Bengali guy i.e your friend has Bengali version of the books you want. So to read those books you can do two things either you yourself convert the books in to Odia and then read else ask any translator to translate the book and provide you with the translated version of the Bengali books.
Here the first way is working as a normal JDBC flow where developer has the whole responsibility of translating the back-end data into Java objects. On the other hand, the second way is treated as Hibernate translation. Where the translator is working on translating the back-end data into Java objects and developer is more concentrated on the business logic.

Well, I would like to thank one of my readers who has contributed this article.
Article contributed by: Amrita Pattnaik

Palash Kanti Kundu

Sunday, December 1, 2013

Don't repeat the DAO !!!

Most of the time, DAO objects we create, we basically promote the same functionality for different object types.
For example, take the following two implementations.

Implementation of Person DAO for Person related operations
 /*  
  * Copyright 2014-2014 Palash Kanti Kundu.  
  *  
  * Licensed under the Apache License, Version 2.0 (the "License");  
  * you may not use this file except in compliance with the License.  
  * You may obtain a copy of the License at  
  *  
  *   http://www.apache.org/licenses/LICENSE-2.0  
  *  
  * Unless required by applicable law or agreed to in writing, software  
  * distributed under the License is distributed on an "AS IS" BASIS,  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  * See the License for the specific language governing permissions and  
  * limitations under the License.  
  *   
  */  
 import java.io.Serializable;  
 import java.util.List;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.springframework.orm.hibernate4.HibernateTemplate;  
 /**  
  * Person DAO implementation with basic CRUD operations.  
  *   
  * @author Palash Kanti Kundu  
  * @version 1.0  
  */  
 public class PersonDAOImpl {  
      private HibernateTemplate hibernateTemplate;  
      private SessionFactory sessionFactory;  
      public List<Person> fetchAll() {  
           @SuppressWarnings("unchecked")  
           List<Person> objectList = (List<Person>) hibernateTemplate  
                     .find("from Person");  
           return objectList;  
      }  
      public Person fetchById(Serializable id) {  
           return hibernateTemplate.get(Person.class, id);  
      }  
      public void save(Person bean) {  
           Session session = sessionFactory.openSession();  
           Transaction transaction = session.beginTransaction();  
           session.save(bean);  
           session.flush();  
           transaction.commit();  
           session.close();  
      }  
      public void update(Person bean) {  
           Session session = sessionFactory.openSession();  
           Transaction transaction = session.beginTransaction();  
           session.update(bean);  
           session.flush();  
           transaction.commit();  
           session.close();  
      }  
      public void deleteById(Serializable id) {  
           Session session = sessionFactory.openSession();  
           Transaction transaction = session.beginTransaction();  
           Person bean = fetchById(id);  
           session.delete(bean);  
           session.flush();  
           transaction.commit();  
           session.close();  
      }  
 }  


Implementation of Employee DAO for Employee related operations
 /*  
  * Copyright 2014-2014 Palash Kanti Kundu.  
  *  
  * Licensed under the Apache License, Version 2.0 (the "License");  
  * you may not use this file except in compliance with the License.  
  * You may obtain a copy of the License at  
  *  
  *   http://www.apache.org/licenses/LICENSE-2.0  
  *  
  * Unless required by applicable law or agreed to in writing, software  
  * distributed under the License is distributed on an "AS IS" BASIS,  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  * See the License for the specific language governing permissions and  
  * limitations under the License.  
  *   
  */  
 import java.io.Serializable;  
 import java.util.List;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.springframework.orm.hibernate4.HibernateTemplate;  
 /**  
  * Employee DAO implementation with basic CRUD operations.  
  *   
  * @author Palash Kanti Kundu  
  * @version 1.0  
  */  
 public class EmployeeDAOImpl {  
      private HibernateTemplate hibernateTemplate;  
      private SessionFactory sessionFactory;  
      public List<Employee> fetchAll() {  
           @SuppressWarnings("unchecked")  
           List<Employee> objectList = (List<Employee>) hibernateTemplate  
                     .find("from Employee");  
           return objectList;  
      }  
      public Employee fetchById(Serializable id) {  
           return hibernateTemplate.get(Employee.class, id);  
      }  
      public void save(Employee bean) {  
           Session session = sessionFactory.openSession();  
           Transaction transaction = session.beginTransaction();  
           session.save(bean);  
           session.flush();  
           transaction.commit();  
           session.close();  
      }  
      public void update(Employee bean) {  
           Session session = sessionFactory.openSession();  
           Transaction transaction = session.beginTransaction();  
           session.update(bean);  
           session.flush();  
           transaction.commit();  
           session.close();  
      }  
      public void deleteById(Serializable id) {  
           Session session = sessionFactory.openSession();  
           Transaction transaction = session.beginTransaction();  
           Employee bean = fetchById(id);  
           session.delete(bean);  
           session.flush();  
           transaction.commit();  
           session.close();  
      }  
 }  

So, we can see that both the classes basically achieve the same set of functionality but on different type. Now, if you go through these implementations and think it in a different way, you can find that, with Java 5.0 you can write it a single time and use it for different types with Generics.
Hibernate and Spring gives you the flexibility to use this concept in a fine grained way.

Well, it can be done in various ways, one implementation is here. You can check this article, its a great way to achieve the Generic DAO  implementation.
I have done it in another way, depending on my application needs. In my application, any persistence object is of type IBean. So, I have used the following DAO implementation in my application


 /*  
  * Copyright 2014-2014 Palash Kanti Kundu.  
  *  
  * Licensed under the Apache License, Version 2.0 (the "License");  
  * you may not use this file except in compliance with the License.  
  * You may obtain a copy of the License at  
  *  
  *   http://www.apache.org/licenses/LICENSE-2.0  
  *  
  * Unless required by applicable law or agreed to in writing, software  
  * distributed under the License is distributed on an "AS IS" BASIS,  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  * See the License for the specific language governing permissions and  
  * limitations under the License.  
  *   
  */  
 package com.palash90.assistant.dao;  
 import java.io.Serializable;  
 import java.util.List;  
 import org.hibernate.Criteria;  
 import org.hibernate.SessionFactory;  
 import org.springframework.orm.hibernate4.HibernateTemplate;  
 import com.palash90.assistant.beans.IBean;  
 /**  
  * DAO interface  
  *   
  * @author Palash Kanti Kundu  
  * @version 1.0  
  */  
 public interface IDao {  
      /**  
       * Returns the list of objects of the provided class  
       *   
       * @return  
       */  
      public List<? extends IBean> fetchAll(Class<? extends IBean> cls);  
      /**  
       * Returns the object with the provided id  
       *   
       * @return  
       */  
      public <T extends IBean> T fetchById(Class<T> cls, Serializable id);  
      /**  
       * Saves the bean to database  
       *   
       * @param bean  
       */  
      public void save(IBean bean);  
      /**  
       * Updates the bean in the database  
       *   
       * @param bean  
       */  
      public void update(IBean bean);  
      /**  
       * Deletes the bean from the database  
       *   
       * @param bean  
       */  
      void deleteById(Class<? extends IBean> cls, Serializable id);  
      /**  
       * Set the sessionFactory to be used  
       */  
      void setSessionFactory(SessionFactory sessionFactory);  
      /**  
       * Set the hibernateTemplate to be used  
       */  
      void setHibernateTemplate(HibernateTemplate hibernateTemplate);  
      /**  
       * Returns the list of object of Class type for the provided criteria  
       *   
       * @param cls  
       * @param criteria  
       * @return  
       */  
      <T extends IBean> List<T> fetchByCriteria(Class<? extends IBean> cls,  
                Criteria criteria);  
 }  

And this is the implementation,

 /*  
  * Copyright 2014-2014 Palash Kanti Kundu.  
  *  
  * Licensed under the Apache License, Version 2.0 (the "License");  
  * you may not use this file except in compliance with the License.  
  * You may obtain a copy of the License at  
  *  
  *   http://www.apache.org/licenses/LICENSE-2.0  
  *  
  * Unless required by applicable law or agreed to in writing, software  
  * distributed under the License is distributed on an "AS IS" BASIS,  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  * See the License for the specific language governing permissions and  
  * limitations under the License.  
  *   
  */  
 package com.palash90.assistant.dao;  
 import java.io.Serializable;  
 import java.util.List;  
 import org.hibernate.Criteria;  
 import org.hibernate.Session;  
 import org.hibernate.Transaction;  
 import com.palash90.assistant.beans.IBean;  
 import com.palash90.assistant.constants.AssistantConstants;  
 /**  
  * Generic DAO implementation with basic CRUD operations.  
  *   
  * @author Palash Kanti Kundu  
  * @version 1.0  
  */  
 public class GenericDAOImpl extends AbstractDaoImpl {  
   /*  
    * (non-Javadoc)  
    *   
    * @see com.palash90.assistant.dao.IDao#fetch(java.lang.Class)  
    */  
   @Override  
   public List<? extends IBean> fetchAll(Class<? extends IBean> cls) {  
      @SuppressWarnings("unchecked")  
      List<? extends IBean> objectList = (List<? extends IBean>) hibernateTemplate  
           .find(AssistantConstants.FROM + AssistantConstants.SPACE  
                + cls.getCanonicalName());  
      return objectList;  
   }  
   /*  
    * (non-Javadoc)  
    *   
    * @see com.palash90.assistant.dao.IDao#fetchById(java.lang.Class,  
    * java.io.Serializable)  
    */  
   @Override  
   public <T extends IBean> T fetchById(Class<T> cls, Serializable id) {  
      return hibernateTemplate.get(cls, id);  
   }  
   /*  
    * (non-Javadoc)  
    *   
    * @see com.palash90.assistant.dao.IDao#save(com.palash90.assistant  
    * .beans.IBean)  
    */  
   @Override  
   public void save(IBean bean) {  
      Session session = sessionFactory.openSession();  
      Transaction transaction = session.beginTransaction();  
      session.save(bean);  
      session.flush();  
      transaction.commit();  
      session.close();  
   }  
   /*  
    * (non-Javadoc)  
    *   
    * @see com.palash90.assistant.dao.IDao#update(com.palash90.assistant  
    * .beans.IBean)  
    */  
   @Override  
   public void update(IBean bean) {  
      Session session = sessionFactory.openSession();  
      Transaction transaction = session.beginTransaction();  
      session.update(bean);  
      session.flush();  
      transaction.commit();  
      session.close();  
   }  
   /*  
    * (non-Javadoc)  
    *   
    * @see com.palash90.assistant.dao.IDao#delete(com.palash90.assistant  
    * .beans.IBean)  
    */  
   @Override  
   public void deleteById(Class<? extends IBean> cls, Serializable id) {  
      Session session = sessionFactory.openSession();  
      Transaction transaction = session.beginTransaction();  
      IBean bean = fetchById(cls, id);  
      session.delete(bean);  
      session.flush();  
      transaction.commit();  
      session.close();  
   }  
   /*  
       * (non-Javadoc)  
       *   
       * @see dao.IDao#fetchByCriteria(java.lang.Class, org.hibernate.Criteria)  
       */  
      @SuppressWarnings("unchecked")  
      @Override  
      public <T extends IBean> List<T> fetchByCriteria(Class<? extends IBean> cls,Criteria criteria) {  
           return (List<T>) criteria.list();  
      }  
 }  

Now, if you need a specific kind of implementation for any of particular, you can inherit the generic implementation and add the particular functionality, like I have done for my Person DAO,

 /*  
  * Copyright 2014-2014 Palash Kanti Kundu.  
  *  
  * Licensed under the Apache License, Version 2.0 (the "License");  
  * you may not use this file except in compliance with the License.  
  * You may obtain a copy of the License at  
  *  
  *   http://www.apache.org/licenses/LICENSE-2.0  
  *  
  * Unless required by applicable law or agreed to in writing, software  
  * distributed under the License is distributed on an "AS IS" BASIS,  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  * See the License for the specific language governing permissions and  
  * limitations under the License.  
  *   
  */  
 package com.palash90.assistant.dao;  
 import java.util.List;  
 import org.hibernate.Criteria;  
 import org.hibernate.criterion.Restrictions;  
 import com.palash90.assistant.beans.person.Person;  
 public class EmployeeDaoImpl extends GenericDAOImpl {  
      /**  
       * Returns the list of persons with the name provided  
       *   
       * @param name  
       * @return  
       */  
      public List<Person> fetchByName(String name) {  
           Criteria criteria = sessionFactory.openSession().createCriteria(  
                     Person.class);  
           criteria.add(Restrictions.eq("firstName", name));  
           return fetchByCriteria(Person.class, criteria);  
      }  
 }  

Hope that, you get some idea about implementing your DAO in a generic way.
Now, Don't repeat the DAO.

Thanks for reading !!!

Palash Kanti Kundu

Wednesday, November 20, 2013

Website or Web Application

I don't know, how this came up to my mind and is it really helpful to my readers too. But, once I get a question I try my best to find the answer and I also did some search, read some articles and finally I get some idea on the difference.

So, I am just sharing the knowledge !!!

Well, these two terms are used interchangeably and both are available through web browsers. Either in the development or in the normal day to day uses of internet, we don't bother to know the difference and the difference is very small in today's world as the internet has become so much advanced these days.

Website is collection of information usually having multiple web pages. Like, this series of articles. Where, viewers have very little or nothing to interact with the website.

On the other hand, when an application is available over the internet, we call it as web application. Like, any mail application.

For example, you are reading my articles and really have a very little to interact with my articles. So, you can consider it as a website. But when I write articles, I have many more things to do so this becomes an interactive application at my end. So, its web application for me.

In a nutshell, we can formulate it as below,
website + interactive controls = web application

Nowadays, the web development and UI controls has gained a smooth control over the web pages. So, almost every website comes with interactive controls. So the distance between website and web application has become minute.

I hope, you will find this information useful. If so, please reshare. 

Palash Kanti Kundu

Friday, November 1, 2013

Servlet, the way you see it

Hey, have you ever thought of having a book from library ?
Of course, I have done that. Do you think that, I don't read books ?

No,  never. In fact reading books is a good hobby indeed.
Hey, I know that very well. Let's come to the straight point. Don't you think that easy way ?

Well, of course yes. Today I am going to tell you how a library system works.
I don't know why you are doing this. STILL GO ON.

Let's assume that you are going to issue a book on Hibernate.

You went to a library to get a book "JUST HIBERNATE" by O'rEILLY of 2nd Eddition. You meet the librarian and she asked you to fill up a requisition slip. You filled the slip which has three columns
  1. Name of the book
  2. Name of the publisher - O' REILLY
  3. Edition- 2nd Edition
You give this slip to librarian . Now librarian will read the request and will check in the register which bookshelf is having the book you  requested and will go to the shelf and find out the book and will hand it over to you.

Is that the way you borrow a book ?
Yeah, pretty much the same way.

Well, let's check this out in Java way in a web context !!!
You want some service from a server and you push a request to the server with some details you provide over the form (Requisition Slip) you see. There sits a container (Librarian) in the server side (Library), which reads the register (web.xml) for appropriate servlet (Bookshelf) and the servlet returns the response (Specified Book) and the response is sent to the client (You yourself) by the container.

Contributed by:                Amrita Pattnaik
Edited and re-written by:  Palash Kanti Kundu
Palash Kanti Kundu Palash Kanti Kundu Palash Kanti Kundu Palash Kanti Kundu

Internet defined simply

The Internet is so big, so powerful and pointless that for some people it is a complete substitute for life. - Andrew Brown

For most of us, this is true. Internet provides lots of information, lots of entertainment, lots of stuffs to pass time. But the original purpose of internet was to build an information network between computers and internet today really proved to be successful on this goal. Mitchell Kapor perfectly said "Getting information off the Internet is like taking a drink from a fire hydrant."

This powerful weapon can be accessed from any corner of the world using a web browser. Many web site and web applications are available over internet to provide you with information. Beautiful web pages are what we can see in our PC/Mobile phones and more interestingly, whatever device you use, you always get the same information in each of them.

As the days passing by, the numbers of websites are increasing. We for our day to day basis, visit many websites. Many of us are having our own Mail accounts, Facebook Account, WhatsApp Account. World is moving and we call this era, 'Era of Internet'. Most of the world is connected with the giant called, 'Internet' by any means. May be its for entertainment purpose (FacebookYoutube etc), or for news (www.timesofindia.comespncricinfo.com) or for health care purpose (https://www.healthcare.gov/) or may be for some knowledge gaining purpose (www.mathisfun.com) or to connect professionally (https://linkedin.com) or to store your files on cloud(drive.google.com) or to show off who you are (http://palashkantikundu.in) or simply when you have nothing special and start building something (palash90.intales.palash90.in) and the list goes on, each one use internet for a purpose.

Now let's try to see how this is done.

This is achieved by a Server-Client Concept. Following is the graphical representation of the architecture,
Client-Server architecture
To define the different components in the diagram, we have to go through some definitions,

Server: This is a software component which can perform some operations based on requests sent by a Client.
Client: A client is a software which sends request to the server.
User: A user is a person using the Client.

I am a person, can I be a user ?
Yes you are a user at this point of time and you are using a web browser, may be Firefox, Google Chrome, Internet Explorer, Safari, Opera etc. These are applications which sends a request to the server palash-90.blogspot.com; the server knows which information the client wants and does a beautiful job for you and finds the information you want and sends the information formatted as response back to the client you are using and the client application knows how to format the response and gives you a beautiful reading experience.

So, at its bare basic is a process of request-response communication.

So, we know how everything goes on. Now let's check how everything works.

Client application takes user input >> It then generates a request >> Client sends the request to Server

Server receives the request >> Server processes the request >> Server creates a response based on the processed output >> Sends back the response to client

To perform all these operations, Client and Server agrees upon a common language between them for communication. This language is known as HTTP. The communication takes place on a medium known as network. This network is responsible for all the communication taken place on it and also takes care of all the related hassles to ensure that the server and client should not bother about it and can perform their tasks at ease.

So, what is Internet ?
Internet is network of networks. Following diagram puts a more light on it.
Internet - network of networks
Now, its a bit tricky here. We know that network is responsible for a server and a client to communicate. Then we might think what is the use of Internet.

Well the answer is simple but it comes with a question. Suppose, you want a piece of information which is not available on the network you are connected (that happens in most cases), how would you fetch the information ?
Simple, I will connect to the network, it has the information in it.

Exactly, Internet does the same thing. It finds the network for you and connects your client to the network.

Definition from webopedia is 'The Internet is a global network connecting millions of computers. More than 190 countries are linked into exchanges of data, news and opinions.'

What is data ?
Well, this defines data.

Hope, this article helps you understand the internet. Thanks for reading.


Palash Kanti Kundu

REST - a simple approach for network communication

We know about Websites and Web Applications. In day to day uses, we see that most cases, we use Web Applications rather than websites. Now, web comes into different flavours, a perfect browser based GUI application, a powerful back end Web Service or a lightweight alternative REST Service.

Now, you all know about GUI Applications, anything that you see on a web browser like Internet Explorer, Mozilla Firefox, Google Chrome, Opera. When you hit a URL in the address bar, you see a GUI Application with lots of colours, lots of controls, lots of interactions etc.

But, this is not the case for the later two, they just provide the data in text based format like XML, JSON etc. In these cases, the server just knows which data to provide and care less about the presentation of the data.

Hey, wait, what is the necessity of using Web Services and REST, if we already can present the data in the way we want ?
Well, thanks for bringing up this point. Let's take a closer look on this part here. The business problem is already discussed here and a solution approach is also provided to address the business problem.

Well, I understand now, we need Web Service and REST. Now, my question is why REST, if we already have Web Service to answer all the problems ?
Well, you can use either of them.
Now, just to take a confirmation, would you like to have a powerful client application, more network bandwidth, more processing on data ? No, right !

Well, I got it. So, how REST handles all these scenarios ?
Web services use XML, which means a strict API, more verbose. The communication between Server and Client is also a point to consider. Web Services uses SOAP (based on XML) for communication.
Now, in case of REST, it is all based on HTTP. So, the overhead of request and response processing to and from SOAP or XML to or from Request/Response body is not required. Also REST uses JSON as the backbone for data transfer.
This boils down to less processing, less bandwidth and faster data transfer.

Well, now I understand. But you just told that, REST uses JSON, so what about data integrity ?
Well, that's a catch, REST thinks that the client and server knows their responsibility of transferring data. So, you are free to transfer anything you want. On the other hand, Web Services provide a really beautiful way of transferring data in particular format and you can even impose constraints using DTD and XSD if you want. So, data integrity is really a part where Web Services rule over REST.

Hmm... (Aww...) So, if I have a more like of data integrity, I should use Web Services in the cost of performance and bandwidth.
Yes, you are right. If you have a data integrity constraints, you are more likely to bend over Web Services rather REST.

Prev     Next
Palash Kanti Kundu

Thursday, October 31, 2013

Configure Web, REST and Web Service from a single application using Spring

Now, you have your web application ready and you have deployed it on the cloud. Your website has some viewers. Now comes Ms. Sharma to tell you, "Hey the look and feel of your web site is not good at all. Why don't you put some pink flowery image background and your site will attract more lady customers."
Now, its a cool approach you are going to implement, now again Mr. Kundu has some views on your application and he sends a mail, "Hey can you put some corporate looks in your website. It would be good to attract corporate customers as well'."

Now what, are you going Ms. Sharma way and put some images in your web site background or you are going with Mr. Kundu with some BlueSky theme ?

Now, I have my own way, I would have given them WS and REST exposures and ask them to create their own interfaces or I myself would have created different versions using the same business layer.

If you are not aware of them, you can read them. There are plenty of resources explaining them in minute detail.

Or may be your business requirement is something where you should have a web app, an android app and also an exposure for other clients (Like Windows Phone, ASP.NET  etc). What you are going to do in this situation ?
Mostly you can do, create different applications one for web, another for Web Service and another for REST. But that has a problem too, if you make a change in business, you have to change in all the 3 areas, code re-usability is in question. Other way around could be, install the business logic as separate jar and use it all the 3 applications. But some Cloud account has restrictions of limited application hosting (like Openshift has a restriction of only 3 for a free account). Of course you can buy some space on cloud but for most of the development or simple use case scenarios, I think you are not going to invest a lot.

So, what ?
What about exposing all your applications in a single build.

Yeah you can do that with help of Spring. There may be other way around leaving Spring too. But this one worked for me and it was easy to setup.

Its all about working with 3 different servlets in web.xml and configuring 3 Spring applications. So, the implementation part I am not going into detail, just going through the configuration.

Classpath Dependencies:
I am using JSF as web app and Spring WS and Spring RS. So, I got 31 dependencies in my system. You may have some more or less and if you are reading this section, you are advanced enough to determine which one to keep and which one to remove. Here are my dependencies,

antlr-2.7.7.jar
commons-logging-1.1.1 (1).jar
dom4j-1.6.1.jar
el-impl-2.2.1-b05.jar
hibernate-commons-annotations-4.0.5.Final.jar
hibernate-core-4.3.7.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
hsqldb.jar
jandex-1.1.0.Final.jar
javassist-3.18.1-GA.jar
jboss-logging-3.1.3.GA.jar
jboss-logging-annotations-1.2.0.Beta1.jar
jboss-transaction-api_1.2_spec-1.0.0.Final.jar
jsf-api-2.2.8-02.jar
jsf-impl-2.2.8-02.jar
jstl-1.2.jar
primefaces-4.0.jar
spring-aop-4.1.3.RELEASE.jar
spring-beans-4.1.3.RELEASE.jar
spring-context-4.1.3.RELEASE.jar
spring-context-support-4.1.3.RELEASE.jar
spring-core-4.1.3.RELEASE.jar
spring-expression-4.1.3.RELEASE.jar
spring-jdbc-4.1.3.RELEASE.jar
spring-orm-4.1.3.RELEASE.jar
spring-tx-4.1.3.RELEASE.jar
spring-web-4.1.3.RELEASE.jar
spring-webmvc-4.1.3.RELEASE.jar
jdom-2.0.2.jar
spring-ws-core-2.2.0.RELEASE.jar
wsdl4j-1.6.2.jar

Please choose accordingly and carefully, otherwise you will end up having ClassNotFoundException.

Now with that, we are moving forward with our web.xml changes.

Configure different exposure in web.xml
In Spring, Simple web app and REST both are handled by DispatcherServlet only while Web Services are handled by MessageDispatcherServlet. So, you don't have to worry about Web Service and REST/Web App.

But you will be in problem while configuring REST and Web App. It is the most important part.
You can try different url pattern mapping with the same servlet and handle them in controller. But, I got errors in this way too and its really painful to handle REST and Web App mapping in controllers. Cause, they behave in the same way.

So, what's the way out ?
Just extend DispatcherServlet and create a dummy servlet that does nothing except making itself a DispatcherServlet. Here is a sample.

 /**  
  *   
  */  
 package servlet;  
 import org.springframework.web.servlet.DispatcherServlet;  
 /**  
  * @author palash.k  
  *   
  */  
 public class RestDispatcher extends DispatcherServlet{  
      /**  
       *   
       */  
      private static final long serialVersionUID = 5153026121972664690L;  
 }  

And you put this in web.xml for your REST controllers.
 <?xml version="1.0" encoding="UTF-8"?>  
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
      http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
      id="WebApp_ID" version="2.5">  
      <display-name>PrimeFaces Web Application</display-name>  
      <context-param>  
     <param-name>contextConfigLocation</param-name>  
     <param-value>  
       /WEB-INF/resources/context.xml  
     </param-value>  
   </context-param>  
      <listener>  
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
   </listener>  
   <listener>  
     <listener-class>  
       org.springframework.web.context.request.RequestContextListener  
     </listener-class>  
   </listener>  
      <!-- WEB Application -->  
       <servlet>  
     <servlet-name>web</servlet-name>  
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
     <load-on-startup>1</load-on-startup>  
   </servlet>  
   <servlet-mapping>  
     <servlet-name>web</servlet-name>  
     <url-pattern>/web/*</url-pattern>  
   </servlet-mapping>  
   <servlet-mapping>  
     <servlet-name>web</servlet-name>  
     <url-pattern>*.jsp</url-pattern>  
   </servlet-mapping>

<!-- REST Service --> <servlet> <servlet-name>rest</servlet-name> <servlet-class>servlet.RestDispatcher</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>rest</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> <!-- Web Service --> <servlet> <servlet-name>webService</servlet-name> <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class> <init-param> <param-name>transformWsdlLocations</param-name> <param-value>true</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>webService</servlet-name> <url-pattern>/service/*</url-pattern> </servlet-mapping> </web-app>

Configure 3 different Spring applications:

web-servlet.xml
 <beans xmlns="http://www.springframework.org/schema/beans"  
      xmlns:context="http://www.springframework.org/schema/context"  
      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  
     http://www.springframework.org/schema/context   
     http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
      <import resource="resources/context.xml" />  
      <context:component-scan base-package="controllers" />  
      <bean  
           class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
           <property name="prefix">  
                <value>/WEB-INF/jsp/</value>  
           </property>  
           <property name="suffix">  
                <value>.jsp</value>  
           </property>  
      </bean>  
 </beans>  

rest-servlet.xml

 <beans xmlns="http://www.springframework.org/schema/beans"  
      xmlns:context="http://www.springframework.org/schema/context"  
      xmlns:mvc="http://www.springframework.org/schema/mvc" 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 http://www.springframework.org/schema/context   
     http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  
      <context:component-scan base-package="rest" />  
      <mvc:annotation-driven />  
 </beans>  

webService-servlet.xml

 <beans xmlns="http://www.springframework.org/schema/beans"  
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
      xmlns:sws="http://www.springframework.org/schema/web-services"  
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd  
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
      <context:component-scan base-package="ws" />  
      <sws:annotation-driven />  
      <sws:dynamic-wsdl id="person" portTypeName="Person"  
           locationUri="/service/Person/" targetNamespace="urn:assistant:1.0:person"  
           requestSuffix="Request" responseSuffix="Response">  
           <sws:xsd location="classpath:xsd/person.xsd" />  
      </sws:dynamic-wsdl>  
 </beans>  



Now, that's it. You now have configured your web app, Spring WS and Spring RS in a single app.

Palash Kanti Kundu

Wednesday, October 30, 2013

Step by step configuration of Hibernate, Spring MVC, Primefaces

So, you have decided to use Spring, Hibernate and Primefaces in your application. I am very much fond of each one of them cause, all of them very easy to use and open source. I use all of them in my own application.
But, the first time I tried to configure them in my application, I had nightmare. The most tough part was to configure Hibernate with Spring and to find how to use Spring beans in Managed Beans. But now my application is stable and development has become easy for me now.
So, I thought of sharing the knowledge to configure the application to use all of them.
I will use HSQL as DB for this post. I assume that you are capable of configuring your DB in the configuration files. Because, you are reading this post means, you are an advanced Java Developer.

Prerequisite
1.     You have knowledge on Spring, Hibernate and JSF and know the basics of setting them up individually
2.     Knowledge of Eclipse IDE or Maven or any other build tool
3.     Working database
4.     Hibernate 4 and Spring 4 (For another pair of these, generally these configuration needs a little change in the session factory configuration, which you can figure out in ease)
5.     Primefaces (3 or 4) and Spring(3 or 4)
This pair can have any combination. Choose any. Spring versioons are compatible with Primefaces versions.
Configuration
 I will go step by step for the configurations.


1. Mention the required libraries in your build - Required library list is huge cause Spring, Hibernate and Primefaces depend on different libraries. So please be careful otherwise you will get many exceptions. There are total 28 dependencies in total.
§  antlr-2.7.7.jar
§  commons-logging-1.1.1.jar
§  dom4j-1.6.1.jar
§  el-impl-2.2.1-b05.jar
§  hibernate-commons-annotations-4.0.5.Final.jar
§  hibernate-core-4.3.7.Final.jar
§  hibernate-jpa-2.1-api-1.0.0.Final.jar
§  hsqldb.jar
§  jandex-1.1.0.Final.jar
§  javassist-3.18.1-GA.jar
§  jboss-logging-3.1.3.GA.jar
§  jboss-logging-annotations-1.2.0.Beta1.jar
§  jboss-transaction-api_1.2_spec-1.0.0.Final.jar
§  jsf-api-2.2.8-02.jar
§  jsf-impl-2.2.8-02.jar
§  jstl-1.2.jar
§  primefaces-4.0.jar
§  spring-aop-4.1.3.RELEASE.jar
§  spring-beans-4.1.3.RELEASE.jar
§  spring-context-4.1.3.RELEASE.jar
§  spring-context-support-4.1.3.RELEASE.jar
§  spring-core-4.1.3.RELEASE.jar
§  spring-expression-4.1.3.RELEASE.jar
§  spring-jdbc-4.1.3.RELEASE.jar
§  spring-orm-4.1.3.RELEASE.jar
§  spring-tx-4.1.3.RELEASE.jar
§  spring-web-4.1.3.RELEASE.jar
§  spring-webmvc-4.1.3.RELEASE.jarWith all these dependencies, WebContent/WEB-INF/lib looks like

2.       Setup JSF for your application
Dependency declaration is complete. The next step is to setup Faces for your application.
In your web.xml mention faces servlet and the extensions you want to map with JSF and run your server. It should be working.
If not, then delete the web.xml and retry. Here is one sample for ease.




 <?xml version="1.0" encoding="UTF-8"?>  
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
      http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
      id="WebApp_ID" version="2.5">  
      <display-name>PrimeFaces Web Application</display-name>  
      <!-- Change to "Production" when you are ready to deploy -->  
      <context-param>  
           <param-name>javax.faces.PROJECT_STAGE</param-name>  
           <param-value>Development</param-value>  
      </context-param>  
      <!-- Welcome page -->  
      <welcome-file-list>  
           <welcome-file>faces/index.xhtml</welcome-file>  
      </welcome-file-list>  
      <!-- JSF mapping -->  
      <servlet>  
           <servlet-name>Faces Servlet</servlet-name>  
           <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>  
           <load-on-startup>1</load-on-startup>  
      </servlet>  
      <!-- Map these files with JSF -->  
      <servlet-mapping>  
           <servlet-name>Faces Servlet</servlet-name>  
           <url-pattern>/faces/*</url-pattern>  
      </servlet-mapping>  
      <servlet-mapping>  
           <servlet-name>Faces Servlet</servlet-name>  
           <url-pattern>*.jsf</url-pattern>  
      </servlet-mapping>  
      <servlet-mapping>  
           <servlet-name>Faces Servlet</servlet-name>  
           <url-pattern>*.faces</url-pattern>  
      </servlet-mapping>  
      <servlet-mapping>  
           <servlet-name>Faces Servlet</servlet-name>  
           <url-pattern>*.xhtml</url-pattern>  
      </servlet-mapping>  
 </web-app>  

3.       Add Spring MVC to Faces
Now, add Spring MVC to your faces application. You have to include  Spring context file as context-param with param name contextConfigLocation and RequestContextListener and ContextLoaderListener as your application listener.
So, basically you have to add three more tags in your web.xml.
Now, it’s time to write faces-config.xml. Here you mention SpringBeanFacesELResolver as the EL Resolver for your faces application.
After adding these, restart the server to check if configuration is working.


 <context-param>  
     <param-name>contextConfigLocation</param-name>  
     <param-value>  
       /WEB-INF/resources/context.xml  
     </param-value>  
   </context-param>  
      <listener>  
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
   </listener>  
   <listener>  
     <listener-class>  
       org.springframework.web.context.request.RequestContextListener  
     </listener-class>  
   </listener>  

This is the faces-config file
 <?xml version="1.0" encoding="utf-8"?>  
 <faces-config xmlns="http://java.sun.com/xml/ns/javaee"  
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
 http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"  
      version="2.0">  
      <application>  
           <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>  
      </application>  
 </faces-config>  

4.       Add Hibernate to Spring
In your context file, DriverManagerDataSource as data source, hibernate4.LocalSessionFactoryBean as sessionFactory and use this in your DAO classes. Add POJO, hibernate configurations and mappings etc in the project.
Again restart the server and it is in complete configuration.


 <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans  
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
      <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">  
           <property name="driverClassName" value="org.hsqldb.jdbc.JDBCDriver">  
           <property name="url" value="jdbc:hsqldb:hsql://localhost:1521/opt/db">  
           <property name="username" value="SA">  
           <property name="password" value="">  
      </property></property></property></property></bean>  
      <bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">  
           <property name="dataSource" ref="dataSource">  
           <property name="configLocation" value="classpath:hibernate.cfg.xml">  
      </property></property></bean>  
      <bean class="dao.EmployeeDaoImpl" id="employeeDAO">  
           <property name="sessionFactory" ref="sessionFactory">  
      </property></bean>  
      <bean class="service.EmployeeService" id="service">  
           <property name="dao" ref="employeeDAO">  
      </property></bean>  
 </beans>  

Hibernate configuration
 <?xml version="1.0" encoding="utf-8"?>  
 <!DOCTYPE hibernate-configuration SYSTEM   
 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">  
 <hibernate-configuration>  
      <session-factory>  
           <property name="hibernate.dialect">  
                org.hibernate.dialect.HSQLDialect  
           </property>  
           <property name="hibernate.connection.driver_class">  
                org.hsqldb.jdbc.JDBCDriver  
           </property>  
           <!-- Assume test is the database name -->  
           <property name="hibernate.connection.url">  
                jdbc:hsqldb:hsql://localhost:1521/opt/db  
           </property>  
           <property name="hibernate.connection.username">  
                SA  
           </property>  
           <property name="hibernate.connection.password">  
           </property>  
           <!-- List of XML mapping files -->  
           <mapping resource="resources/Employee.hbm.xml" />  
      </session-factory>  
 </hibernate-configuration>  

Mapping
 <?xml version="1.0" encoding="utf-8"?>  
 <!DOCTYPE hibernate-mapping PUBLIC   
  "-//Hibernate/Hibernate Mapping DTD//EN"  
  "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">   
 <hibernate-mapping>  
   <class name="bean.Employee" table="EMPLOYEE">  
    <meta attribute="class-description">  
      This class contains the employee detail.   
    </meta>  
    <id name="sapCode" type="int" column="sap_code">  
      <generator class="native"/>  
    </id>  
    <property name="firstName" column="first_name" type="string"/>  
    <property name="lastName" column="last_name" type="string"/>  
    <property name="middleName" column="middle_name" type="string"/>  
   </class>  
 </hibernate-mapping>  

5.   Retrieve Spring beans in Managed Beans
All the setup is complete. To retrieve Spring beans, in your Managed beans, use @ManagedProperty on attributes.

 package managedbeans;  
 import javax.faces.bean.ManagedBean;  
 import javax.faces.bean.ManagedProperty;  
 import service.EmployeeService;  
 @ManagedBean(name = "editor")  
 public class EditorBean {  
      @ManagedProperty(name = "service", value = "#{service}")  
      private EmployeeService service;  
      private String value = "Editor";  
      /**  
       * @return the value  
       */  
      public String getValue() {  
           return value;  
      }  
      /**  
       * @param value  
       *      the value to set  
       */  
      public void setValue(String value) {  
           this.value = value;  
      }  
      /**  
       * @return the service  
       */  
      public EmployeeService getService() {  
           return service;  
      }  
      /**  
       * @param service  
       *      the service to set  
       */  
      public void setService(EmployeeService service) {  
           this.service = service;  
      }  
      public void save() {  
           System.out.println("Using service");  
           System.out.println(getValue());  
           System.out.println(service.getEmployees());  
      }  
 }  


Enjoy the development with these components. They are really cool stuffs.

I've complete websites built on top of these three only. They really are helpful for faster development, better maintainability, less coding, good looking GUI. You are free to take a look in the below locations,

https://assistant-palash90.rhcloud.com/req-resp.asst

https://temperatureconverter-palash90.rhcloud.com/


That's it. If anything breaks, in between, you can post comment, I will check and revert back.

If this helped you out, you can share this in your network as well. Sharing is caring...


Next
Palash Kanti Kundu