Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Saturday, 27 February 2016

Java 8 Lambda Expressions (Functional Interfaces, Variable Capture, Method References, Default Methods)

In this article we will discuss about most exiting release of Java ever, Java 8 and its new features like Lambda expressions and Streams.

Java 8 Lambda Expressions

In this particular section we will come to know syntax and functioning of Java 8 Lambdas, following are the breakups:

1) Concept
2) Syntax
3) Functional Interfaces
4) Variable Capture
5) Method References
6) Default Methods


Java 8 Lambda Concept

The Mathematica foundation of Lambda Calculus was stated in 1930 and than most of the programming languages started using the concept from 1960 to till data, before Java other languages like C++, Python, JS etc are already having the concept in them.

What are Lambdas good for ? : Lambda expressions are the basics of functional programming; can be used to define anonymous functions, can be assigned to a variable, can be passed to a function and can be returned from a function. Other than this lambda expressions made the parallel programming easier, help programmers to write compact, cleaner and richer data structures code and API's.


Java 8 Lambda Syntax

We have seen what are lambda theoretically, what are other languages already using the concept and how can lambda help us in cleaner code writing; now lets see how Java 8 does it:

Example 1: Printing a list of integers
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
list.forEach(i -> System.out.print(i));

Output: 12345

forEach() is a method that accepts a function as input and calls the function for each value of the collection. i -> System.out.print(i), is an lambda expression, this defines an anonymous function with one parameter i of type Integer.

Example 2: Printing a list of integers by adding 10 to them
 List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

  list.forEach(i -> {
   int addNumber = 10;
   i = i + addNumber;
   System.out.print(i);
  });

Output: 11,12,13,14,15,

As said earlier we can pass a function to forEach(), if we have single line we don't need to put body of the function {} as in Example 1, but for multiple line we need ro put {} as in Example 2. we can define variable, do calculation and everything that can be done in a body of a function.

Example 3: Function parameter with a type
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

list.forEach((Integer i) -> System.out.print(i + ","));

Output: 1,2,3,4,5, We can define the type of parameter “i” as Integer, but that is optional because Java compiler is smart enough to identify the type. Lambda Expression Life cycle Lambda expressions do have a life cycle as well, when compiler sees a lambda expression than it converts it to a function and than calls that function:
i -> System.out.print(i) // lambda expresson 

is converted to:
 public static void generatedNameForLambda(Integer i){
  System.out.println(i);
 }



Java 8 Lambda Functional Interfaces

Any Java developer around the globe has used at least one of the followig interface in their application: java.lang.Runnable, java.awt.event.ActionListener, java.util.Comparator, java.util.concurrent.Callable. These interfaces has one thing in common, that these interfaces had only one method in them. These interfaces can be represented uisng Java 8 Lambda expression. There is a @FunctionalInterface annotation to put on functional interfaces, this will throw an error if put on a wrong implementation of functional interface.
 @FunctionalInterface
 public interface SimpleFuncInterface {
   public void doWork();
 }

So this @FunctionalInterface annotation has a backword compatibility as well, any interface having one method even compiled with Java 1.0 is comatible with Java 8 as a functional interface.

Example 4: Assigning lambda to interfaces

Now we can assign lambda expressions to these functional interfaces as well, we have an functional interface named Consumer in java.util.function:
 public interface Consumer<T>{
  void accept(T t);
 }

We can assign a lambda expression to this Consumer<T> iterface as follows :
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
Consumer<Integer> consumer = i -> System.out.print(i);
list.forEach(consumer);

Output: 12345

Exampel 5: Return an lambda expression
 @FunctionalInterface
 interface Calculator {
  public Integer add(Integer i1, Integer i2);
 }

 public Calculator addNumbers() {
  return (i1, i2) -> i1 + i2;
 }

 public void doSomething(Calculator c) {
  System.out.println(c.add(123, 120));
 }

Calculator c = addNumbers();
doSomething(c);

Output: 243

Here we can see addNumbers() is returning an lambda expression, we have already seen lambda expressions can be assigned or represented as functional interfaces.


Java 8 Lambda Variable Capture

Variable capture is nothing but the ability of lambdas to identify and use variables outside the expression. Local variable

Example 6: Capturing a local variable inside expressions
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int v = 10;
list.forEach(i -> System.out.print((i + v)+","));

Output: 11,12,13,14,15,

This is simple, local variables outside expression can be used easily. But if we try to modify local variables defined outside expression, the compiler will through an exception saying: “local variable v defined in an enclosing scope must be final or effectively final”
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
  int v = 10; 
  list.forEach(i -> {
   v++;  // will not compile
   System.out.print((i + v) + ",");
});


Example 7: Capturing a static variable inside expressions

The same is true with static variables as well:
 static int v = 10;
 public static void main(String[] args) {

  List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
  
  list.forEach(i -> {
   System.out.print((i + v) + ",");
  });
 }

Unlike anonymous inner classes, this keyword in lambda expressions points to the this of enclosing class.


Lambda are not anonymous inner classes

Lambda expressions looks like anonymous inner classes but they are completely different, below are the points in favor of that:

1) Anonymous inner classes can have states in form of class level instance, but lambda can not have that.

2) Anonymous inner classes can have a number of different methods in them, but lambda can have single method only.

3) Keyword “this“ ponts to the object instance of the anonymous inner class but “this” in labda points to the enclosong class.



Java 8 Lambda Method References

So far we have seen, we can pass a anonymous function as a lambda during lambda expressions, but we can also reference an already created function in a lambda expression as follows:

Example 8: Passing a reference of existing method as lambda
public class Impl {
 public static void main(String[] args) {

  // way 1 of passing existing static method as lambda
  Consumer<Integer> consumer1 = i -> doSomething(i);
  consumer1.accept(1);

  // way 2 of passing existing static method as lambda
  Consumer<Integer> consumer2 = Impl::doSomething;
  consumer2.accept(1);
 }

 public static void doSomething(Integer i) {
  System.out.println(i);
 }

}

Output: 1 1

We have an elready created static method doSomething(Integer I), we can pass it to functional interface Consuler<Integer> because both accept(Integer I) and doSomething(Integer I) have same signature. We can do the same in two ways as shown above. In the examples above the code works because Consumer<T> is having accept(Integer I) single paramater of type integer and does not return anything and same is the condition with doSomething(Integer I).

To pass a already exiting method as a function in lambda expressions; the signature of referenced method need to match with signature of functional interface method.

Example 9: Referencing a constructor
A constructor can be passed to a mapper in following two ways:
    // way 1 of passing existing constructor as lambda
  Function<String, Integer> mapper1 = x -> new Integer(x);
  System.out.println(mapper1.apply("12"));

  // way 2 of passing existing constructor as lambda
  Function<String, Integer> mapper2 = Integer::new;
  System.out.println(mapper2.apply("11"));

Output: 1

In the above code we are telling the compiler to create a method and in the body of method accept String parameter and convert it to Integer.


Java 8 default methods in Interfaces

When Java 8 features start building the top most challenge was back support meaning that, every new functionality should not affect existing code.
default void forEach(Consumer action)

For instance we have a java 8 method forEach() in Iterable<T> interface, as per old interface conventions if we have unimplemented methods in an interface than its implementation class has to override it and hence all List implementation were forced to override forEach(). The alternative to that was created with default methods, these methods has not to be implemented by any implementation class forcefully.

Example 10: Default methods
interface InterfaceA{
 public void a();
 default void b(){
  // some implementation
 }
}

class ClassA implements InterfaceA{
 @Override
 public void a() {
  // TODO Auto-generated method stub
  
 }
}

