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



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"



Tuesday, 24 June 2014

100 Core Java Interview Questions and Answers - Part 10

Here are top selected core java interview questions asked in high level interviews, these questions may be helpful for both freshers or experienced professional going for interview.




91) What is synchronization in Java?

In java synchronization is the ability to control the access of multiple threads to shared resources. Synchronization ensures that only one thread can access a shared resource at a time.

92) What are wrapper classes in Java.

Java provides some equivalent classes to represent primitive types as object these classes are called wrapper classes. There are 8 wrapper classes in java ; Byte, Short, Integer, Long, Float, Double, Character and Boolean.

93) Can we have more than one class declaration in a single java file.

We can have only a single public class declaration per java file, whereas we can have multiple non-public classes in a single java file.

94) Can we declare main() method as private?

No, We cannot declare main() method as private. If we does so the program will compile fine but at runtime it will give “Main Method Not Public” message.

95) Explain System.out.println() briefly?

System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object.











Thanks for reading !
Being Java Guys Team



100 Core Java Interview Questions and Answers - Part 9

Here are top selected core java interview questions asked in high level interviews, these questions may be helpful for both freshers or experienced professional going for interview.




81) What if, we import a class or package more than once in our program?

We can import a class or an package as many times as we want to, neither the compiler or the JVM will complain about it. But internally the class or package will be loaded once no matters how many times we have written the import statement.

82) What is the difference between a checked or unchecked exception in Java?

The classes which extends Throwable class except RuntimeException and Error are known as checked exceptions. These exceptions are thrown at compile time. E.g. IOException, FileNotFoundException etc. The classes which extends RuntimeException class are called unchecked exceptions. These exceptions are thrown at runtime. E.g. ArithmeticException,NullPointerException etc.

83) What is the root class of all Exception and Errors in Java.

Throwable is the base class for all Exceptions and Errors in Java.

84) Can we have a try block without a catch block in Java?

Yes, we can have a try block without having a catch block but a try block must be followed by either a catch or a finaly block or with both.

85) What are nested classes in Java?

A class that is declared inside another class is called nested class, there are four types of a nested class in java : member inner class, local inner class, annonymous inner class and static nested class.

86) What is volatile keyword in Java?

Threads hold their own copy of variables in local memory, if a variable is marked as volatile it means that the variable will be stored in main memory, every time a volatile variable is read it will be read from the main memory similarly every time the volatile variable is written the changes will be written to the main memory only.

87) What is the difference between path and classpath in java?

In context of java path and classpath both are operating system level environment variables. Path says where can the system finds .exe files whereas classpath tells the location of .class files within a system.

88) What do you mean by downcasting in Java?

In java downcasting means casting a general type to a more specific type.











Thanks for reading !
Being Java Guys Team



100 Core Java Interview Questions and Answers - Part 8

Here are top selected core java interview questions asked in high level interviews, these questions may be helpful for both freshers or experienced professional going for interview.




71) What are immutable objects in Java?

In java, immutable objects are the objects which can not be changed once created. Any change to the states of these object results in a new object. String objects are the example of immutable objects in java any change to the states of an String object results in a new object and the old object remains unchanged.

72) What is the difference between a StringBuffer and StringBuilder class in Java?

In java both StringBuffer and StringBuilder classes are immutable in nature, the only difference in between them is that StringBuffer class in thread-safe while StringBuilder is not thread safe in nature. StringBuilder class was introduced in Java5 to reduce the overhead of synchronization.

73) How many types of memory areas are allocated by JVM?

JVM allocated memory areas in many forms like:
1. Class(Method) Area
2. Heap
3. Stack
4. Program Counter Register
5. Native Method Stack

74) What if I changed the order of public static and void in ‘public static void main(String args[])’?

The program will compile fine and run properly, main() method implementation is regardless of the order of public, static and void keywords.

75) What is the default value for an instance variable in Java?

All instance variables are initialized to “null” by default.

76) What do you mean by composition in Java ?

Holding the reference of one class in another class in known as composition in Java.

77) Can be define an abstract method in an non abstract class ?

No, if a single method is declared as abstract in a class then the class must be declared as abstract itself.

78) Can we declare a class as abstract and final in Java?

No, we cannot declare an abstract method as final, abstract methods does not have body and they are meant to be overridden in another class, if we declare them final than its impossible to override them and hence no use of them.











Thanks for reading !
Being Java Guys Team



100 Core Java Interview Questions and Answers - Part 7

Here are top selected core java interview questions asked in high level interviews, these questions may be helpful for both freshers or experienced professional going for interview.




61) What if we does not pass an String array of objects to main() method ?

Program will compile fine, but at runtime it will give an error “NoSuchMethodError”.

62) List all primitive types in Java ?

There are a total of 8 primitive types in java; byte, short, char, int, long, Boolean, float and double. In java String is an object and not a primitive type.

63) Can we have multiple main() methods in the same class?

No, We can have multiple overloaded methods in a same class with name main(), but there must be a single method with signature ‘public static void main(String args[])’. Unless the compiler says main method already defined.

64) What is difference between “String” and “StringBuffer” class in Java?

In java, “String” is an immutable class whereas “StringBuffer” is not immutable in nature. This means that once a String object is created we cannot change its state. Every time an operation is performed on a String object, it results the creation of a new Object and the old object remains unchanged. Whereas in ‘StringBuffer’ because of being a non-immutable class, the changes are reflected to the same object on which the operation is performed.

65) What is transient variable in Java?

If we declare a variable as transient, it prevents that variable from being serialized. If a class is serialized to a stream and one tries to deserialize it again than the variable having transient with it return a null value.

66) Are “true” ,“false” and “null” keywords in Java?

No, Neither of the three true, false or null is a keyword in java.

67) Can we declare an abstract class as final.

No, we cannot declare an abstract class as final because abstract classes are meant to be extended by some other class to make it meaningful. If we declare a class final it cannot be extended by some other class and hence an abstract class cannot be declared as final.

68) What is the default value of a boolean type in Java?

In java a Boolean type variable is initialized to “false” by default.











Thanks for reading !
Being Java Guys Team



Search Tutorials
Like Us on Facebook

Like Us On Google+