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



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"



Thursday, 24 July 2014

Integrate Neo4j (Graph DB) with Java – Neo4J with Java (Neo4J + Java)

In this article we will see, what is Neo4J and graph db and how to use Neo4J with Java, adding nodes, relationships, properties and much more, stay tight and go forward :)

In computer science a graph database is a database that uses graph structure to store data, with help of graph nodes, nodes properties and relationships in between nodes. Nodes represents entities like employee, person, item, salary .. etc. Properties holds information about the node, as in case of employee node properties are id, name, department etc.. The graph can be traversed using any graph traversal algorithm.

Relationships are represented by edges those connects different nodes to nodes or nodes to properties. Relationships can also have properties. Like a relationships “friend” between two person nodes with type “knows” can have relationship properties like “are-true-friend”, “fiends-since” etc.. and their values like “yes”, “1787” etc..

There are a number of different graph db projects, some of them are AllegroGraph, ArangoDB, Bitsy, DEX/Sparksee, GraphBase and Neo4j.


Neo4j graph db

Neo4j is a open source database implemented in Java, Neo4j is the most popular graph database of today. Neo4j is fully transactional Java persistent engine that stores data in graph node rather than tables. Installing Neo4j database in windows 7

Neo4j db can be used as embedded db to be used in your code, but it’s always a better practice to store full db server to learn it. Follow the steps below to download and install Neo4j db in your local machine and get it up:
1) Download an updated and appropriate release from http://www.neo4j.org/download.
2) Double click the setup and install db server as simple as other windows application.
3) Visit http://localhost:7474 to verify that the server instance is started and running correctly.


Integrating Neo4j with Java

Neo4j exposes all required API’s to integrate with Java applications, Neo4j accepts request and return response in Json format only. In the rest part of the application we will see how to create a node, add properties and relationships to db using Java code.

We need to add a Neo4j driver dependency to the project

  <dependency>
   <groupId>org.neo4j</groupId>
   <artifactId>neo4j</artifactId>
   <version>2.1.2</version>
  </dependency>
Neo4j exposes its functions using REST API’s in Json format, so we have to use any REST API client to interact with. I am using HttpCient libraries, but you are free to use any API as per your convenient.
  
<dependency>
   <groupId>commons-httpclient</groupId>
   <artifactId>commons-httpclient</artifactId>
   <version>3.1</version>
  </dependency>
  <dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
   <version>4.1.3</version>
   <scope>compile</scope>
  </dependency>
  <dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpmime</artifactId>
   <version>4.1.3</version>
   <scope>compile</scope>
  </dependency>


Checking if Neo4j DB server is up and running.

To check the server status we need to send a get request to server in the required format, if got 200 status code, it means everything is fine and server is running peacefully.

For rest of the blog we have referring server root with “SERVER_ROOT_URI” as:
final String SERVER_ROOT_URI = "http://localhost:7474";
        /*
  * checks if neo4j server is up and running, returns 200 if succeeded and
  * 500 otherwise
  */
 public int getNeo4jServerStatus(String SERVER_ROOT_URI) {
  int statusCode = 500;
  try {

   String url = SERVER_ROOT_URI;
   HttpClient client = new HttpClient();
   GetMethod getMethod = new GetMethod(url);
   statusCode = client.executeMethod(getMethod);
   getMethod.releaseConnection();
  } catch (Exception e) {
   System.out.println("Exception in connecting to neo4j DB : " + e);
  }

  return statusCode;
 }


Adding a node to Neo4j DB server using Java

We have to send a post request to server URI //db/data/node to make a node in Neo4j DB. In accepts POST request and returns JSON data.

Create node Request format
• POST http://localhost:7474/db/data/node
• Accept: application/json; charset=UTF-8

