JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Spring Data REST + GemFire + Backbone.js Integration

June 6, 2014 by Amr Mohammed Leave a Comment

In my previous tutorial I have explained about Spring Data REST + GemFire + jQuery Integration. This tutorial explains about the integration of Spring Data and Backbone.js integration. Backbone JavaScript framework isn’t like any of the previous frameworks when it comes to the integration.

Before getting started writing the integration application, let’s get the basics of the backbone framework. Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions,views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.

So, this tutorial walks you through the sample application for creating a backbone  model that consumes the Spring Data REST and GemFire resources to use in the backbone view.   

1. Project Structure

Here is the structure of the project that is used for this tutorial. It has only those files related to the Spring Data REST, GemFire and its repository.

Spring Data REST - GemFire - Backbone.js - Project Structure

2. Tools Used

  • JDK 1.6.
  • Tomcat 1.7.
  • Maven 3.
  • Spring Data REST.
  • GemFire 7.0.1 Platform (JAR distribution).

3. Business Domain

We have a Message entity or object that needs to be used for the Restful service. This is the primary entity class for this tutorial.

Message.java

[code lang="java"]
package net.javabeat.springdata.data;

import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.gemfire.mapping.Region;

@Region("messages")
public class Message {
@Id
private String messageId;
private String message;

public Message() {
}

@PersistenceConstructor
public Message(String id, String message) {
this.messageId = id;
this.message = message;
}

public String getMessageId() {
return messageId;
}

public void setMessageId(String messageId) {
this.messageId = messageId;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}
}
[/code]

4. Spring Data Repository

Repository provides you an abstraction layer in which you have never been providing an implementation for your CRUD operations even if it was a small portion of code. What you should have to do is to create your own interface that extends the Spring Data’s special Repository and the remaining work has been left for the Spring framework to complete the required implementation. So, you should have to provide a repository like below. If you look at the below class MessageRepository, it extends the CrudeRepository which is the spring data’s interface which defines the methods for the CRUD operations.

MessageRepository.java

[code lang="java"]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.data.Message;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel="messages",path="messages")
public interface MessageRepository extends CrudRepository<Message,Integer> {}
[/code]

As you’ve noted, the message repository is just an interface which is consider as an extension for the special spring data repository. You’ve mentioned the repository act on type i.e. Message business object in which the repository would play around of it to achieve the  CRUD operations.

5. GemFire Spring Bean

It’s just a normal spring bean that used for providing a dummy messages that would be consumed by the services.

GemFireBean.java

[code lang="java"]
package net.javabeat.springdata.bean;

import net.javabeat.springdata.data.Message;
import net.javabeat.springdata.repo.MessageRepository;

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

@Component
public class GemFireBean {

MessageRepository messageRepository;

public GemFireBean(){

}

public MessageRepository getMessageRepository() {
return messageRepository;
}

@Autowired
public void setMessageRepository(MessageRepository messageRepository) {
// Message repository has been set
this.messageRepository = messageRepository;

// Add some messages into GemFire for being seen
Message message = new Message();
message.setMessageId("1");
message.setMessage("Hello JavaBeat !");

messageRepository.save(message);

// Add
message = new Message();
message.setMessageId("2");
message.setMessage("Hello GemFire REST");
messageRepository.save(message);
System.out.println("Messages are filled");
}
}
[/code]

6. Spring Bean Definition

This is the simple XML configuration for the spring beans.

SpringContext.xml

[code lang="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:gfe-data="http://www.springframework.org/schema/data/gemfire"
xmlns:gfe="http://www.springframework.org/schema/gemfire"
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.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/data/gemfire http://www.springframework.org/schema/data/gemfire/spring-data-gemfire.xsd http://www.springframework.org/schema/gemfire http://www.springframework.org/schema/gemfire/spring-gemfire.xsd">
<!-- Search for spring components -->
<context:component-scan base-package="net.javabeat"></context:component-scan>
<!-- Declare GemFire Cache -->
<gfe:cache/>
<!-- Local region for being used by the Message -->
<gfe:local-region id="messages" value-constraint="net.javabeat.springdata.data.Message"/>
<!-- Search for GemFire repositories -->
<gfe-data:repositories base-package="net.javabeat.springdata.repo"/>
</beans>
[/code]

7. Repository Rest Dispatcher Servlet & Web deployment Descriptor

To install spring data rest alongside your existing web application, you need to include the appropriate configuration.

  • Spring Data REST configuration is defined in a class called RepositoryRestMvcConfiguration.
  • Since Spring Data REST is simply a spring MVC application, you only need to include the RepositoryRestDispatcherServlet to use the REST functionality when we use spring framework with XML configurations.

The web deployment descriptor seems like below.

web.xml

[code lang="xml"]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" metadata-complete="true" version="3.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config/SpringContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>org.springframework.data.rest.webmvc.RepositoryRestDispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
[/code]

8. Access GemFire Repositories

It’s just a steps for exposing the GemFire repositories through using of google Dev HTTP. For doing that just follow the below steps:

  • From chrome browser open the Dev HTTP Client.
  • Type your host followed by the port number followed with the web context for the deployed application which should results in the token http://localhost:8080/SpringData-GemFire-REST-1.0.
  • For consuming the messages resources, you have to add the RepositoryRestDispactherServlet mapping url which mentioned in the web.xml and it’s /rest/ which results in url value like http://localhost:8080/SpringData-GemFire-REST-Bakbone.js-1.0./rest/
  • Add the The path segment under which this resource is to be exported. that value was provided using the path property at the header of the MessageRepository in order to be able of exposing the messages resource like below.

Spring Data REST - Backbone - GemFire Data Export

As you’ve noted the messages resources prefixed with the rest word that mapped to the RepositoryRestDispatcherServlet.

9. Setup Environment – Create Bower Configuration Files

First, create a bower (bower is a package manager) control which tells the bower where to put the JavaScript dependencies and for doing that you have to follow the below steps.

  • Download Git (is a free and open source distributed version control system DVCS) and install it into your machine. In case you have used a linux or other operating systems, try to install the desired version by visiting the Git site.
  • Download the node.js platform ( is a software platform offers a safe way to build high performance and scalable network applications in JavaScript).
  • After finish the installation of Git & node.js, next it will be using the command line, so open the command line and navigate through it into webapps within your own project. In our case the location is D:\Krishna\EclipseLink\Workspace\SpringData-GemFire-REST-Backbone.js\src\main\webapp.
  • Type  node -v to ensure that you are getting installed node.js successfully. You should find the version of the installed node.js platform. In our case the version is v0.10.28.
  • Type npm -v to ensure that the npm (Node Package Manager) is installed properly. Node package manager used for managing the JavaScript dependencies, in which a JavaScript libraries have been installed, and a JavaScript programs have been published. In our case we’ve got 1.4.9 version.
  • Type bower init for creating a bower.json file that describes each JavaScript package required by the project. Bower will ask for several bits of information such as project name, license, etc. If in doubt, just press Enter to accept the default.
  • Next, use bower to install Backbone (since we’re using JavaScript modules, we’ll use the AMD version of Backbone), jQuery and Lodash (an alternative to Underscore), and an AMD module loader such as curl.js.

Bower Init Command Execution

Where the resulted file should be bower.json that would carry the required information about JavaScript dependencies. And the project structure should be like

Spring Data REST - Backbone - Bower Init - Project Structure

  • From the command line type:
  • bower install –save backbone-amd#~1
  • bower install –save jquery#~2
  • bower install –save lodash#~1
  • bower install –save curl#~0.8

Bower will install these packages into directory.

Spring Data REST - Backbone - Install JavaScript Libraries

And the bower.json file should look like

bower.json

[code lang="xml"]
{
"name": "SpringData-GemFire-REST-Backbone.js",
"version": "0.0.1",
"description": "Spring Data REST GemFire Backbone Integration",
"main": "controller",
"license": "MIT",
"homepage": "index.html",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
],
"dependencies": {
"backbone-amd": "~1",
"jquery": "~2",
"lodash": "~1",
"curl": "~0.8"
}
}
[/code]