The code written above works fine and does not give any compilation error, we have a non-abstract method in InterfaceA that workds because a new keyword “default” can be used for doing so. Secondly we are not forced to override b() in implementation class InterfaceA. This is where we needed to have default type of methods.

The default methods written in interfaces are already having an impersonation and do not forced the implemented class to inherit them, but one can inherit them as well as in traditional manner and in that case the overridden functionality will be taken into account:
interface InterfaceA {
 public void a();

 default void b() {
  System.out.println("InterfaceA");
 }
}

class ClassA implements InterfaceA {
 @Override
 public void a() {
  // TODO Auto-generated method stub

 }

 @Override
 public void b() {
  System.out.println("ClassA");
 }
}


This is all for this article, we have seen a lot of implmentation od lambda expressions. These expressions keeps the code compact and are very handy while dealing with Java 8 Streams. We will see more bout Java 8 Stream in next examples.

Saturday, 20 February 2016

Java Programming - Introduction

Java is a most commonly used and widely accepted object oriented programming language of today. When it comes to choosing an programming language for companies and individuals to develop a simple or complicated enterprise web application they choose Java. Java is an open source programming language with a support of wide community.


What is Java ?

1) Java is an open source, object oriented programming language originally developed by James Gosling under the roof of Sun Microsystems in 1995.

2) Java applications are platform independent, i.e. any Java program written and compiled on one platform can run on any other platform of same or distinct type.

3) Java can be used for Desktop or Web or middle-ware application development, Core Java, Jsp, Servlet are most commonly used Java variants.

4) Most popular mobile operating system Android applications are written and developed in simple Core Java.


Properties of Java

1) Open-source : Java is an open source programming language, Java source code is open to all and one can change the code and compile again to use Java in its own way.

2) Platform Independent: Java is purely platform independent, any java program written and developed on one platform can run on any other platform without recompiling it.

3) Simple: Java has a very simple and easy to understand syntax, most of the terms are inherited from C and C++ programming languages. One who has studied C or C++ can start with Java in no time.

4) Secure: Java is secure, one can write virus free, authentic and secure code with help of Java authentication and security mechanism.

5) Multi-threaded: Java is a multi threaded programming language, that means one can write a effective multi threaded application in Java to utilize most of CPU and memory.

6) Distributed: Java OS designed to be used in a network distributed way, RMI is an example of Java's distributed way of working.

7) Dynamic: Despite a lot of other features Java also has a dynamic nature, It is considered more dynamic than C and C++ because of its adopting nature towards changing technology.


Java tools

One can start write code in Java even with notepad, as far as JDK is installed on the system, although more sofesticated and managed IDE's are also there like, Eclipse, Netbeans and intellij.

Saturday, 15 November 2014

How First Level Caching Works in Hibernate - Example

In computer science Caching is a practice that stores data in memory to increase performance by reducing the number of database hits. In a caching procedure we stores frequently asked data into memory so than next time a similar request came to the application the data can be served from the cache memory without fetching it again and again from the database. It helps us to reduce the number of database hits and hence increases performance.


Caching in Hibernate

While Hibernate proved itself an efficient and useful tool in Java community, it provides three type of in build caching techniques, we call them First level caching, Second level caching and Query Caching.


First Level Caching in Hibernate

First Level Caching is enabled by default and we don’t need to do anything to achieve it, in fact we can’t even disable it from there. First level caching is also called Session Level Caching meaning that it works for a session only, in case same query is being executed two or more times in a single session it gets data from the DB for the very first request only and serves the same data from cache for all upcoming similar requests.


How First Level Caching Works in Hibernate

First level cache is associated with sessions only, when the query is executed first time it gets the data from the database and save that data to cache memory. The data that is stored in cache at first occurrence of query is being served for all upcoming similar requests until the session is alive.



Once a session is closed all first level cache are cleared. We can remove a particular loaded entity from the cache using evict() and entire cache can be cleared using clear(). Once the cache is cleared with any of the two methods it will query to the database again for a new call even if the session is not closed yet.

src\main\java\com\beingjavaguys\sample\CachingImpl.java
package com.beingjavaguys.sample;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.beingjavaguys.models.Employee;
import com.beingjavaguys.utils.HibernateUtils;

/**
 * @author Nagesh.Chauhan
 *
 */
public class CachingImpl {
 public static void main(String[] args) {
  SessionFactory sessionFactory = HibernateUtils.getSessionFactory();

  // create an employee object to persist in DB
  Employee employee = new Employee("eddy", "smith",
    "eddy@beingjavaguys.com", "9898787676");

  // lets save few data in Employee table
  Session session = sessionFactory.openSession();
  Transaction transaction = session.beginTransaction();
  session.save(employee);
  transaction.commit();
  session.close();

  System.out.println("****Data creation completed****");

  Session session1 = sessionFactory.openSession();
  System.out.println("****Created Session 1****");
  transaction = session1.beginTransaction();

  employee = (Employee) session1.load(Employee.class, 1l);
  System.out.println(employee.getFirstName());

  employee = (Employee) session1.load(Employee.class, 1l);
  System.out.println(employee.getFirstName());

  employee = (Employee) session1.load(Employee.class, 1l);
  System.out.println(employee.getFirstName());

  transaction.commit();
  session1.close();
  System.out.println("****Closed Session 1****");

  Session session2 = sessionFactory.openSession();
  System.out.println("****Created Session 2****");
  transaction = session2.beginTransaction();

  employee = (Employee) session2.load(Employee.class, 1l);
  System.out.println(employee.getFirstName());

  transaction.commit();
  session2.close();
  System.out.println("****Closed Session 2****");

 }
}

****Created Session 1****
Hibernate: select employee0_.ID as ID1_0_0_, employee0_.EMAIL as EMAIL2_0_0_, employee0_.FIRST_NAME as FIRST_NA3_0_0_, employee0_.LAST_NAME as LAST_NAM4_0_0_, employee0_.PHONE as PHONE5_0_0_ from EMPLOYEE employee0_ where employee0_.ID=?
eddy
eddy
eddy
****Closed Session 1****
****Created Session 2****
Hibernate: select employee0_.ID as ID1_0_0_, employee0_.EMAIL as EMAIL2_0_0_, employee0_.FIRST_NAME as FIRST_NA3_0_0_, employee0_.LAST_NAME as LAST_NAM4_0_0_, employee0_.PHONE as PHONE5_0_0_ from EMPLOYEE employee0_ where employee0_.ID=?
eddy
****Closed Session 2****


You can see that for session1 we have requested the entity three times but the query is being executed only once and for second and third request the data saved in the cache is served. We closed the session1 and created new session2, this time we requested same entity from database but it went to get data from DB because the cached data is cleared when session1 get closed. Here is what happened.

1) We requested for the Employee entity first time, hibernate checked if the object is available on first level cache; the object is not there so the entity is requested from the database. And a copy of that is stored on cache.

2) Now second request came for employee entity, this time the entity was present on cache so no db call made and entity served from the cache.

3) Now third request came for employee entity, this time the entity was present on cache so no db call made and entity served from the cache.

4) Session (session1) is closed so all the first level cache data associated with is removed.

5) A new session (session2) being created.

6) A request came to get employee entity, hibernate checked if the object is available on first level cache, the object is not there so the entity is requested from form the database. And a copy of that is stored on cache.


How evict() and clear() works in hibernate

We can’t disable first level cache in hibernate but we can clear a particular entity cache with evict() and whole cache with clear(). The example below explains the same.

src\main\java\com\beingjavaguys\sample\EvictImpl.java
package com.beingjavaguys.sample;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.beingjavaguys.models.Employee;
import com.beingjavaguys.utils.HibernateUtils;