Create node Response format
• 201: Created
• Content-Type: application/json; charset=UTF-8
• Location: http://localhost:7474/db/data/node/89
        /*
  * adding a node to server root
  */
 public String addNode(String SERVER_ROOT_URI) {
  String serverResponse = null;
  String nodeLocation = null;
  try {
   String nodePointUrl = SERVER_ROOT_URI + "/db/data/node";
   HttpClient client = new HttpClient();
   PostMethod postMethod = new PostMethod(nodePointUrl);

   /**
    * set header information to post request
    */
   Header header = new Header();
   header.setName("content-type");
   header.setValue("application/json");
   header.setName("accept");
   header.setValue("application/json");
   postMethod.addRequestHeader(header);

   /**
    * set json payload to post request
    */
   // empty node in json format
   StringRequestEntity stringRequestEntity = new StringRequestEntity(
     "{}", "application/json", "UTF-8");
   postMethod.setRequestEntity(stringRequestEntity);
   int requestStatus = client.executeMethod(postMethod);
   serverResponse = postMethod.getResponseBodyAsString();
   Header locationHeader = postMethod.getResponseHeader("location");
   nodeLocation = locationHeader.getValue();
   postMethod.releaseConnection();
   System.out.println("Request Status : " + requestStatus);
   System.out.println("Node Location : " + nodeLocation);
   System.out.println("Server Response Json : " + serverResponse);
  } catch (Exception e) {
   System.out.println("Exception in adding a node to neo4j graph : "
     + e);
  }

  return nodeLocation;
 }
The code above is self explained, all we have done is make a POST request and send a empty JSON object. We can that verify the node by browsing to URL printed in “Node Location” in console. It would be in form of http://localhost:7474/db/data/node/1.


Adding properties to a Neo4J node using Java

Till now we have added a empty node to Neo4J server, lets add some properties to the node. The properties service is a PUT service and upon successful completion it returns “204 No Content” response. Like it’s create pear this service also accepts and sends Json data format.

Properties node Request format
• PUT http://localhost:7474/db/data/node/80/properties/foo
• Accept: application/json; charset=UTF-8
• Content-Type: application/json

Properties node Response format
• 204: No Content
        /*
  * adding properties to nodes
  */
 public void addProperty(String SERVER_ROOT_URI, String nodeLocationPath,
   String propertyName, String propertyValue) {

  try {
   String nodePointUrl = nodeLocationPath + "/properties/"
     + propertyName;
   HttpClient httpClient = new HttpClient();
   PutMethod putMethod = new PutMethod(nodePointUrl);

   /**
    * set headers
    */
   Header header = new Header();
   header.setName("content-type");
   header.setValue("application/json");
   header.setName("accept");
   header.setValue("application/json");
   putMethod.addRequestHeader(header);

   /**
    * set json payload
    */
   String jsonString = "\"" + propertyValue + "\"";
   StringRequestEntity requestEntity = new StringRequestEntity(
     jsonString, "application/json", "UTF-8");
   putMethod.setRequestEntity(requestEntity);
   int satusCode = httpClient.executeMethod(putMethod);

   putMethod.releaseConnection();
   System.out.println("Satus Code : " + satusCode);
  } catch (Exception e) {
   System.out.println("Exception in adding propery to node : " + e);
  }

 }
In the code above we have passed the node URI to which we need to add properties, once added the node you can check it using browser console of Neo4J.


Creating a relationship in Neo4J using Java

To create a relationship we uses URI /relationships, here nodeurl is the location of source node to which relationship is being created.

The web service accepts a POST request in json format and returns response in Json format. After successful completion of request you will get a 201 status code. The API also returns the relationship node location.

Relationship node Request format
• PUT http://localhost:7474/db/data/node/80/properties/foo
• Accept: application/json; charset=UTF-8
• Content-Type: application/json