Now, you’re ready for getting started writing a backbone components.

10. Backbone Model

Backbone consumes data from a RESTful web services via models and collections. First, you’ll create a Backbone model that represents the data you want to consume from the REST service.

GemFireModel.js

[code lang="java"]
define(function(require) {
var Backbone = require('Backbone');

return Backbone.Model.extend({
urlRoot: 'http://localhost:8080/SpringData-GemFire-REST-Backbone.js-1.0/rest/messages',
url: function() {
return this.urlRoot;
}
});
});
[/code]

The model extends Backbone’s base Model, and sets the model’s urlRoot to the REST service at http://localhost:8080/SpringData-GemFire-REST-Backbone.js-1.0/rest/messages.

11. Backbone View

Next, you have to create a Backbone view to render the data in your GemFireModel.

GemFireView.js

[code lang="java"]
define(function(require) {
var Backbone = require('Backbone');
var $ = require('jquery');
var _ = require('underscore');

return Backbone.View.extend({
initialize: function() {
console.log($('#gemfire-template').html());
this.template = _.template($('#gemfire-template').html());
this.listenTo(this.model, 'change', this.render);
},

render: function(){
console.log(this.template);
this.$el.html(this.template(this.model.attributes));
}
});
})
[/code]

The view extends Backbone’s base View. The initialize method will be called when the view is instantiated. It uses Underscore to compile a template that will be used to render the model data, saving the compiled template in this.template.

Backbone automatically wraps the view’s root DOM Node (which will be provided when instantiating the view) in jQuery and makes it available as this.$el. The render method renders the compiled template, passing the model data, and then uses jQuery’s html() method to insert the rendered output into the DOM.

12. Backbone Controller

controller.js

[code lang="java"]
define(
function(require) {
var GemFireModel = require('./GemFireModel');
var GemFireView = require('./GemFireView');
var $ = require('jquery');

var model = new GemFireModel();
model.fetch();

$(document).ready(function() {
var gemfireView = new GemFireView({
el: $('.messages'),
model: model
});
});
});
[/code]

This controller instantiates a GemFireModel, and then invokes its fetch() method to fetch data from the REST service and populate the model’s data fields. Then it instantiates a GemFireView, passing the DOM Node where it should render, and the model. The view will automatically render the model using its compiled template.

13. Backbone Boot Script

This script configures the AMD loader: curl.config(). The main configuration property tells curl.js where to find the application’s main module, which will be fetched and evaluated automatically. The packages config object tells curl.js where to find modules in our application’s packages or in third-party packages.

boot.js

[code lang="java"]
var curl;
(
function () {

curl({
main: 'controller',
packages: {
// Third-party packages
curl: { location: 'bower_components/curl/src/curl' },
jquery: { location: 'bower_components/jquery/dist/jquery', main: '.' },
Backbone: { location: 'bower_components/backbone-amd/backbone', main: '.' },
underscore: { location: 'bower_components/lodash/lodash', main: '.' }
}
});
}());
[/code]

14. HTML View

Now that you have a model, view, and controller, you’ll create the HTML page that will load the client into the user’s web browser:

index.html

[code lang="xml"]
<!doctype html>
<html>
<head>
<title>GemFire Backbone</title>
<script data-curl-run="boot.js" src="bower_components/curl/src/curl.js"></script>
<script type="text/html" id="gemfire-template">
<% _.each(_embedded.messages, function(message) { %>
Message :: <%= message.message %> :: <a href='<%= message._links.self.href%>'>Message Link</a>
<br/>
<% }); %>
</script>
</head>
<body>
<h2>JavaBeat Tutorials</h2>
<h3>Spring Data REST - GemFire - Backbone Integration</h3>
<div class="messages">

</div>
</body>
</html>
[/code]

The script element will load curl.js and then load an application boot script named boot.js. The boot script will initialize and configure an AMD module environment and then start the client-side application code.

[code lang="java"]
<script data-curl-run="boot.js" src="lib/curl/src/curl.js"></script>
[/code]

Next is the HTML template that your view uses to render the model data. Note that we use a script tag, with the type text/html. This tells the browser not to try to execute the script tag as JavaScript.

[code lang="java"]
<script type="text/html" id="gemfire-template">
<% _.each(_embedded.messages, function(message) { %>
Message :: <%= message.message %> :: <a href='<%= message._links.self.href%>'>Message Link</a>
<br/>
<% }); %>
</script>
[/code]

Finally, there is the root DOM Node of the view. The view will render the model data, using the template, into this node:

[code lang="xml"]
<div class="messages"></div>
[/code]

15. Spring Data REST & Backbone Demo

The final project structure should look like

Spring Data REST - GemFire - Backbone - Final Project Structure

And once you’ve packaged the application using the maven and exporting it into Tomcat Apache for deploying. The execution should look like

Spring Data REST - Backbone - GemFire - Integration Demo

16. Summary

This tutorial I have explained how to access the Spring Data REST services and  GemFire in-memory repository through the Backbone components. Also this tutorial walks you through the various JavaScript techniques like Bower package manager, Underscore which are used as part of this tutorial. If you have any questions, please write it in the comments section.

Download Source Code

[wpdm_file id=109]

Filed Under: Spring Framework Tagged With: BackBone, GemFire, Spring Data, Spring REST

Spring Data REST + GemFire + jQuery Integration

May 28, 2014 by Amr Mohammed Leave a Comment

This tutorial explains how to integrate Spring Data REST, GemFire and JQuery frameworks. Multiple JavaScript frameworks can be integrated with the Spring Data REST for consuming the services. We’ve explained integration between Spring Data REST & AngularJS, where in a GemFire in-memory platform was used for presenting the data repository.

Also read:

  • Spring Data JPA
  • Spring Data JPA + Querydsl
  • Spring Data + MongoDB 
  • Connect With Us : Google+ | Twitter | FaceBook

However, in this tutorial we’re exploring the integrating between Spring Data REST with the jQuery library. jQuery library being used here is 1.10.2 which consider late version, but even if you’ve decided to use another version of jQuery, you’ve just need to use the same application in this tutorial which will work without any issues. If you have any questions, please write it in the comments section.