/**
 * @author Nagesh.Chauhan
 *
 */
public class EvictImpl {
 public static void main(String[] args) {
  SessionFactory sessionFactory = HibernateUtils.getSessionFactory();

  // create an employee object to persist in DB
  Employee employee = new Employee("eddy", "smith",
    "eddy@beingjavaguys.com", "9898787676");

  // lets save few data in Employee table
  Session session = sessionFactory.openSession();
  Transaction transaction = session.beginTransaction();
  session.save(employee);
  transaction.commit();
  session.close();

  System.out.println("****Data creation completed****");

  Session session1 = sessionFactory.openSession();
  System.out.println("****Created Session****");
  transaction = session1.beginTransaction();

  employee = (Employee) session1.load(Employee.class, 1l);
  System.out.println(employee.getFirstName());

  employee = (Employee) session1.load(Employee.class, 1l);
  System.out.println(employee.getFirstName());

  // removed employee entity from the cache
  session1.evict(employee);
  System.out.println("****removed employee entity from the cache****");

  employee = (Employee) session1.load(Employee.class, 1l);
  System.out.println(employee.getFirstName());

  transaction.commit();
  session1.close();
  System.out.println("****Closed Session****");

 }
}

****Created Session****
Hibernate: select employee0_.ID as ID1_0_0_, employee0_.EMAIL as EMAIL2_0_0_, employee0_.FIRST_NAME as FIRST_NA3_0_0_, employee0_.LAST_NAME as LAST_NAM4_0_0_, employee0_.PHONE as PHONE5_0_0_ from EMPLOYEE employee0_ where employee0_.ID=?
eddy
eddy
****removed employee entity from the cache****
Hibernate: select employee0_.ID as ID1_0_0_, employee0_.EMAIL as EMAIL2_0_0_, employee0_.FIRST_NAME as FIRST_NA3_0_0_, employee0_.LAST_NAME as LAST_NAM4_0_0_, employee0_.PHONE as PHONE5_0_0_ from EMPLOYEE employee0_ where employee0_.ID=?
eddy
****Closed Session****


We can see that, we requested employee entity three times again, here is what happened :

1) We requested for the Employee hibernate checked if the object is available on first level cache, the object is not there so the entity is requested from form the database. And a copy of that is stored on cache.

2) Next time same request came for employee entity, this time the entity was present on cache so no db call made and entity served from the cache.

3) A request came to remove entity from the cache, now cache does not have a cached entity.

4) Third request came to get employee entity, hibernate checked if the object is available on first level cache, the object is not there so the entity is requested from form the database. And a copy of that is stored on cache. We look into how evict() works for hibernate, clear works in the same way except that clear() removes all the entities form the cache.


Here we are done with how first level cache works in hibernate and how evict() and clear() works in hibernate. We came to know how we can clear hibernate cache using evict() and clear(). In coming articles we will see how to what is second level caching and query caching in hibernate.

Complete Source Code and Configuration can be found in the attached sample project. Download it from Here: Download Source Code









Thanks for reading !
Being Java Guys Team

Download How First Level Caching Works in Hibernate Project





Saturday, 18 October 2014

Securing Restful Web Services with Spring Security and OAuth2 (Spring Security + OAuth2 + Spring Rest)

OAuth (Open Authentication) is an open standard or kind of protocol that lets one site to share its content with some other site without sharing credentials.

The source code of this application can be found on Git Hub: Source Code

In this post we will discuss how to secure Restful Web Services using Spring security and OAuth2, we will use Spring Security to validate a user on server and OAuth to manage authentication tokens to be used in communication. After applying this implementation only authenticated users and applications will get a valid access token from OAuth and using that token the user can access authorized API’s on server.


The flow of application will go something like this:

1) User sends a GET request to server with five parameters: grant_type, username, password, client_id, client_secret; something like this:
http://localhost:8080/SpringRestSecurityOauth/oauth/token?grant_type=password&client_id=restapp&client_secret=restapp&username=beingjavaguys&password=spring@java


2) Server validates the user with help of spring security, and if the user is authenticated, OAuth generates a access token and send sends back to user in following format.

{
"access_token": "22cb0d50-5bb9-463d-8c4a-8ddd680f553f",
"token_type": "bearer",
"refresh_token": "7ac7940a-d29d-4a4c-9a47-25a2167c8c49",
"expires_in": 119
}
Here we got access_token for further communication with server or to get some protected resourses(API’s), it mentioned a expires_in time that indicates the validation time of the token and a refresh_token that is being used to get a new token when token is expired.


3) We access protected resources by passing this access token as a parameter, the request goes something like this:
http://localhost:8080/SpringRestSecurityOauth/api/users/?access_token=8c191a0f-ebe8-42cb-bc18-8e80f2c4238e

Here http://localhost:8080/SpringRestSecurityOauth is the server path, and /api/users/ Is an API URL that returns a list of users and is being protected to be accessed.


4) If the token is not expired and is a valid token, the requested resources will be returned.

5) In case the token is expired, user needs to get a new token using its refreshing token that was accepted in step(2). A new access token request after expiration looks something like this:
http://localhost:8080/SpringRestSecurityOauth/oauth/token?grant_type=refresh_token&client_id=restapp&client_secret=restapp&refresh_token=7ac7940a-d29d-4a4c-9a47-25a2167c8c49
And you will get a new access token along with a new refresh token.


Integrating Spring Security with OAuth2 to secure Restful Web Services.

In this section we will see how the application works and how to integrate Spring Security with OAuth2, so for now we have a simple Spring Rest structure that returns a list of users for authenticated user, we have a simple spring controller that’s taking the responsibility:

More on @ResponseBody : Here

\src\main\java\com\beingjavaguys\controllers\RestController.java
package com.beingjavaguys.controllers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.beingjavaguys.models.User;
import com.beingjavaguys.services.DataService;

/**
 * @author Nagesh.Chauhan
 *
 */
@Controller
@RequestMapping("/api/users")
public class RestController {

 @Autowired
 DataService dataService;

 @RequestMapping(value = "/", method = RequestMethod.GET)
 @ResponseBody
 public List list() {
  return dataService.getUserList();

 }
}

The code is self explainer, we are having an URI (/api/users/) to be accessed by a GET request and it will return a list of users as a response.


We are using simple service structure to get data, for now the data is being returned in a harcoded way but it can be kind of dynamic of from database.

More on Spring Rest Web Services : Here

\src\main\java\com\beingjavaguys\services\DataService.java
package com.beingjavaguys.services;

import java.util.List;

import com.beingjavaguys.models.User;
/**
 * @author Nagesh.Chauhan
 *
 */
public interface DataService {
 public List getUserList();
}


\src\main\java\com\beingjavaguys\services\DataServiceImpl.java We have created three users and added them to a list, this list will be accessed to authenticated users only with the help of auhentication OAuth token.
package com.beingjavaguys.services;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.beingjavaguys.models.User;
/**
 * @author Nagesh.Chauhan
 *
 */
@Service
public class DataServiceImpl implements DataService {

 @Override
 public List getUserList() {
  
  // preparing user list with few hard coded values
  List userList = new ArrayList();
  
  userList.add(new User(1, "user_a", "user_a@example.com", "9898989898"));
  userList.add(new User(2, "user_b", "user_b@example.com", "9767989898"));
  userList.add(new User(3, "user_c", "user_c@example.com", "9898459898"));
  
  return userList;
 }

}