Relationship node Response format
• 204: No Content
        /*
  * adding relationship between two nodes
  */
 public String addRelationship(String firstNodeLocation,
   String secondNodeLocation, String relationship,
   String relationAttributes) {
  String relationOutputJson = null;
  String relationLocation = null;
  try {
   String fromUrl = firstNodeLocation + "/relationships";

   String relationshipJson = generateJsonRelationship(
     secondNodeLocation, relationship, relationAttributes);

   System.out.println("Relationship Json : " + relationshipJson);

   HttpClient httpClient = new HttpClient();
   PostMethod mPost = new PostMethod(fromUrl);

   /**
    * set request headers
    */
   Header mtHeader = new Header();
   mtHeader.setName("content-type");
   mtHeader.setValue("application/json");
   mtHeader.setName("accept");
   mtHeader.setValue("application/json");
   mPost.addRequestHeader(mtHeader);

   /**
    * set request json payload
    */
   StringRequestEntity requestEntity = new StringRequestEntity(
     relationshipJson, "application/json", "UTF-8");
   mPost.setRequestEntity(requestEntity);
   int nodesatus = httpClient.executeMethod(mPost);
   relationOutputJson = mPost.getResponseBodyAsString();
   Header locationHeader = mPost.getResponseHeader("location");
   relationLocation = locationHeader.getValue();
   mPost.releaseConnection();
   System.out.println("Node Satus : " + nodesatus);
   System.out.println("Relation node Location : " + relationLocation);
   System.out.println("output : " + relationOutputJson);
  } catch (Exception e) {
   System.out.println("Exception in adding relationship node in neo4j : " + e);
  }

  return relationLocation;

 }

 /*
  * used to create relationship json in required format
  */
 private String generateJsonRelationship(String secondNodeLocation,
   String relationship, String relationAttributes) {

  StringBuilder sb = new StringBuilder();
  sb.append("{ \"to\" : \"");
  sb.append(secondNodeLocation);
  sb.append("\", ");

  sb.append("\"type\" : \"");
  sb.append(relationship);
  if (relationAttributes == null || relationAttributes.length() < 1) {
   sb.append("\"");
  } else {
   sb.append("\", \"data\" : " + relationAttributes);

  }

  sb.append(" }");
  return sb.toString();
 }


Adding properties to a relationship in Neo4J using Java

Here we are done with adding nodes and a relationship in between nodes, now we can add properties to relationships as well. Properties can be added to a relationship making a put request to /properties where relationshiplocation is the location of relationship in db server.

Relationship node Request format
• PUT http://localhost:7474/db/data/relationship/113/properties
• Accept: application/json; charset=UTF-8
• Content-Type: application/json

Relationship node Response format
• 204: No Content
public void addPropertyToRelations(String relationshipLocationPath,
   String propertyName, String propertyValue) {

  try {
   String relPropUrl = relationshipLocationPath + "/properties";
   HttpClient httpClient = new HttpClient();
   PutMethod putMethod = new PutMethod(relPropUrl);

   /**
    * set request headers
    */
   Header header = new Header();
   header.setName("content-type");
   header.setValue("application/json");
   header.setName("accept");
   header.setValue("application/json");
   putMethod.addRequestHeader(header);

   /**
    * set request json payload
    */
   String jsonString = convertToNameValueJson(propertyName,
     propertyValue);
   StringRequestEntity requestEntity = new StringRequestEntity(
     jsonString, "application/json", "UTF-8");
   putMethod.setRequestEntity(requestEntity);
   int satusCode = httpClient.executeMethod(putMethod);

   putMethod.releaseConnection();
   System.out.println("Satus Code : " + satusCode);
  } catch (Exception e) {
   System.out
     .println("Exception in addding properties to a relation in neo4j : "
       + e);
  }

 }

 private String convertToNameValueJson(String name, String value) {
  return String.format("{ \"%s\" : \"%s\" }", name, value);
 }
Done, till now we have seen, how to install and setup Neo4J in Windows and integrate Neo4j with Java. Lets see the folks running now, here are two complete files used in this project one is consists of operations and other file is having main() to perform them.

\src\main\java\com\beingjavaguys\graphdb\ServerUtils.java
package com.beingjavaguys.graphdb;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;

/**
 * @author Nagesh.Chauhan
 * 
 */
public class ServerUtils {
 /*
  * checks if neo4j server is up and running, returns 200 if succeeded and
  * 500 otherwise
  */
 public int getNeo4jServerStatus(String SERVER_ROOT_URI) {
  int statusCode = 500;
  try {

   String url = SERVER_ROOT_URI;
   HttpClient client = new HttpClient();
   GetMethod getMethod = new GetMethod(url);
   statusCode = client.executeMethod(getMethod);
   getMethod.releaseConnection();
  } catch (Exception e) {
   System.out.println("Exception in connecting to neo4j DB : " + e);
  }

  return statusCode;
 }