1. Tools Used

  • JDK 1.6.
  • Tomcat 7.
  • Maven 3.
  • Spring Data REST.
  • GemFire 7.0.1 Platform (JAR distribution).
  • JQuery 1.10.2

2. Project Structure

Here is the project structure used for developing the Spring Data REST, GemFire and JQuery application.

Spring Data REST GemFire jQuery Project Structure

3. Business Domain

Here is the domain class used in this tutorial. In this tutorial, we have a Message entity or object that needs to be consumed through  Restful service. Look at the implementation below. @Region annotation must be used to specify that this class uses the GemFire storage. This is equivalent to the table in the relational database.

Message.java

[code lang=”java”]
package net.javabeat.springdata.data;

import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.gemfire.mapping.Region;

@Region("messages")
public class Message {
@Id
private String messageId;
private String message;

public Message() {
}

@PersistenceConstructor
public Message(String id, String message) {
this.messageId = id;
this.message = message;
}

public String getMessageId() {
return messageId;
}

public void setMessageId(String messageId) {
this.messageId = messageId;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}
}
[/code]

4. Spring Data Repository

Repository provides you an abstraction layer in which you’ve never been providing an implementation for your CRUD operations even if it was a small portion of code. What you should have to do is to create your own interface that extends the Spring Data’s special Repository and the remaining work has been left for the Spring framework to complete the required implementation. So, you should have to provide a repository like below. If you look at the below class MessageRepository, it extends the CrudeRepository which is the spring data’s interface which defines the methods for the CRUD operations.

MessageRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.data.Message;

import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel="messages",path="messages")
public interface MessageRepository extends CrudRepository<Message,Integer> {}
[/code]

As you’ve noted, the message repository is just an interface which is consider as an extension for the special spring data repository. You’ve mentioned the repository act on type i.e. Message business object in which the repository would play around of it to achieve the needed CRUD operations.

5. GemFire Spring Bean

It’s just an normal spring bean that used for providing a dummy messages that would be consumed.

GemFireBean.java

[code lang=”java”]
package net.javabeat.springdata.bean;

import net.javabeat.springdata.data.Message;
import net.javabeat.springdata.repo.MessageRepository;

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

@Component
public class GemFireBean {

MessageRepository messageRepository;

public GemFireBean(){

}

public MessageRepository getMessageRepository() {
return messageRepository;
}

@Autowired
public void setMessageRepository(MessageRepository messageRepository) {
// Message repository has been set
this.messageRepository = messageRepository;

// Add some messages into GemFire for being seen
Message message = new Message();
message.setMessageId("1");
message.setMessage("Hello JavaBeat !");

messageRepository.save(message);

// Add
message = new Message();
message.setMessageId("2");
message.setMessage("Hello GemFire REST");
messageRepository.save(message);
System.out.println("Messages are filled");
}
}
[/code]

6. Spring Context Configuration

This is the simple XML configuration for the spring beans.

SpringContext.xml

[code lang=”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:gfe-data="http://www.springframework.org/schema/data/gemfire"
xmlns:gfe="http://www.springframework.org/schema/gemfire"
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.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/data/gemfire http://www.springframework.org/schema/data/gemfire/spring-data-gemfire.xsd http://www.springframework.org/schema/gemfire http://www.springframework.org/schema/gemfire/spring-gemfire.xsd">
<!– Search for spring components –>
<context:component-scan base-package="net.javabeat"></context:component-scan>
<!– Declare GemFire Cache –>
<gfe:cache/>
<!– Local region for being used by the Message –>
<gfe:local-region id="messages" value-constraint="net.javabeat.springdata.data.Message"/>
<!– Search for GemFire repositories –>
<gfe-data:repositories base-package="net.javabeat.springdata.repo"/>
</beans>
[/code]

7. Repository Rest Dispatcher Servlet & Web deployment Descriptor

To install spring data rest alongside your existing web application, you need to include the appropriate configuration in the deployment descriptor. Spring Data REST configuration is defined in a class called RepositoryRestMvcConfiguration. Since Spring Data REST is simply a spring MVC application, you only need to include the RepositoryRestDispatcherServlet for being able to use the REST functionality when it comes to configure the spring framework using the XML. The web deployment descriptor seems like below.

web.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" metadata-complete="true" version="2.5">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config/SpringContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>org.springframework.data.rest.webmvc.RepositoryRestDispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
[/code]

8. Expose GemFire Repositories Directly

It’s just a try for exposing the GemFire repositories through google Dev HTTP. For doing that just follow the below steps:

  • From chrome browser open the Dev HTTP Client.
  • Type your host followed by the port number followed with the web context for the deployed application which should results in the token http://localhost:8080/SpringData-GemFire-REST-1.0.
  • For consuming the messages resources, you have to add the RepositoryRestDispactherServlet mapping url which mentioned in the web.xml and it’s /rest/ which results in url value like http://localhost:8080/SpringData-GemFire-REST-jQuery/rest/
  • Add the The path segment under which this resource is to be exported. that value was provided using the path property at the header of the MessageRepository in order to be able of exposing the messages resource like below.

Spring Data REST GemFire jQuery Consumption

9. Spring Data REST & jQuery Integration

As all of us knew, jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multiple browsers. Also, it uses the json response as you would see. Look at the below JQuery example to know how to access Spring Data REST services through jQUery.

index.html

[code lang=”xml”]
<html>
<head>
<title>JavaBeat Tutorial</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="messages.js"></script>
</head>
<body>
<div style="width:50%">
<h2>JavaBeat Tutorial</h2>
<h2>GemFire + REST + JQuery</h2>
<div id="messages">

</div>
</div>
</body>
</html>
[/code]

messages.js

[code lang=”java”]
$(document).ready(function() {
$.ajax({
url: "http://localhost:8080/SpringData-GemFire-REST-JQuery-1.0/rest/messages"
}).then(function(data) {
var messages = data["_embedded"]["messages"];
var value = "";
$("#messages").html("Message #1 :: Message Content :: " + messages[0].message + " :: Message Link :: <a href=’"+messages[0]._links.self.href+"’>Link</a>" + ‘<br>’ +
"Message #2 :: Message Content :: " + messages[1].message + " :: Message Link :: <a href=’"+messages[1]._links.self.href+"’>Link</a>");
});
});
[/code]

10. Spring Data REST & jQuery Demo

Spring Data REST & jQuery Consumption

Spring Data REST Consumption

11. Summary

In this tutorial Spring Data REST service is consumed using the jQuery library and the result of consumption has been displayed into HTML page. In our previous tutorial we have explained the similar Spring Data REST to be accessed using the AngularJS library. If you have any questions, please write it in the comments section.

Download Source Code

[wpdm_file id=107]

Filed Under: Spring Framework Tagged With: jQuery, Spring Data, Spring REST

Spring Data + MongoDB + REST Shell Integration

May 19, 2014 by Amr Mohammed Leave a Comment

This tutorial guides you through an example for understanding the integration between Spring Data, Spring REST and MongoDB. As you are going to use the rest-shell for achieving different operations against database. Entities will be persisted into MongoDB in the form of which an outer entity will save a reference to the inner one. Unlike the most of the examples that are published in previous tutorials here. Also, you’d see the integrating of Spring Boot for initializing of an embedded Apache Tomcat.

Also read:

  • Spring Roo + Spring Data JPA Repositories + Eclipse Integration
  • Spring Data JPA + Querydsl
  • Spring Data + MongoDB 
  • Connect With Us : Google+ | Twitter | FaceBook

1. Tools Required

The required platforms and environments for this tutorial:

  • JDK 1.7.
  • Maven 3.2.1.
  • Eclipse IDE Kepler 4.3.
  • Spring Data
  • MongoDB

2. Java Beans (Entities)

Address and Employees entities will be used for defining the business domain.

Address.java

[code lang=”java”]
package net.javabeat.springdata.data;

import javax.persistence.Id;

import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

@Document(collection="Address")
public class Address {
@Id
@Field
private String id;
@Field
private String addressCountry = "";
@Field
private String addressCity = "";

public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAddressCountry() {
return addressCountry;
}
public void setAddressCountry(String addressCountry) {
this.addressCountry = addressCountry;
}
public String getAddressCity() {
return addressCity;
}
public void setAddressCity(String addressCity) {
this.addressCity = addressCity;
}
}
[/code]

Employee.java

[code lang=”java”]
package net.javabeat.springdata.data;

import javax.persistence.Id;

import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

@Document(collection="Employee")
public class Employee {
@Id
@Field
private String id;
@Field
private String employeeName;
@DBRef
private Address address;

public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
[/code]

3. Spring Data Repositories

It’s the spring data repositories that will be used for communicating with the MongoDB for any CRUD operation.

AddressRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.data.Address;

import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel="address",path="address")
public interface AddressRepository extends CrudRepository<Address,String>{
}
[/code]

EmployeeRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.data.Employee;

import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel="employee",path="employee")
public interface EmployeeRepository extends CrudRepository<Employee, String>{
}
[/code]