Dependencies required to integrate Spring MVC , Spring Security and OAuth2

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.beingjavaguys.sample</groupId>
 <artifactId>SpringRestSecurityOauth</artifactId>
 <packaging>war</packaging>
 <version>1.0-SNAPSHOT</version>
 <name>SpringRestSecurityOauth Maven Webapp</name>
 <url>http://maven.apache.org</url>
 <!-- @author Nagesh.Chauhan(neel4soft@gmail.com) -->
 <properties>
  <spring.version>4.0.7.RELEASE</spring.version>
  <log4j.version>1.2.17</log4j.version>
  <jdk.version>1.7</jdk.version>
  <context.path>SpringRestSecurityOauth</context.path>
  <spring.security.version>3.2.5.RELEASE</spring.security.version>
 </properties>
 <build>
  <finalName>${pom.artifactId}</finalName>
  <plugins>
   <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
  </plugins>
 </build>
 <dependencies>

  <dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-io</artifactId>
   <version>1.3.2</version>
  </dependency>

  <!-- log4j -->
  <dependency>
   <groupId>log4j</groupId>
   <artifactId>log4j</artifactId>
   <version>${log4j.version}</version>
  </dependency>


  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-web</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>

  <!-- Spring Security -->
  <dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-web</artifactId>
   <version>${spring.security.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-config</artifactId>
   <version>${spring.security.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework.security.oauth</groupId>
   <artifactId>spring-security-oauth2</artifactId>
   <version>1.0.0.RELEASE</version>
  </dependency>
  <dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>2.2.2</version>
  </dependency>
  <dependency>
   <groupId>org.codehaus.jackson</groupId>
   <artifactId>jackson-mapper-asl</artifactId>
   <version>1.9.10</version>
  </dependency>
  <dependency>
   <groupId>commons-httpclient</groupId>
   <artifactId>commons-httpclient</artifactId>
   <version>3.1</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context-support</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.0.1</version>
   <scope>provided</scope>
  </dependency>
 </dependencies>
</project>



Spring security OAuth configuration

Now this is where the actual thing is happening, we need to configure a number of thing in this security configuration file:
\src\main\webapp\WEB-INF\spring-security.xml
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:sec="http://www.springframework.org/schema/security" xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd
  http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd 
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd ">

 <!-- @author Nagesh.Chauhan(neel4soft@gmail.com) -->
 <!-- This is default url to get a token from OAuth -->
 <http pattern="/oauth/token" create-session="stateless"
  authentication-manager-ref="clientAuthenticationManager"
  xmlns="http://www.springframework.org/schema/security">
  <intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" />
  <anonymous enabled="false" />
  <http-basic entry-point-ref="clientAuthenticationEntryPoint" />
  <!-- include this only if you need to authenticate clients via request 
   parameters -->
  <custom-filter ref="clientCredentialsTokenEndpointFilter"
   after="BASIC_AUTH_FILTER" />
  <access-denied-handler ref="oauthAccessDeniedHandler" />
 </http>

 <!-- This is where we tells spring security what URL should be protected 
  and what roles have access to them -->
 <http pattern="/api/**" create-session="never"
  entry-point-ref="oauthAuthenticationEntryPoint"
  access-decision-manager-ref="accessDecisionManager"
  xmlns="http://www.springframework.org/schema/security">
  <anonymous enabled="false" />
  <intercept-url pattern="/api/**" access="ROLE_APP" />
  <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
  <access-denied-handler ref="oauthAccessDeniedHandler" />
 </http>


 <bean id="oauthAuthenticationEntryPoint"
  class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
  <property name="realmName" value="test" />
 </bean>

 <bean id="clientAuthenticationEntryPoint"
  class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
  <property name="realmName" value="test/client" />
  <property name="typeName" value="Basic" />
 </bean>

 <bean id="oauthAccessDeniedHandler"
  class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />

 <bean id="clientCredentialsTokenEndpointFilter"
  class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
  <property name="authenticationManager" ref="clientAuthenticationManager" />
 </bean>

 <bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased"
  xmlns="http://www.springframework.org/schema/beans">
  <constructor-arg>
   <list>
    <bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
    <bean class="org.springframework.security.access.vote.RoleVoter" />
    <bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
   </list>
  </constructor-arg>
 </bean>

 <authentication-manager id="clientAuthenticationManager"
  xmlns="http://www.springframework.org/schema/security">
  <authentication-provider user-service-ref="clientDetailsUserService" />
 </authentication-manager>


 <!-- This is simple authentication manager, with a hardcoded user/password 
  combination. We can replace this with a user defined service to get few users 
  credentials from DB -->
 <authentication-manager alias="authenticationManager"
  xmlns="http://www.springframework.org/schema/security">
  <authentication-provider>
   <user-service>
    <user name="beingjavaguys" password="spring@java" authorities="ROLE_APP" />
   </user-service>
  </authentication-provider>
 </authentication-manager>

 <bean id="clientDetailsUserService"
  class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
  <constructor-arg ref="clientDetails" />
 </bean>


 <!-- This defined token store, we have used inmemory tokenstore for now 
  but this can be changed to a user defined one -->
 <bean id="tokenStore"
  class="org.springframework.security.oauth2.provider.token.InMemoryTokenStore" />

 <!-- This is where we defined token based configurations, token validity 
  and other things -->
 <bean id="tokenServices"
  class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
  <property name="tokenStore" ref="tokenStore" />
  <property name="supportRefreshToken" value="true" />
  <property name="accessTokenValiditySeconds" value="120" />
  <property name="clientDetailsService" ref="clientDetails" />
 </bean>

 <bean id="userApprovalHandler"
  class="org.springframework.security.oauth2.provider.approval.TokenServicesUserApprovalHandler">
  <property name="tokenServices" ref="tokenServices" />
 </bean>

 <oauth:authorization-server
  client-details-service-ref="clientDetails" token-services-ref="tokenServices"
  user-approval-handler-ref="userApprovalHandler">
  <oauth:authorization-code />
  <oauth:implicit />
  <oauth:refresh-token />
  <oauth:client-credentials />
  <oauth:password />
 </oauth:authorization-server>

 <oauth:resource-server id="resourceServerFilter"
  resource-id="test" token-services-ref="tokenServices" />

 <oauth:client-details-service id="clientDetails">
  <!-- client -->
  <oauth:client client-id="restapp"
   authorized-grant-types="authorization_code,client_credentials"
   authorities="ROLE_APP" scope="read,write,trust" secret="secret" />

  <oauth:client client-id="restapp"
   authorized-grant-types="password,authorization_code,refresh_token,implicit"
   secret="restapp" authorities="ROLE_APP" />

 </oauth:client-details-service>

 <sec:global-method-security
  pre-post-annotations="enabled" proxy-target-class="true">
  <!--you could also wire in the expression handler up at the layer of the 
   http filters. See https://jira.springsource.org/browse/SEC-1452 -->
  <sec:expression-handler ref="oauthExpressionHandler" />
 </sec:global-method-security>

 <oauth:expression-handler id="oauthExpressionHandler" />
 <oauth:web-expression-handler id="oauthWebExpressionHandler" />
</beans>



Spring configuration file

This is nothing more that a very simple spring configuration file, it just loads Spring web app context in the container, we can configure spring related thing here:
\src\main\webapp\WEB-INF\mvc-dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<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:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
 <!-- @author Nagesh.Chauhan(neel4soft@gmail.com) -->
 <context:component-scan base-package="com.beingjavaguys" />
 <mvc:annotation-driven />
</beans>


Deployment descriptor

This is simple web.xml file that lets the container know that all upcoming requests will be handled by spring itself, we have passed location of configuration files and added a spring security filter over here. This filter is intercepting all requests to be authenticated by security context. \src\main\webapp\WEB-INF\web.xml
<web-app 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-app_2_5.xsd"
 version="2.5">

 <display-name>Sample Spring Maven Project</display-name>
 <!-- @author Nagesh.Chauhan(neel4soft@gmail.com) -->

 <servlet>
  <servlet-name>mvc-dispatcher</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>mvc-dispatcher</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>  
            /WEB-INF/mvc-dispatcher-servlet.xml,  
            /WEB-INF/spring-security.xml
        </param-value>
 </context-param>

 <!-- Spring Security -->

 <filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
 </filter>

 <filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

</web-app>


Domain classes

Here is a single domain class, whose objects are going to be returned in json format:
\src\main\java\com\beingjavaguys\models\User.java
package com.beingjavaguys.models;
/**
 * @author Nagesh.Chauhan
 *
 */
public class User {
 private int id;
 private String name;
 private String email;
 private String phone;

 public User() {
  super();
  // TODO Auto-generated constructor stub
 }

 public User(int id, String name, String email, String phone) {
  super();
  this.id = id;
  this.name = name;
  this.email = email;
  this.phone = phone;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public String getPhone() {
  return phone;
 }

 public void setPhone(String phone) {
  this.phone = phone;
 }

}

This is all about, securing restful web services with spring security and oauth2, in this article we look into how to configure spring security with oauth2 to use a token based authentication mechanism. In upcoming articles we will see more about security in java EE applications.

Download complete Project : Git Hub









Thanks for reading !
Being Java Guys Team

Get Spring Security and OAuth2 Integration Source Code from Git Hub





Sunday, 31 August 2014

Spring Security with Hibernate using Maven - Authentication and Authorization Example

In our previous discussions we came across a number of implementations in Spring Security, What is Spring Security, Login & Logout with Spring Security, Spring Security Authentication and Authorization

In this particular blog we will see how to configure Spring Security with Hibernate to accomplish Authentication and Authorization in our application. We will use a maven web project for the purpose, we have just created a simple maven web project and imported it in Eclipse.

More Details on : Dynamic Web Project with Maven and Import it in eclipse


Database Setup for Spring Security and Hibernate Integration

Before we go forward let's first create a database and required tables to store and get user credential from, we have created two tables "users" and "user_roles". We have added two users details, with ROLE_USER and ROLE_ADMIN to be used here. Just copy and execute the below script in your mysql query editor to get a db setup for you.

-- Dumping database structure for spring_social_db
CREATE DATABASE IF NOT EXISTS `spring_social_db` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `spring_social_db`;


-- Dumping structure for table spring_social_db.users
CREATE TABLE IF NOT EXISTS `users` (
  `username` varchar(45) NOT NULL,
  `enabled` bit(1) NOT NULL,
  `password` varchar(60) NOT NULL,
  PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- Dumping data for table spring_social_db.users: ~2 rows (approximately)
/*!40000 ALTER TABLE `users` DISABLE KEYS */;
INSERT INTO `users` (`username`, `enabled`, `password`) VALUES
 ('admin', b'10000000', 'admin@123'),
 ('user', b'10000000', 'user@123');
/*!40000 ALTER TABLE `users` ENABLE KEYS */;


-- Dumping structure for table spring_social_db.user_roles
CREATE TABLE IF NOT EXISTS `user_roles` (
  `user_role_id` int(11) NOT NULL AUTO_INCREMENT,
  `role` varchar(45) NOT NULL,
  `username` varchar(45) NOT NULL,
  PRIMARY KEY (`user_role_id`),
  KEY `FK_9ry105icat2dux14oyixybw9l` (`username`),
  CONSTRAINT `FK_9ry105icat2dux14oyixybw9l` FOREIGN KEY (`username`) REFERENCES `users` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

-- Dumping data for table spring_social_db.user_roles: ~3 rows (approximately)
/*!40000 ALTER TABLE `user_roles` DISABLE KEYS */;
INSERT INTO `user_roles` (`user_role_id`, `role`, `username`) VALUES
 (1, 'ROLE_ADMIN', 'admin'),
 (2, 'ROLE_USER', 'user'),
 (3, 'ROLE_USER', 'admin');
/*!40000 ALTER TABLE `user_roles` ENABLE KEYS */;
/*!40014 SET FOREIGN_KEY_CHECKS=1 */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;

If everything goes right you will see following table structures.




Dependencies required for Spring Security with Hibernate integration

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.beingjavaguys.sample</groupId>
 <artifactId>SP_SC_Hibernate</artifactId>
 <packaging>war</packaging>
 <version>1.0-SNAPSHOT</version>
 <name>SP_SC_Hibernate Maven Webapp</name>
 <url>http://maven.apache.org</url>
 <properties>
  <spring.version>4.0.6.RELEASE</spring.version>
  <hibernate.version>4.3.6.Final</hibernate.version>
  <log4j.version>1.2.17</log4j.version>
  <jdk.version>1.7</jdk.version>
  <jstl.version>1.2</jstl.version>
  <mysql_connector.version>5.1.6</mysql_connector.version>
  <spring.security.version>3.2.5.RELEASE</spring.security.version>
  <context.path>SP_SC_Hibernate</context.path>
 </properties>
 <build>
  <finalName>${pom.artifactId}</finalName>
  <plugins>
   <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
  </plugins>
 </build>
 <dependencies>

  <!-- hibernate -->
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>${hibernate.version}</version>
  </dependency>

  <!-- log4j -->
  <dependency>
   <groupId>log4j</groupId>
   <artifactId>log4j</artifactId>
   <version>${log4j.version}</version>
  </dependency>

  <!-- Spring -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-orm</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-web</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>

  <!-- Spring Security -->
  <dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-web</artifactId>
   <version>${spring.security.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-config</artifactId>
   <version>${spring.security.version}</version>
  </dependency>

  <!-- Spring Security JSP Taglib -->
  <dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-taglibs</artifactId>
   <version>${spring.security.version}</version>
  </dependency>

  <!-- jstl -->
  <dependency>
   <groupId>jstl</groupId>
   <artifactId>jstl</artifactId>
   <version>${jstl.version}</version>
  </dependency>

  <!-- mysql driver -->
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>${mysql_connector.version}</version>
  </dependency>
 </dependencies>
</project>




\src\main\webapp\WEB-INF\web.xml
We need to make an Spring entry to web.xml, this will tell the container that all upcoming requests will be served by Spring Framework itself as per the configuration. We have also added a filter entry to integrate spring security in the application.
<web-app 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-app_2_5.xsd"
 version="2.5">

 <display-name>Sample Spring Maven Project</display-name>
<!-- Spring MVC -->  
  
    <servlet>  
        <servlet-name>mvc-dispatcher</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>mvc-dispatcher</servlet-name>  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  
  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>  
            /WEB-INF/mvc-dispatcher-servlet.xml,  
            /WEB-INF/spring-security.xml  
        </param-value>  
  
    </context-param>  

 <!-- Spring Security -->

 <filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
 </filter>

 <filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

</web-app>


\src\main\webapp\WEB-INF\spring-config.xml
This is simple spring configuration file, we have added entry for base-package here to search and find Controller, Dao and Service classes with annotations. We defined few beans here for hibernate configurations and a datasource bean to connect with database.

More details on : Spring Hibernate Integration
<?xml version="1.0" encoding="UTF-8"?>
<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:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

 <context:component-scan base-package="com.beingjavaguys" />
 <context:property-placeholder location="classpath:database.properties" />
 <mvc:resources mapping="/resources/**" location="/resources/" />
 <mvc:annotation-driven />

 <bean id="dataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="${database.driver}" />
  <property name="url" value="${database.url}" />
  <property name="username" value="${database.user}" />
  <property name="password" value="${database.password}" />
 </bean>

 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="annotatedClasses">
   <list>
    <value>com.beingjavaguys.models.login.Users</value>
    <value>com.beingjavaguys.models.login.UserRole</value>
   </list>
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
    <prop key="hibernate.hbm2ddl.auto">update</prop>
   </props>
  </property>
 </bean>

 <bean id="txManager"
  class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
 </bean>

 <bean id="persistenceExceptionTranslationPostProcessor"
  class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

 <bean
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix">
   <value>/WEB-INF/pages/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>
</beans>

Spring security configuration file

\src\main\webapp\WEB-INF\spring-security.xml

Here is spring-security configuration file with all required configurations and settings, we have defioned two roles here and a service "loginService" bean to communicate with data layer of the application.
<beans:beans xmlns="http://www.springframework.org/schema/security"
 xmlns:beans="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
 http://www.springframework.org/schema/security
 http://www.springframework.org/schema/security/spring-security-3.2.xsd">

 <!-- enable use-expressions -->
 <http auto-config="true" use-expressions="true">
  <intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />
  <intercept-url pattern="/user**" access="hasRole('ROLE_USER')" />

  <!-- access denied page -->
  <access-denied-handler error-page="/403" />
  <form-login login-page="/login" authentication-failure-url="/login?error"
   username-parameter="username" password-parameter="password" />
  <logout logout-success-url="/login?logout" />
  <!-- enable csrf protection -->
  <csrf />
 </http>

 <authentication-manager>
  <authentication-provider user-service-ref="loginService" />
 </authentication-manager>

</beans:beans>


Login controller code

\src\main\java\com\beingjavaguys\controller\LoginController.java

This is simple spring mvc controller having request mappings to deal with different incoming request and render appropriate pages used in the login process.
package com.beingjavaguys.controller;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.beingjavaguys.models.login.Users;

@Controller
public class LoginController {

 @RequestMapping(value = { "/", "/home" })
 public String getUserDefault() {
  return "home";
 }

 @RequestMapping("/login")
 public ModelAndView getLoginForm(@ModelAttribute Users users,
   @RequestParam(value = "error", required = false) String error,
   @RequestParam(value = "logout", required = false) String logout) {

  String message = "";
  if (error != null) {
   message = "Incorrect username or password !";
  } else if (logout != null) {
   message = "Logout successful !";
  }
  return new ModelAndView("login", "message", message);
 }

 @RequestMapping("/admin**")
 public String getAdminProfile() {
  return "admin";
 }

 @RequestMapping("/user**")
 public String getUserProfile() {
  return "user";
 }

 @RequestMapping("/403")
 public ModelAndView getAccessDenied() {
  Authentication auth = SecurityContextHolder.getContext()
    .getAuthentication();
  String username = "";
  if (!(auth instanceof AnonymousAuthenticationToken)) {
   UserDetails userDetail = (UserDetails) auth.getPrincipal();
   username = userDetail.getUsername();
  }

  return new ModelAndView("403", "username", username);
 }

}



Model classes to represent "user" and "user_role" tables in database

\src\main\java\com\beingjavaguys\models\login\Users.java

package com.beingjavaguys.models.login;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "users", catalog = "spring_social_db")
public class Users {

 @Id
 @Column(name = "username", unique = true, nullable = false, length = 45)
 private String username;

 @Column(name = "password", nullable = false, length = 60)
 private String password;

 @Column(name = "enabled", nullable = false)
 private boolean enabled;

 @OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
 private Set userRole = new HashSet(0);

 
 public String getUsername() {
  return username;
 }

 public void setUsername(String username) {
  this.username = username;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public boolean isEnabled() {
  return enabled;
 }

 public void setEnabled(boolean enabled) {
  this.enabled = enabled;
 }

 public Set getUserRole() {
  return userRole;
 }

 public void setUserRole(Set userRole) {
  this.userRole = userRole;
 }
}


\src\main\java\com\beingjavaguys\models\login\UserRole.java
package com.beingjavaguys.models.login;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "user_roles", catalog = "spring_social_db")
public class UserRole {

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name = "user_role_id", unique = true, nullable = false)
 private Integer userRoleId;

 @ManyToOne(fetch = FetchType.LAZY)
 @JoinColumn(name = "username", nullable = false)
 private Users user;

 @Column(name = "role", nullable = false, length = 45)
 private String role;

 public Integer getUserRoleId() {
  return userRoleId;
 }

 public void setUserRoleId(Integer userRoleId) {
  this.userRoleId = userRoleId;
 }

 public Users getUser() {
  return user;
 }

 public void setUser(Users user) {
  this.user = user;
 }

 public String getRole() {
  return role;
 }

 public void setRole(String role) {
  this.role = role;
 }

}



Data Layer for Spring Security and Hibernate Configuration

\src\main\java\com\beingjavaguys\dao\login\LoginDao.java
package com.beingjavaguys.dao.login;

import com.beingjavaguys.models.login.Users;



public interface LoginDao {
 Users findByUserName(String username);
}

\src\main\java\com\beingjavaguys\dao\login\LoginDaoImpl.java
package com.beingjavaguys.dao.login;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.beingjavaguys.models.login.Users;

@Repository("loginDao")
public class LoginDaoImpl implements LoginDao{
 
 @Autowired
 SessionFactory sessionFactory;

 Session session = null;
 Transaction tx = null;

 @Override
 public Users findByUserName(String username) {
  session = sessionFactory.openSession();
  tx = session.getTransaction();
  session.beginTransaction();
  Users user = (Users) session.load(Users.class, new String(username));
  tx.commit();
  return user;
 }

}



\src\main\java\com\beingjavaguys\service\login\LoginServiceImpl.java
package com.beingjavaguys.service.login;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.beingjavaguys.dao.login.LoginDao;
import com.beingjavaguys.models.login.UserRole;
import com.beingjavaguys.models.login.Users;

@Service("loginService")
public class LoginServiceImpl implements UserDetailsService {

 @Autowired
 LoginDao loginDao;

 @Override
 public UserDetails loadUserByUsername(String username)
   throws UsernameNotFoundException {

  Users user = loginDao.findByUserName(username);

  List authorities = buildUserAuthority(user
    .getUserRole());

  return buildUserForAuthentication(user, authorities);
 }

 private User buildUserForAuthentication(Users user,
   List authorities) {
  return new User(user.getUsername(), user.getPassword(),
    user.isEnabled(), true, true, true, authorities);
 }

 private List buildUserAuthority(Set userRoles) {

  Set setAuths = new HashSet();

  // Build user's authorities
  for (UserRole userRole : userRoles) {
   setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
  }

  List Result = new ArrayList(
    setAuths);

  return Result;
 }

}



Front End Layer files

Login Form \src\main\webapp\WEB-INF\pages\login.jsp
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Login | Beingjavaguys.com</title>
</head>
<body>
 <center>
  <br /> <br /> <br />
  <div style="border: 1px solid black; width: 300px; padding-top: 10px;">
   <br /> Please enter your username and password to login ! <br /> <span
    style="color: red">${message}</span> <br />
   <form:form method="post" action="j_spring_security_check"
    modelAttribute="users">
    <table>
     <tr>
      <td>Username:</td>
      <td><form:input path="username" /></td>
     </tr>
     <tr>
      <td>Password:</td>
      <td><form:input path="password" /></td>
     </tr>
     <tr>
      <td> </td>
      <td><input type="submit" /></td>
     </tr>
    </table>
   </form:form>
  </div>
 </center>

</body>
</html>


\src\main\webapp\WEB-INF\pages\home.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Home Page | Beingjavaguys.com</title>
</head>
<body>
 <center>
  <br /> <br /> <br />
  <h1>Default Logged in User page !!!</h1>
  <c:url var="logoutUrl" value="j_spring_security_logout" />
  <form action="${logoutUrl}" method="post">
   <input type="submit" value="Log out" /> <input type="hidden"
    name="${_csrf.parameterName}" value="${_csrf.token}" />
  </form>
 </center>

</body>
</html>


\src\main\webapp\WEB-INF\pages\admin.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Admin Profile Page | Beingjavaguys.com</title>
</head>
<body>
 <center>
  <br /> <br /> <br />
  <h1>Admin profile page !!!</h1>
  <c:url var="logoutUrl" value="j_spring_security_logout" />
  <form action="${logoutUrl}" method="post">
   <input type="submit" value="Log out" /> <input type="hidden"
    name="${_csrf.parameterName}" value="${_csrf.token}" />
  </form>
 </center>

</body>
</html>


\src\main\webapp\WEB-INF\pages\user.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>User Profile Page | Beingjavaguys.com</title>
</head>
<body>
 <center>
  <br /> <br /> <br />
  <h1>User profile page !!!</h1>
  <c:url var="logoutUrl" value="j_spring_security_logout" />
  <form action="${logoutUrl}" method="post">
   <input type="submit" value="Log out" /> <input type="hidden"
    name="${_csrf.parameterName}" value="${_csrf.token}" />
  </form>
 </center>

</body>
</html>


\src\main\webapp\WEB-INF\pages\403.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Access Denied | Beingjavaguys.com</title>
</head>
<body>
 <center>
  <br /> <br /> <br />
  <h1>
   Access Denied for User : <span style="color: red;">${username}</span>
  </h1>
  <c:url var="logoutUrl" value="j_spring_security_logout" />
  <form action="${logoutUrl}" method="post">
   <input type="submit" value="Log out" /> <input type="hidden"
    name="${_csrf.parameterName}" value="${_csrf.token}" />
  </form>
 </center>

</body>
</html>


How to run the application

Once you are donw with adding all required file to the project, simple run the application on server and hit following URL: http://localhost:8080/SP_SC_Hibernate/user

It will redirect you to login page (http://localhost:8080/SP_SC_Hibernate/login)



Enter the user credentials "user"/"user@123", and you will get your requested page after a success login:



Now try to see admin page, hit url http://localhost:8080/SP_SC_Hibernate/admin
Now you will get a access denied error, because "user" is not authorized to see "/admin" pages.



That's all for now in, Spring Security with Hibernate with Maven.

More Details on : Spring Security Authentication and Authorization
Download complete Project : Download Link









Thanks for reading !
Being Java Guys Team

Download "Spring Security with Hibernate Example Project" from "SkyDrive"



Thursday, 14 August 2014

Spring 4 Restful Web Services With Hibernate 4 Example using Maven – Server Application

Spring 4 Restful Web Services With Hibernate 4 Example using Maven – Server Application In our previous discussions we came across several Spring related topics. In this particular blog we will see how to create Spring Restful Web Services With Hibernate using Maven. We will create and build the project with Maven and hibernate 4 will be used in data layer.

To get started simply create a simple web application with maven and import it in Eclipse. If you are new to Maven please go through the Link below.

More Details on : Dynamic Web Project with Maven and Import it in eclipse

Now we have a skeleton Maven project imported to eclipse, lets add all required Java and Configuration files to it as shown in the rest part of the tutorial.

Database Setup
Here us MySql script to create a simple database and table structure to be used in our application, simply paste the script in query editor and run to make a DB skeleton.
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET FOREIGN_KEY_CHECKS=0 */;

-- Dumping database structure for employee_db
CREATE DATABASE IF NOT EXISTS `employee_db` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `employee_db`;


-- Dumping structure for table employee_db.employee
CREATE TABLE IF NOT EXISTS `employee` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(45) DEFAULT NULL,
  `last_name` varchar(45) DEFAULT NULL,
  `email` varchar(45) DEFAULT NULL,
  `phone` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

-- Dumping data for table employee_db.employee: ~1 rows (approximately)
/*!40000 ALTER TABLE `employee` DISABLE KEYS */;
INSERT INTO `employee` (`id`, `first_name`, `last_name`, `email`, `phone`) VALUES
 (2, 'Hoston', 'lindey', 'hl@gmail.com', '90908989899');
/*!40000 ALTER TABLE `employee` ENABLE KEYS */;
/*!40014 SET FOREIGN_KEY_CHECKS=1 */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;



Dependencies required to make Spring Restful Web Services with Hibernate

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.beingjavaguys.sample</groupId>
 <artifactId>SpringRestCrud</artifactId>
 <packaging>war</packaging>
 <version>1.0-SNAPSHOT</version>
 <name>SpringRestCrud Maven Webapp</name>
 <url>http://maven.apache.org</url>
 <properties>
  <spring.version>4.0.5.RELEASE</spring.version>
  <hibernate.version>4.3.5.Final</hibernate.version>
  <log4j.version>1.2.17</log4j.version>
  <jdk.version>1.7</jdk.version>
  <context.path>SpringRestCrud</context.path>
 </properties>
 <build>
  <finalName>${pom.artifactId}</finalName>
  <plugins>
   <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
  </plugins>
 </build>
 <dependencies>
  <dependency>
   <groupId>log4j</groupId>
   <artifactId>log4j</artifactId>
   <version>${log4j.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-orm</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-web</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>jstl</groupId>
   <artifactId>jstl</artifactId>
   <version>1.2</version>
  </dependency>
  <dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>2.2.2</version>
  </dependency>
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.6</version>
  </dependency>
  <dependency>
   <groupId>org.codehaus.jackson</groupId>
   <artifactId>jackson-mapper-asl</artifactId>
   <version>1.9.10</version>
  </dependency>
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>${hibernate.version}</version>
  </dependency>
 </dependencies>
</project>



\src\main\webapp\WEB-INF\web.xml
We need to make an Spring entry to web.xml, this will tell the container that all upcoming requests will be served by Spring Framework itself as per the configuration.
<web-app 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-app_2_5.xsd"
 version="2.5">

 <display-name>Sample Spring Maven Project</display-name>

 <servlet>
  <servlet-name>mvc-dispatcher</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/spring-config.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>mvc-dispatcher</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>

</web-app>


\src\main\webapp\WEB-INF\spring-config.xml
This is simple spring configuration file, we have added entry for base-package her to search and find Controller classes with annotations. We defined two beans here for Service and Dao layer that we will see in details shortly. Rest is hibernate configurations and a datasource bean to connect with database. More details on : Spring Hibernate Integration
<?xml version="1.0" encoding="UTF-8"?>
<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:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

 <context:component-scan base-package="com.beingjavaguys.controller" />
 <mvc:annotation-driven />

 <bean id="dataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <property name="url" value="jdbc:mysql://localhost:3306/employee_db" />
  <property name="username" value="root" />
  <property name="password" value="root" />
 </bean>

 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="annotatedClasses">
   <list>
    <value>com.beingjavaguys.model.Employee</value>
   </list>
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
   </props>
  </property>
 </bean>

 <bean id="txManager"
  class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
 </bean>

 <bean id="persistenceExceptionTranslationPostProcessor"
  class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

 <bean id="dataDao" class="com.beingjavaguys.dao.DataDaoImpl"></bean>
 <bean id="dataServices" class="com.beingjavaguys.services.DataServicesImpl"></bean>
</beans>

\src\main\java\com\beingjavaguys\controller\RestController.java
This is simple Spring MVC controller with annotations, we have added all general purpose methods here those method will accept a rest request in Json form and will return a JSON response. The methods are self explanatory we have used @Controller annotation to point incoming requests to this class, and @RequestMapping annotation to point incoming requests to appropriate Methods. @RequestBody annotation is used to accept data with request in Json form and @ResponseBody is used to return JSON as response to incoming request.
package com.beingjavaguys.controller;

import java.util.List;

import org.apache.log4j.Logger;
import com.beingjavaguys.model.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.beingjavaguys.model.Employee;
import com.beingjavaguys.services.DataServices;

@Controller
@RequestMapping("/employee")
public class RestController {

 @Autowired
 DataServices dataServices;

 static final Logger logger = Logger.getLogger(RestController.class);

 /* Submit form in Spring Restful Services */
 @RequestMapping(value = "/create", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
 public @ResponseBody
 Status addEmployee(@RequestBody Employee employee) {
  try {
   dataServices.addEntity(employee);
   return new Status(1, "Employee added Successfully !");
  } catch (Exception e) {
   // e.printStackTrace();
   return new Status(0, e.toString());
  }

 }

 /* Ger a single objct in Json form in Spring Rest Services */
 @RequestMapping(value = "/{id}", method = RequestMethod.GET)
 public @ResponseBody
 Employee getEmployee(@PathVariable("id") long id) {
  Employee employee = null;
  try {
   employee = dataServices.getEntityById(id);

  } catch (Exception e) {
   e.printStackTrace();
  }
  return employee;
 }

 /* Getting List of objects in Json format in Spring Restful Services */
 @RequestMapping(value = "/list", method = RequestMethod.GET)
 public @ResponseBody
 List getEmployee() {

  List employeeList = null;
  try {
   employeeList = dataServices.getEntityList();

  } catch (Exception e) {
   e.printStackTrace();
  }

  return employeeList;
 }

 /* Delete an object from DB in Spring Restful Services */
 @RequestMapping(value = "delete/{id}", method = RequestMethod.GET)
 public @ResponseBody
 Status deleteEmployee(@PathVariable("id") long id) {

  try {
   dataServices.deleteEntity(id);
   return new Status(1, "Employee deleted Successfully !");
  } catch (Exception e) {
   return new Status(0, e.toString());
  }

 }
}


More details on : Spring JSON – Output Json in Spring application

Model Classes

\SpringRestCrud\src\main\java\com\beingjavaguys\model\Employee.java
This is simple POJO to represent Employee entity in our application, we will be dealing with Employee entity to save, retrieve and delete data using Spring Restful Web Services. We have annotated the class with Hibernate annotations to make hibernate aware of the entity.
package com.beingjavaguys.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.codehaus.jackson.annotate.JsonIgnoreProperties;

@Entity
@Table(name = "employee")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Employee implements Serializable {

 private static final long serialVersionUID = 1L;

 @Id
 @GeneratedValue
 @Column(name = "id")
 private long id;

 @Column(name = "first_name")
 private String firstName;

 @Column(name = "last_name")
 private String lastName;

 @Column(name = "email")
 private String email;

 @Column(name = "phone")
 private String phone;

 public long getId() {
  return id;
 }

 public void setId(long id) {
  this.id = id;
 }

 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 String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public String getPhone() {
  return phone;
 }

 public void setPhone(String phone) {
  this.phone = phone;
 }
}



Don’t forget to add @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) annotation to class, this is used to resolve Hibernate and Json conflict.

\src\main\java\com\beingjavaguys\model\Status.java
This is another POJO to represent conditional Status and Error messages in form of Json, this comes handy in case of sending status response to requests if needed.
package com.beingjavaguys.model;

public class Status {

 private int code;
 private String message;

 public Status() {
 }

 public Status(int code, String message) {
  this.code = code;
  this.message = message;
 }

 public int getCode() {
  return code;
 }

 public void setCode(int code) {
  this.code = code;
 }

 public String getMessage() {
  return message;
 }

 public void setMessage(String message) {
  this.message = message;
 }
}



Data layer with spring and hibernate

Below are simple Service and Dao classes and Interfaces to make a two tier data layer between Spring and Hibernate.

More details on : Spring Hibernate Integration

\src\main\java\com\beingjavaguys\dao\DataDao.java
package com.beingjavaguys.dao;

import java.util.List;

import com.beingjavaguys.model.Employee;

public interface DataDao {

 public boolean addEntity(Employee employee) throws Exception;
 public Employee getEntityById(long id) throws Exception;
 public List getEntityList() throws Exception;
 public boolean deleteEntity(long id) throws Exception;
}



\src\main\java\com\beingjavaguys\dao\DataDaoImpl.java
package com.beingjavaguys.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import com.beingjavaguys.model.Employee;

public class DataDaoImpl implements DataDao {

 @Autowired
 SessionFactory sessionFactory;

 Session session = null;
 Transaction tx = null;

 @Override
 public boolean addEntity(Employee employee) throws Exception {

  session = sessionFactory.openSession();
  tx = session.beginTransaction();
  session.save(employee);
  tx.commit();
  session.close();

  return false;
 }

 @Override
 public Employee getEntityById(long id) throws Exception {
  session = sessionFactory.openSession();
  Employee employee = (Employee) session.load(Employee.class,
    new Long(id));
  tx = session.getTransaction();
  session.beginTransaction();
  tx.commit();
  return employee;
 }

 @SuppressWarnings("unchecked")
 @Override
 public List getEntityList() throws Exception {
  session = sessionFactory.openSession();
  tx = session.beginTransaction();
  List employeeList = session.createCriteria(Employee.class)
    .list();
  tx.commit();
  session.close();
  return employeeList;
 }
 
 @Override
 public boolean deleteEntity(long id)
   throws Exception {
  session = sessionFactory.openSession();
  Object o = session.load(Employee.class, id);
  tx = session.getTransaction();
  session.beginTransaction();
  session.delete(o);
  tx.commit();
  return false;
 }

}



\src\main\java\com\beingjavaguys\services\DataServices.java
package com.beingjavaguys.services;

import java.util.List;

import com.beingjavaguys.model.Employee;

public interface DataServices {
 public boolean addEntity(Employee employee) throws Exception;
 public Employee getEntityById(long id) throws Exception;
 public List getEntityList() throws Exception;
 public boolean deleteEntity(long id) throws Exception;
}



\src\main\java\com\beingjavaguys\services\DataServicesImpl.java
package com.beingjavaguys.services;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.beingjavaguys.dao.DataDao;
import com.beingjavaguys.model.Employee;

public class DataServicesImpl implements DataServices {

 @Autowired
 DataDao dataDao;
 
 @Override
 public boolean addEntity(Employee employee) throws Exception {
  return dataDao.addEntity(employee);
 }

 @Override
 public Employee getEntityById(long id) throws Exception {
  return dataDao.getEntityById(id);
 }

 @Override
 public List getEntityList() throws Exception {
  return dataDao.getEntityList();
 }

 @Override
 public boolean deleteEntity(long id) throws Exception {
  return dataDao.deleteEntity(id);
 }

}

In this particular article we came across "Spring 4 Restful Web Services With Hibernate 4 Example using Maven", in our next discussion we will see how to create a Client Application in Spring to consume Spring Restful Services.
Download complete Project : Download Link
NOTE : In case you want to test the application with some dummy data and without using any client application, you can do that using Chrome's Postman - REST Client. Make sure to set content-type: application/json when sending form data in JSON format to the service.










Thanks for reading !
Being Java Guys Team

Download "Spring 4 Restful Web Services With Hibernate 4 Example" from "SkyDrive"



Like Us on Facebook


Like Us On Google+



Contact

Email: neel4soft@gmail.com
Skype: neel4soft