 /*
  * adding a node to server root
  */
 public String addNode(String SERVER_ROOT_URI) {
  String serverResponse = null;
  String nodeLocation = null;
  try {
   String nodePointUrl = SERVER_ROOT_URI + "/db/data/node";
   HttpClient client = new HttpClient();
   PostMethod postMethod = new PostMethod(nodePointUrl);

   /**
    * set header information to post request
    */
   Header header = new Header();
   header.setName("content-type");
   header.setValue("application/json");
   header.setName("accept");
   header.setValue("application/json");
   postMethod.addRequestHeader(header);

   /**
    * set json payload to post request
    */
   // empty node in json format
   StringRequestEntity stringRequestEntity = new StringRequestEntity(
     "{}", "application/json", "UTF-8");
   postMethod.setRequestEntity(stringRequestEntity);
   int requestStatus = client.executeMethod(postMethod);
   serverResponse = postMethod.getResponseBodyAsString();
   Header locationHeader = postMethod.getResponseHeader("location");
   nodeLocation = locationHeader.getValue();
   postMethod.releaseConnection();
   System.out.println("Request Status : " + requestStatus);
   System.out.println("Node Location : " + nodeLocation);
   System.out.println("Server Response Json : " + serverResponse);
  } catch (Exception e) {
   System.out.println("Exception in adding a node to neo4j graph : "
     + e);
  }

  return nodeLocation;
 }

 /*
  * adding properties to nodes
  */
 public void addProperty(String SERVER_ROOT_URI, String nodeLocationPath,
   String propertyName, String propertyValue) {

  try {
   String nodePointUrl = nodeLocationPath + "/properties/"
     + propertyName;
   HttpClient httpClient = new HttpClient();
   PutMethod putMethod = new PutMethod(nodePointUrl);

   /**
    * set headers
    */
   Header header = new Header();
   header.setName("content-type");
   header.setValue("application/json");
   header.setName("accept");
   header.setValue("application/json");
   putMethod.addRequestHeader(header);

   /**
    * set json payload
    */
   String jsonString = "\"" + propertyValue + "\"";
   StringRequestEntity requestEntity = new StringRequestEntity(
     jsonString, "application/json", "UTF-8");
   putMethod.setRequestEntity(requestEntity);
   int satusCode = httpClient.executeMethod(putMethod);

   putMethod.releaseConnection();
   System.out.println("Satus Code : " + satusCode);
  } catch (Exception e) {
   System.out.println("Exception in adding propery to node : " + e);
  }

 }

 /*
  * adding relationship between two nodes
  */
 public String addRelationship(String firstNodeLocation,
   String secondNodeLocation, String relationship,
   String relationAttributes) {
  String relationOutputJson = null;
  String relationLocation = null;
  try {
   String fromUrl = firstNodeLocation + "/relationships";

   String relationshipJson = generateJsonRelationship(
     secondNodeLocation, relationship, relationAttributes);

   System.out.println("Relationship Json : " + relationshipJson);

   HttpClient httpClient = new HttpClient();
   PostMethod mPost = new PostMethod(fromUrl);

   /**
    * set request headers
    */
   Header mtHeader = new Header();
   mtHeader.setName("content-type");
   mtHeader.setValue("application/json");
   mtHeader.setName("accept");
   mtHeader.setValue("application/json");
   mPost.addRequestHeader(mtHeader);

   /**
    * set request json payload
    */
   StringRequestEntity requestEntity = new StringRequestEntity(
     relationshipJson, "application/json", "UTF-8");
   mPost.setRequestEntity(requestEntity);
   int nodesatus = httpClient.executeMethod(mPost);
   relationOutputJson = mPost.getResponseBodyAsString();
   Header locationHeader = mPost.getResponseHeader("location");
   relationLocation = locationHeader.getValue();
   mPost.releaseConnection();
   System.out.println("Node Satus : " + nodesatus);
   System.out.println("Relation node Location : " + relationLocation);
   System.out.println("output : " + relationOutputJson);
  } catch (Exception e) {
   System.out
     .println("Exception in adding relationship node in neo4j : "
       + e);
  }

  return relationLocation;

 }

 /*
  * used to create relationship json in required format
  */
 private String generateJsonRelationship(String secondNodeLocation,
   String relationship, String relationAttributes) {

  StringBuilder sb = new StringBuilder();
  sb.append("{ \"to\" : \"");
  sb.append(secondNodeLocation);
  sb.append("\", ");

  sb.append("\"type\" : \"");
  sb.append(relationship);
  if (relationAttributes == null || relationAttributes.length() < 1) {
   sb.append("\"");
  } else {
   sb.append("\", \"data\" : " + relationAttributes);

  }

  sb.append(" }");
  return sb.toString();
 }