4. Spring Context Configuration

Here is the required spring context configuration for communicating to the MongoDB.

SpringContext.xml

[code lang=”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:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

<!– Register Mongo Instance –>
<mongo:mongo id="mongo" host="localhost" port="27017" />
<!– for defining mongo template –>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongo" />
<constructor-arg name="databaseName" value="JavaBeat" />
</bean>

<!– For consider the using of annotations foe defining Spring Bean –>
<context:annotation-config />

<!– For defining Spring Bean –>
<context:component-scan base-package="net.javabeat.springdata.beans" />
<!– For defining mongo repository –>
<mongo:repositories base-package="net.javabeat.springdata.repo" />

</beans>
[/code]

5. Executable Application

This stand alone spring boot application will start this sample application.

Executable.java

[code lang=”java”]
package net.javabeat.springdata.executable;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;

@Configuration
@EnableMongoRepositories
@Import(RepositoryRestMvcConfiguration.class)
@ImportResource("classpath:SpringContext.xml")
@EnableAutoConfiguration
public class Executable {

public static void main(String[] args) {
SpringApplication.run(Executable.class, args);
}
}
[/code]

6. Maven Dependencies

It’s the maven libraries that define the required libraries for the suggested communication with the MongoDB through Spring REST.

pom.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>net.javabeat.springdata</groupId>
<artifactId>SpringData-MongoDB-REST</artifactId>
<version>1.0</version>
<packaging>jar</packaging>

<name>Spring Data</name>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.0.2.RELEASE</version>
</parent>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

<dependencies>

<!– Dependency for Spring Boot –>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-core</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
</dependency>
</dependencies>

</project>

[/code]

7. Install REST Shell

Rest shell is the native engine that provided by Spring and can be downloaded from here. After downloading the shell, you can unzip it into any location that you suggested.

Open the command line and navigate into the unzipped location that you already selected before and type into command line rest-shell and press enter. Be sure that your application is up and running before any further uses of the shell.

Rest-Shell Starting Up

8. MongoDB + Spring Data Repository + Spring REST Demo

Inside this demonstration, set of snapshots has been used for clarifying the operations of READ, PERSIST & DELETE operations.

List all of collections inside MongoDB

Follow address - getting the address of id 1

Follow employee - getting the employee of id 1

Create Employee and Associate it with the already created Address entity

List of Addresses

List all employees

9. MongoDB Collections

Database address records

Database employee records

10. Accessing Through HTTP

HTTP employees list

11. Summary

Congratulations, you’ve just developed an application that uses the Spring REST for getting successful operations against MongoDB.

Download Source Code

[wpdm_file id=100]

Filed Under: Spring Framework Tagged With: MongoDB, Spring Boot, Spring Data, Spring REST

Spring Data Neo4j 3 REST Exporter – Converting Spring Boot JAR Application To WAR

May 16, 2014 by Amr Mohammed Leave a Comment

This tutorial is the continuation of the previous tutorial for building the standalone application using spring boot. This guide walks you through the process of converting a runnable JAR application that was built with Spring Boot into a WAR file that you can run in any standard servlet container. You’ll take a simple Spring MVC web app and build a WAR file using Spring Boot.

Also read:

  • Spring Roo + Spring Data JPA Repositories + Eclipse Integration
  • Spring Data JPA + Querydsl
  • Spring Data + MongoDB 
  • Connect With Us : Google+ | Twitter | FaceBook

1. Java Beans

It’s the entities that will be used for representing the persisted nodes.

Address.java

[code lang=”java”]
package net.javabeat.springdata.data;

import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.NodeEntity;

@NodeEntity
public class Address{

@GraphId
private Long id;

private String addressCountry;

private String addressCity;

public Long getId() {
return id;
}

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

public String getAddressCountry() {
return addressCountry;
}

public void setAddressCountry(String addressCountry) {
this.addressCountry = addressCountry;
}

public String getAddressCity() {
return addressCity;
}

public void setAddressCity(String addressCity) {
this.addressCity = addressCity;
}
}
[/code]

Employee.java

[code lang=”java”]
package net.javabeat.springdata.data;

import org.springframework.data.neo4j.annotation.Fetch;
import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.NodeEntity;
import org.springframework.data.neo4j.annotation.RelatedTo;

@NodeEntity
public class Employee{
@GraphId
private Long id;

private String employeeName;

@Fetch
@RelatedTo(type="Address")
private Address address = new Address();

public Long getId() {
return id;
}

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

public String getEmployeeName() {
return employeeName;
}

public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}
}
[/code]

2. Spring Data Neo4j Repositories

It’s the repositories that will be used for operating against the graph database through different operations.

EmployeeRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.data.Employee;

import org.springframework.data.neo4j.repository.GraphRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel = "employee", path = "employee")
public interface EmployeeRepository extends GraphRepository<Employee>{

}
[/code]

AddressRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.data.Address;

import org.springframework.data.neo4j.repository.GraphRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel = "address", path = "address")
public interface AddressRepository extends GraphRepository<Address>{

}

[/code]

3. Spring Controller

It’s Spring MVC controller that allows you to quickly build controllers for your web site. The controller is very simple, in that the @Controller annotation tells the container that this class contains web application paths. @RequestMapping annotation ensures that HTTP request to /query mapped to the query method and /execute mapped to the execute one.

DataController.java

[code lang=”java”]
package net.javabeat.springdata.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.RequestParam;

@Controller
public class DataController {

@RequestMapping(value="/execute", method=RequestMethod.GET,params="query")
public String execute(@RequestParam ("query")String query,HttpServletRequest request, HttpServletResponse response) {
try {
response.getWriter().write("<h1>JavaBeat Tutorials</h1>");
response.getWriter().write("<h2>Neo4j + REST + Spring Boot WAR Application</h2>");
URL url = new URL("http", "localhost",8080,"/JavaBeat-Neo4j-REST/"+request.getParameter("query"));
HttpURLConnection c = (HttpURLConnection)url.openConnection();
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.connect();
int status = c.getResponseCode();

switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
response.getWriter().append(line+"\n");
}
br.close();
response.flushBuffer();
return "resultTemplate";
}

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "resultTemplate";
}

@RequestMapping(value="/query", method=RequestMethod.GET)
public String query(HttpServletRequest request, HttpServletResponse response) {
try {
response.getWriter().write("<h1>JavaBeat Tutorials</h1>");
response.getWriter().write("<h2>Neo4j + REST + Spring Boot WAR Application</h2>");
} catch (IOException e) {
e.printStackTrace();
}
return "queryTemplate";
}
}
[/code]

4. Thymeleaf Templates

Spring Boot automatically added Thymeleaf beans to the application context to convert a request for the Thymeleaf template located at

  • src/main/resource/templates/queryTemplate.html, which responsible for gathering the query from the user.
  • src/main/resource/templates/resultTemplate.html, which responsible for displaying the result of the queries.

Those templates has very basic HTML elements and no actual Thymeleaf code.

queryTemplate.html

[code lang=”xml”]
<html>
<body>
<form id="form" action="execute" method="GET">
<p>Enter Query You Want To Be Executed Right Below:</p>
<br />
<input id="query" name="query" type="text" value=""/>
<input type="submit" value="Query !"/>
</form>
</body>
</html>
[/code]

resultTemplate.html

[code lang=”xml”]
<!– It’s filled by using the controller response.getWriter() –>
[/code]

4. Executable Application

Already, you have made the application an executable JAR file in the first part of this tutorial. You package everything in a single, executable JAR driven by main() method. Along the way, you use Spring’s support for embedding the Tomcat servlet container as the HTTP runtime, instead of deploying to an external instance. In this part of tutorial, you will see how to build WAR file to run it on a standard container.

Executable.java

[code lang=”java”]
package net.javabeat.springdata.executable;

import org.neo4j.graphdb.GraphDatabaseService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.neo4j.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.config.Neo4jConfiguration;
import org.springframework.data.neo4j.rest.SpringRestGraphDatabase;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
@ComponentScan("net.javabeat")
@Configuration
@EnableNeo4jRepositories("net.javabeat.springdata.repo")
@Import(RepositoryRestMvcConfiguration.class)
@EnableAutoConfiguration
public class Executable extends Neo4jConfiguration {

public Executable() {
}

@Bean(destroyMethod = "shutdown")
public GraphDatabaseService graphDatabaseService() {
SpringRestGraphDatabase service = new SpringRestGraphDatabase("http://localhost:7474/db/data/");
this.setBasePackage("net.javabeat");
return service;
}

public static void main(String[] args) {
SpringApplication.run(Executable.class, args);
}
}
[/code]

5. Run the Service

If you’ve ran the service by using the java -jar or by using the Eclipse IDE running Java application, you will be able to display the templates contents using a resource identifier started with http://localhost:8080/query.

Execute Spring Boot Application Using JAVA

But even if you have provided the input shown a query like employee, you will not be able to see the result, cause the remaining functionality needs the remaining configuration for web application.

6. Build WAR File

The application you built up to this point is configured to generate a JAR artifcat. To switch it to WAR file, you need change the packaging attribute in the pom.xml into war. Also, if you want to deploy the WAR file into external container, you also need to mark the embedded container dependencies as provided.

7. Initialize the Servlet

Previously, the application contained a public static void main() method which consider a Spring Boot configuration was used when using the java -jar command. By converting this into WAR file with no XML files, you need a different message to the servlet container on how to launch the application. So that you have to provide your own WebXML Java class.

WebXML.java

[code lang=”java”]
package net.javabeat.springdata.webXML;

import net.javabeat.springdata.executable.Executable;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;

public class WepXML extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Executable.class);
}
}
[/code]

WebXML is a pure Java class that provides an alternative to creating a web.xml. It extends the SpringServletInitializer class. This extension offers many configurable options by overriding methods. But one required method is configure().

Configure() provides the means to register the classes that are needed to launch the application. This is where you supply a handle to your Executable configuration. Even though public static void main() is no longer needed, you can leave that code in place.

8. Run the WAR file

It’s the demonstration that we would provide you for making everything clear for you. Just build your application and make sure maven has created your WAR. Put your WAR into the tomcat 8 webapp folder and starting the tomcat up. Another way you would follow by integrating your Eclipse IDE with your Tomcat 8 and Right Click on the project folder and use Run As.

Neo4j REST WAR Running Default Location Neo4j REST WAR Running Query Page Neo4j REST WAR Running Execute Page

Neo4j REST WAR Running Query Page Address Neo4j REST WAR Running Execute Page Address

Download Source Code

[wpdm_package id=’23180′]

Filed Under: Spring Framework Tagged With: Neo4j, Spring Boot, Spring Data, Spring REST, WAR

Spring Data Neo4j 3 REST Exporter (Java Application)

May 16, 2014 by Amr Mohammed Leave a Comment

This tutorial walks you through the process of creating an application that accesses graph-based data through a hypermedia-based RESTful front end. You’ll build a Spring application that let’s you create and retrieve Employee and Address objects stored in a Neo4j NoSQL database (Neo4j Server) using Spring Data REST. You’ll use the non embedded Neo4j for achieving the exporter, and the Tomcat 8 for running the Spring Boot application.

Also read:

  • Spring Roo + Spring Data JPA Repositories + Eclipse Integration
  • Spring Data JPA + Querydsl
  • Spring Data + MongoDB 
  • Connect With Us : Google+ | Twitter | FaceBook

1. Install Eclipse Tomcat 8 Plugin

You have to install and use the Tomcat 8 and JDK 1.7 to run the example application used in this tutorial. Eclipse IDE provides you the Tomcat 8 plugin that can be downloaded from here. Tomcat 8 support is not added to the Eclipse at the time of writing this tutorial. So, download the eclipse from the given link and use it.