 public void addPropertyToRelations(String relationshipLocationPath,
   String propertyName, String propertyValue) {

  try {
   String relPropUrl = relationshipLocationPath + "/properties";
   HttpClient httpClient = new HttpClient();
   PutMethod putMethod = new PutMethod(relPropUrl);

   /**
    * set request headers
    */
   Header header = new Header();
   header.setName("content-type");
   header.setValue("application/json");
   header.setName("accept");
   header.setValue("application/json");
   putMethod.addRequestHeader(header);

   /**
    * set request json payload
    */
   String jsonString = convertToNameValueJson(propertyName,
     propertyValue);
   StringRequestEntity requestEntity = new StringRequestEntity(
     jsonString, "application/json", "UTF-8");
   putMethod.setRequestEntity(requestEntity);
   int satusCode = httpClient.executeMethod(putMethod);

   putMethod.releaseConnection();
   System.out.println("Satus Code : " + satusCode);
  } catch (Exception e) {
   System.out
     .println("Exception in addding properties to a relation in neo4j : "
       + e);
  }

 }

 private String convertToNameValueJson(String name, String value) {
  return String.format("{ \"%s\" : \"%s\" }", name, value);
 }
}


\src\main\java\com\beingjavaguys\graphdb\App.java
package com.beingjavaguys.graphdb;

/**
 * @author Nagesh.Chauhan
 * 
 */
public class App {
 public static void main(String[] args) {
  final String SERVER_ROOT_URI = "http://localhost:7474";
  ServerUtils serverUtils = new ServerUtils();

  // getting server status
  int serverStatusCode = serverUtils
    .getNeo4jServerStatus(SERVER_ROOT_URI);

  if (serverStatusCode == 200) {
   // adding a blank node to neo4j db server
   String firstNodeLocation = serverUtils.addNode(SERVER_ROOT_URI);
   System.out.println("First Node Location: " + firstNodeLocation);

   // adding another blank node to neo4j db server
   String secondNodeLocation = serverUtils.addNode(SERVER_ROOT_URI);
   System.out.println("Second Node Location: " + secondNodeLocation);

   // adding properties to first node in server
   serverUtils.addProperty(SERVER_ROOT_URI, firstNodeLocation, "name",
     "andrew");
   serverUtils.addProperty(SERVER_ROOT_URI, firstNodeLocation,
     "email", "andrew@java.com");
   serverUtils.addProperty(SERVER_ROOT_URI, firstNodeLocation,
     "phone", "7876754346");

   // adding properties to second node in server
   serverUtils.addProperty(SERVER_ROOT_URI, secondNodeLocation,
     "name", "smith");
   serverUtils.addProperty(SERVER_ROOT_URI, secondNodeLocation,
     "email", "smith@java.com");
   serverUtils.addProperty(SERVER_ROOT_URI, secondNodeLocation,
     "phone", "8787653454");

   // adding a relationship in between two nodes
   String relationAttributes = "{ \"bestfriends\" : \"yes\",\"since\" : \"2005\" }";
   String relationshipLocation = serverUtils.addRelationship(
     firstNodeLocation, secondNodeLocation, "friend",
     relationAttributes);
   System.out
     .println("Relationship Location: " + relationshipLocation);

   // adding property to existing relation
   serverUtils.addPropertyToRelations(relationshipLocation, "common",
     "behavior");
  }
 }

}


Run Java application, if everything goes right you can browse nodes creted and relationship created using Location URI's(node numbers may be different refer your console to get URI's) like:

Node URI Like: http://localhost:7474/db/data/node/19



Relationship URI Like: http://localhost:7474/db/data/relationship/4



We came to know how to add node, relationships and properties to Neo4J db server using Java. By now you are able to understand the functioning of Neo4J API for Java. Other updating and deleting operations and query database can be performed like this by using appropriate JSON format and request type. There are a number of other useful operations like Updating and Deleting nodes and relationships and their properties. We will see how to query Neo4J db using Java in upcoming blogs.

Download complete Project : Download Link










Thanks for reading !
Being Java Guys Team

Download "Integrate Neo4j (Graph DB) with Java Example Project" from "SkyDrive"



Like Us on Facebook

Search Tutorials

Like Us On Google+