After downloading the plugin you have to follow the below steps for completing the plugin installation:

  • Copy the downloaded file beside your root eclipse folder. Let you have an installed eclipse at D:\eclipse, the zip file should be beside the eclipse not within it.
  • Extract the zip file using extract here.
  • Restart the eclipse ide.
  • Install Tomcat 8 from here.
  • Extract your downloaded Tomcat at your preferred folder.
  • Add a new server using the new server wizard and make sure you have selected the Tomcat 8.
  • While you are installing the Tomcat 8 through wizard, you will be enforced to use a JDK .17 for completing the installation.

Tomcat 8 will not be shown in this tutorial, but it will be important in the next part when a Spring Boot pure Java Application converted into WAR. But the minimum requirement for running the Tomcat 8 is Java 7.

2. Java Beans

It’s the beans (Address and Employees) that will be used for REST exporting process, by which all of the persisted entities inside the Neo4j database have exposed using HTTP.

Address.java

[code lang=”java”]
package net.javabeat.springdata.data;

import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.NodeEntity;

@NodeEntity
public class Address{

@GraphId
private Long id;

private String addressCountry;

private String addressCity;

public Long getId() {
return id;
}

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

public String getAddressCountry() {
return addressCountry;
}

public void setAddressCountry(String addressCountry) {
this.addressCountry = addressCountry;
}

public String getAddressCity() {
return addressCity;
}

public void setAddressCity(String addressCity) {
this.addressCity = addressCity;
}
}
[/code]

Employee.java

[code lang=”java”]
package net.javabeat.springdata.data;

import org.springframework.data.neo4j.annotation.Fetch;
import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.NodeEntity;
import org.springframework.data.neo4j.annotation.RelatedTo;

@NodeEntity
public class Employee{
@GraphId
private Long id;

private String employeeName;

@Fetch
@RelatedTo(type="Address")
private Address address = new Address();

public Long getId() {
return id;
}

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

public String getEmployeeName() {
return employeeName;
}

public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}
}
[/code]

3. Spring Data Repositories

Create the spring data repositories for the each persistence type and leave the actual implementation to the spring data run time.

EmployeeRepositories.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.data.Employee;

import org.springframework.data.neo4j.repository.GraphRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel = "employee", path = "employee")
public interface EmployeeRepository extends GraphRepository<Employee>{}
[/code]

AddressRepositories.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.data.Address;

import org.springframework.data.neo4j.repository.GraphRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel = "address", path = "address")
public interface AddressRepository extends GraphRepository<Address>{}
[/code]

4. Executable Application

It’s the main application that uses the Spring Boot concept to execute the Spring Application. It contains the all configuration required for setting up the context as all of those required information such as the GraphDatabaseService, base package and the repositories package. Executable main class got executed using the normal execution for any Java Class which contains a main method. Spring Boot will use the Embedded Tomcat

Executable.java

[code lang=”java”]
package net.javabeat.springdata.executable;

import org.neo4j.graphdb.GraphDatabaseService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.neo4j.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.config.Neo4jConfiguration;
import org.springframework.data.neo4j.rest.SpringRestGraphDatabase;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;

@Configuration
@EnableNeo4jRepositories("net.javabeat.springdata.repo")
@Import(RepositoryRestMvcConfiguration.class)
@EnableAutoConfiguration
public class Executable extends Neo4jConfiguration {

public Executable() {
}

@Bean(destroyMethod = "shutdown")
public GraphDatabaseService graphDatabaseService() {
SpringRestGraphDatabase service = new SpringRestGraphDatabase("http://localhost:7474/db/data/");
this.setBasePackage("net.javabeat");
return service;
}

public static void main(String[] args) {
SpringApplication.run(Executable.class, args);
}
}
[/code]

5. Maven Dependencies

This pom.xml maven file defines all the dependencies used in this tutorial.

pom.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<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>next.javabeat.jsf</groupId>
<artifactId>JavaBeat-Neo4j-REST</artifactId>
<packaging>jar</packaging>
<version>1.0</version>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.0.2.RELEASE</version>
</parent>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j-rest</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
</dependency>
</dependencies>

<properties>
<!– use UTF-8 for everything –>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<start-class>net.javabeat.springdata.executable.Executable</start-class>
</properties>

<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

<repositories>
<repository>
<id>spring-milestones</id>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>

</project>
[/code]

6. Neo4j REST Demo

It’s just a demonstration for the form of the JSON response, once an HTTP request has been sent from the browser. For exposing the JSON reponse, we used the Google HTTP DEV plugin.

Neo4j REST

Neo4j-REST-ADDRESS

Neo4j-REST-EMPLOYEE

Download Source Code

[wpdm_package id=’23182′]

Filed Under: Spring Framework Tagged With: Neo4j, Spring Boot, Spring Data, Spring REST

Spring Data REST Exporter

May 8, 2014 by Amr Mohammed Leave a Comment

This tutorial provides the detailed instruction on how to use Spring Data REST project in your Spring MVC applications to export your JPA entities. The greatest advantage of using the Spring Data REST is that, it easily exports the entities and made available through the HTTP protocol.

Using Spring Data REST repository exporter project, you can now export these managed entities via a REST web service to easily interact with the data. The exporter mechanism will transparently expose a resource per repository, map CRUD operations onto HTTP methods for that resource, and provide facility to execute the query methods exposed on the repository interface.

But before getting started with Spring Data Exporter , it is important to have a understanding on the REST concept. Also, it is worthy to know that this tutorial will try to simplify the concept of REST by considering the Spring Boot for implementing a standalone spring mvc application.

1. REST

REST stands for Representational State Transfer (REST) is an architectural style. It is a generalization of the principles behind the HTTP protocol, from which it derives the following core concepts:

  • Resources: Systems expose resources to other systems: an Employee, an Address, and so on.
  • Identifiers: These resources can be addressed through an identifier. In the HTTP world, these identifiers are URIs
  • Verbs: Each resource can be accessed and manipulated though a well-defined set of verbs. The most common verbs used in the HTTP are GET, POST, DELETE, HEAD and OPTIONS.
  • Representations: A client never interacts with the resource directly but rather through representations of it. As you will be seeing inside this tutorial, the JSON should be used for representing the resources.

2. Persistence Entities

We are using the Employee and Address persistence entity for this tutorials. Lets look at the implementation of these entities and how it is modeled in the database schema. Note that this example uses Java Persistence API (JPA) for the entity exporter. We can use any other persistence provider supported by Spring Data Rest for exporting the entities. Only change will be the persistence repository.

Employee.java

[code lang=”java”]
package net.javabeat.springdata.jpa.data;

import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

@Entity
public class Employee {

@Id
private Integer employeeId;

@Basic(optional = false)
private String employeeName;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "Address")
private Address address;

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

public Integer getEmployeeId() {
return employeeId;
}

public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}

public String getEmployeeName() {
return employeeName;
}

public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}

public boolean equals(Object obj){
if(obj instanceof Employee){
Employee emp = (Employee)obj;
if(this.employeeId == emp.employeeId){
return true;
}
}
return false;
}

public int hashCode(){
return this.employeeId;
}

}
[/code]

Address.java

[code lang=”java”]
package net.javabeat.springdata.jpa.data;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;

@Entity(name = "address")
public class Address {
@Id
private Integer addressId;
private String addressCountry;
private String addressCity;

@OneToOne(cascade = CascadeType.ALL, mappedBy = "address")
private Employee employee;

public Employee getEmployee() {
return employee;
}

public void setEmployee(Employee employee) {
this.employee = employee;
}

public int getAddressId() {
return addressId;
}

public void setAddressId(int addressId) {
this.addressId = addressId;
}

public String getAddressCountry() {
return addressCountry;
}

public void setAddressCountry(String addressCountry) {
this.addressCountry = addressCountry;
}

public String getAddressCity() {
return addressCity;
}

public void setAddressCity(String addressCity) {
this.addressCity = addressCity;
}
}
[/code]

For your convenience, we have provided the database schema design which will help you for writing the example. Also you can download the example source code at the bottom of this tutorial.

Employee Table

Employee Foreign Key

Address Table

3. JPA Context Configurations

Here is the persistence context used for this tutorial. This configuration file provides configuration details for the MYSQL database driver and the above mentioned persistence entities.

persistence.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="SpringData" transaction-type="RESOURCE_LOCAL">
<class>net.javabeat.springdata.jpa.data.Employee</class>
<class>net.javabeat.springdata.jpa.data.Address</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/JavaBeat" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="eclipselink.logging.level" value="OFF" />
</properties>
</persistence-unit>
</persistence>
[/code]

4. Spring Application Context Configurations

Here is the spring context configuration for this example. For more details about the configurations, please read Spring Data – JPA tutorial.

SpringContext.xml

[code lang=”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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

<!– For consider the using of annotations foe defining Spring Bean –>
<context:annotation-config />

<!– For defining Spring Bean –>
<context:component-scan base-package="net.javabeat.springdata.beans" />

<!– For bootstrapping the Spring Repository –>
<jpa:repositories base-package="net.javabeat.springdata.repo" />

<!– Necessary to get the entity manager injected into the factory bean –>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

<!– Define EclipseLink JPA Vendor Adapter –>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="databasePlatform" value="org.eclipse.persistence.platform.database.MySQLPlatform" />
<property name="generateDdl" value="false" />
<property name="showSql" value="true" />
</bean>

<!– Entity Manager Factory –>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="SpringData"></property>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
</bean>

<!– Transaction Manager –>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<!– Enable Transactional Manner –>
<tx:annotation-driven transaction-manager="transactionManager" />

</beans>
[/code]

5. Spring REST Repositories

For exposing your repositories as a REST, you have to define the repositories using the @RepositoryRestResource annotation.

EmployeeRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.jpa.data.Employee;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel = "employee", path = "employee")
public interface EmployeeRepository extends CrudRepository<Employee, Integer>{}
[/code]

AddressRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.jpa.data.Address;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel = "address", path = "address")
public interface AddressRepository extends CrudRepository<Address,Integer>{}
[/code]

6. Maven Dependencies For Spring Data Rest

pom.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.javabeat.springdata</groupId>
<artifactId>SpringData-JPA</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>Spring Data</name>
<!– Inherit defaults from Spring Boot –>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.0.2.RELEASE</version>
</parent>
<dependencies>
<!– Dependencies for Eclipse JPA Persistence API –>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.0-RC1</version>
<exclusions>
<exclusion>
<groupId>org.eclipse.persistence</groupId>
<artifactId>commonj.sdo</artifactId>
</exclusion>
</exclusions>
</dependency>
<!– Dependency for MySql Java connector –>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!– Spring Data Dependency –>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<!– Dependency for REST Exporter –>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
</dependency>
<!– Required Spring Boot Web Application Dependency –>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!– Required Spring Boot JPA Dependency –>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
</project>
[/code]

7. Spring Data REST Exporter Example Application

This example application is executed using the Spring Boot application. If you have the Tomcat runtime in your machine, this below example will embed the tomcat and spring mvc application.

Executable.java

[code lang=”java”]
package net.javabeat.springdata.executable;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;

@Configuration
@EnableJpaRepositories
@Import(RepositoryRestMvcConfiguration.class)
@ImportResource("classpath:SpringContext.xml")
@EnableAutoConfiguration
public class Executable {

public static void main(String[] args) {
SpringApplication.run(Executable.class, args);
}
}
[/code]

8. Running Application

You can now access the Spring Data Rest through browser which will be exposed as the REST services.

Address Repository

Access Spring Repositories

Employee Repository

9. Summary

Spring Data provides the Spring Developer that ability to create a REST web services against already user defined CRUD repositories. This service is limited to the CRUD repositories but in the next coming releases other types of repositories should be supported.

Download Source Code

  • Download Source Code

Filed Under: Spring Framework Tagged With: Spring Boot, Spring Data, Spring REST

RestController Annotation in Spring 4

November 21, 2013 by Krishna Srinivasan Leave a Comment

In this tutorial I am going to explain one of the new spring annotation @RestController introduced as part Spring 4 release. The spring 4 version comes up with lot of exciting new features. One of the API improvements is new RestController annotation which is inherited from the @Controller annotation.

If you are interested in receiving more updates related to spring framework, spring boot, etc. please subscribe here.

RestController Annotation in Spring 4

RestController in Spring 4

Prior to the version 4.0, all the Spring MVC components has to use the common @Controller annotation to mark that as the controller servlet. When you implement a RESTful web services, the response would be always sent with the response body. To make this simple, Spring 4.0 has provided a specialized version of controller. Look at the definition of the @RestController implementation.

[code lang=”java”]
@Target(value=TYPE)
@Retention(value=RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController[/code]

Spring docs says:

A convenience annotation that is itself annotated with @Controller and @ResponseBody. Types that carry this annotation are treated as controllers where @RequestMapping methods assume @ResponseBody semantics by default.

@ResponseBody – As of version 4.0 this annotation can also be added on the type level in which case is inherited and does not need to be added on the method level.

This tutorial explains with a simple example on how to use the annotation @RestController. I am using the same example of Content Negotiation in Spring MVC 3.2. If you compare both the examples, you would notice the difference.

RestController Example

Here is the example code for RestController annotation.

  • Also Read : REST API Best Practices

UserDetails.java

[code lang=”java”]package javabeat.net.rest;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class UserDetails {
private String userName;
private String emailId;

@XmlAttribute
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}

@XmlAttribute
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
}[/code]

SpringRestControllerDemo.java

[code lang=”java”]package javabeat.net.rest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SpringRestControllerDemo {
@Autowired UserDetails userDetails;
@RequestMapping(value="/springcontent",
method=RequestMethod.GET,produces={"application/xml", "application/json"})
@ResponseStatus(HttpStatus.OK)
public UserDetails getUser() {
UserDetails userDetails = new UserDetails();
userDetails.setUserName("Krishna");
userDetails.setEmailId("krishna@gmail.com");
return userDetails;
}

@RequestMapping(value="/springcontent.htm", method=RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public String getUserHtml() {
//Test HTML view
return "example";
}
}[/code]

dispatcher-servlet.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="javabeat.net.rest" />

<bean id="userDetails" class="javabeat.net.rest.UserDetails"/>
<mvc:annotation-driven content-negotiation-manager="contentManager"/>
<bean id="contentManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="true"/>
<property name="ignoreAcceptHeader" value="true" />
<property name="defaultContentType" value="text/html" />
<property name="useJaf" value="false"/>
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="html" value="text/html" />
<entry key="xml" value="application/xml" />
</map>
</property>
</bean>
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>

</beans>[/code]

With this new feature, we can use this specialized controller instead using the generic @Controller for the REST services.

Summary

In this tutorial I have explained the use of RestController annotation in spring mvc application. I have used the XML configurations for writing this example.

If you have any questions on using RestController, please drop your comments.

Filed Under: Spring Framework Tagged With: Spring 4 Tutorials, Spring REST

Spring and Jersey Integration Example

November 14, 2013 by Krishna Srinivasan Leave a Comment

This tutorial explains how to write a simple example using Spring and Jersey. This example uses Jersey for the REST implementation, Spring is used for managing the beans. In my previous tutorial, I have explained how to write a simple REST application using Jersey. We also can use Spring alone for implementing the RESTful web services.

1. Add Jersey and Spring JAR files

Look at the below picture for the list of JARs added for this application

jersey-spring-jars

2. Create a Spring Bean

[code lang=”java”]
package org.jersey.examples;

public class SpringBeanExample{
public String getValue(){
return "Spring and Jersey Integration";
}
}
[/code]

3. Create Jersey Service

[code lang=”java”]
package org.jersey.examples;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

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

@Component
@Path("/hello")
public class JerseySimpleExample {
@Autowired
SpringBeanExample springBean;

@GET
@Path("/javabeat")
public Response getMessage() {
String result = springBean.getValue();
return Response.status(200).entity(result).build();
}
}
[/code]

4. Spring Configuration XML

[code lang=”xml”]
<context:component-scan base-package="org.jersey.examples" />
<bean id=0"springBean" class="org.jersey.examples.SpringBean" />
[/code]

5. Web.xml Configuration

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Jersey Example</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>\WEB-INF\dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>jersey</servlet-name>
<servlet-class>
com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class>
<init-param>
<param-name>com.sun.jersey.spi.spring.container.servlet.SpringServlet</param-name>
<param-value>org.jersey.examples</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/jersey/*</url-pattern>
</servlet-mapping>
</web-app>
[/code]

Filed Under: Spring Framework Tagged With: Jersey, Spring Integration, Spring REST

How to use Spring HATEOAS LinkBuilder API with Spring REST?

October 26, 2013 by Krishna Srinivasan Leave a Comment

Hypermedia as the Engine of Application State (HATEOAS) is a constraint for the REST architecture. If you are not familiar with the REST web services, REST is services exposed using an URI that is shared to the clients. A client can directly access that given URI to get the response which is mostly a JSON or XML type. It is very popular because it is light weight compared to the traditional web services. However, the drawback on this approach is that each service would have a seperate URL to be defined. It is not easy to remember and maintain the complete list of services and state transition by the clients.

Take an example, If you write a RESTful service to control the Virtual Machines. The different state of the VM is start, stop, restart. Client doesn’t aware of the current status of the VM. When you invoke a REST service for starting a VM that is already running, then in response server should send a next recommended action for the client. This us known as HATEOAS or constraint for the RESTful web services. Here the action is taken by the server instead of REST client.

Spring HATEOAS is a new project in the early stage of its release. The latest version available to the public is  0.7. Spring provides RESTful support through its Spring MVC module. With the existing Spring MVC application, you can use Spring HATEOAS APIs to provide the HATEOAS support.

This project is in the initial stage, I have created a very simple example code to demonstrated the HATSOAS APIs with the LinkBuilder APIs. It is the first step on understanding the Spring HATEOAS project. Here is the steps to understand this code sample.

1. Add Spring HATEOAS Dependencies

If you are using Maven, please add these dependencies to your pom.xml file.

[code lang=”xml”]
<dependencies>
<dependency>
<groupId>org.springframework.hateoas</groupId>
<artifactId>spring-hateoas</artifactId>
<version>0.7.0.RELEASE</version>
</dependency>
</dependencies>
[/code]

2. Necessary Library files to Run Spring HATEOAS

If you are not using the maven build, look at below folder structure to understand the list of library files used for this demo. Also add all the libraries required to run a spring mvc web application.Also add these two jar files mockito-all-1.9.5.jar and org.apache.servicemix.bundles.aopalliance-1.0-1.0.0-rc1.jar which is internally used.

spring-mvc-folder

3. Setup Spring MVC Application

Setup a spring mvc application. I am not explaining that in detail, You can read our previous articles and complete that setup.

4. Controller Implementation With LinkBuilder API

Create VmStatusController.java.

[code lang=”java”]
package javabeat.net.springhateoas;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
import org.springframework.hateoas.LinkDiscoverer;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class VmStatusController {

private static final String TEMPLATE = "Virtual Machine Status %s ";

@RequestMapping("/controlvm")
@ResponseBody
public HttpEntity<VmStatus> controlvm(@RequestParam(value="status",required=false,
defaultValue="start") String status ){
VmStatus vmStatus = new VmStatus(String.format(TEMPLATE, status));
vmStatus.add(linkTo(methodOn(VmStatusController.class).controlvm(status)).withSelfRel());
return new ResponseEntity<VmStatus>(vmStatus, HttpStatus.OK);
}
}
[/code]

  1. Look at the first two import statements, those are static imports as part of the spring hateoas api. linkTo and methodOn are used for adding the link to the response.
  2. Response object is HttpEntiry with the model object which extends the ResourceSupport. Look at the below code.
  3. The method arguments are similar to the normal spring mvc application.
  4. We are creating a ResourceSupport object by passing the template string to the constructor method.
  5. vmStatus.add is the most important code where we are adding the link by calling withSelfRel.

5. ResourceSupport Implementation

Create VmStatus.java

  • ResourceSupport is the representation of resources. This class allows us to add the links and manage it.

[code lang=”java”]
package javabeat.net.springhateoas;
import org.springframework.hateoas.ResourceSupport;
public class VmStatus extends ResourceSupport{

private final String content;

public VmStatus(String content){
this.content = content;
}

public String getContent(){
return content;
}
}
[/code]

6. Run the sample application

Deploy the application in your server and access the application using this url;

[code]http://localhost:8080/SpringExamples/controlvm?name=start[/code]

Your browser will display the output as:

[code]{"content":"Virtual Machine Status start ","links":[{"rel":"test","href":"http://localhost:8080/SpringExamples/controlvm?status=start"}]}[/code]

When you change the name in the URL, the response also will be updated. If you have any questions, please write it in the comments section. In my future articles i will  write few more advanced concepts on the Spring HATEOAS.

Filed Under: Spring Framework Tagged With: Spring HATEOAS, Spring REST

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved