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
  • Contact Us

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 Repository + Sencha Touch Integration

June 5, 2014 by Amr Mohammed Leave a Comment

Spring Data provides you several ways of consuming the REST repositories through a JavaScript frameworks. We have already provided a set of tutorials that discussed about using Spring Data REST with jQuery, AngularJS, Backbone.js and Rest.js. For this tutorial we’re going to explain you how could Sencha Touch be integrated for accessing the services.

Sencha Touch, a high-performance HTML5 mobile application framework, is the cornerstone of the Sencha HTML5 platform. Built for enabling world-class user experiences, Sencha Touch is the only framework that enables developers to build powerful apps that work on iOS, Android, BlackBerry, Windows Phone, and more.

Our goal of introducing this tutorial isn’t going deep into discussing the Sencha Touch framework, but it’s simply a normal sample adhered the Sencha Touch Model, View & Store modules.

In this tutorial, a gemfire MessageRepository will be exported using the REST exporter, as the GemFireBean will populate a dummy message into gemfire in-memory cache. A Sencha Touch framework components will be contribute each other for consuming the populated messages. Let’s see how could implement that scenario, meanwhile you can contribute us by leave your comments in the below comments section.

1. Project Structure

When it comes to implement a Sencha Touch modules, you have to follow the below structure at least for those files related to the Sencha itself. So, be sure that your model, view and store JavaScript files are located under app folder followed by the type of the module. Look at the structure.

Spring Data REST - Sencha Touch - Project Structure

As you’ve noted, MessageModel, MessageStore and MessageView are located under folders represents their type. The exception there, is the MessageApplication which referenced by the index.html and by that it could be located anywhere you want.

2. Tools Used

  • JDK 1.6. Apache Tomcat 7.
  • GemFire 7.0.1 Platform (JAR distribution)
  • Maven 3.
  • Tomcat 7.
  • Sencha Touch
  • Spring Data
  • Spring Framework

3. Persistent Entities

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.  Nothing new here, a Message entity will be the only entity where the persistent store is a gemfire.

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]

5. Spring Service

The main goal of implementing such a service is to allow the application populating a dummy message into gemfire in-memory cache. @Autowired is used for annotating the setMessageRepository and that implementation gives you the ability to inject/wired the repository proxy by using the setter rather than the field itself. That’s type of injection allows you to add whatever you want of business logic. To serve our purpose, we add the needed code for populating the message into gemfire cache.

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("Spring Data REST resources can be consumed by different JavaScript framework \n One of the most important framework here is Sencha Touch");

messageRepository.save(message);

}
}
[/code]

6. Spring Configurations

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="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 steps for exposing the GemFire repositories through using of google Dev HTTP. For doing that just follow the below steps:

  • Open Google Chrome Http Dev.
  • 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-SenchaTouch-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-SenchaTouch-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.

Sencha Touch - Exporting GemFire Repository

9. Implement Sencha Touch Modules

To implement the Sencha Touch Modules you have to follow the below steps:

  • Create a model by developing an Ext model named MessageModel. Place this model in the app/model directory. This is the default location for Sencha Touch models and will allow Sencha’s loader to find it. MessageModel extends Ext.data.Model and defines two fields: message and href.

MessageModel.js

[code lang=”java”]
Ext.define(‘JavaBeat.model.MessageModel’, {
extend: ‘Ext.data.Model’,
config: {
fields: [
{
name:’message’,
name:’href’
}
]
}
});
[/code]

  • Create a view by using Sencha’s Ext.Panel can be used as a simple view. This file should also be placed in Sencha’s default location for views /app/view. The contents of the view are defined by the template described in the tpl config option. Those braced tokens (i.e. {message}) will be replaced by the model fields when the view is rendered.

MessageView.js

[code lang=”java”]
Ext.define(‘JavaBeat.view.MessageView’, {
extend: ‘Ext.Panel’,
config: {
fullscreen: true,
tpl:’<p>Message #1 :: {message} :: <a href=’+"{href}"+’>Message Link</a></p>’
}
});
[/code]

  • Next, create an Ext store that will load the model. The store extends Ext.data.store and references our MessageModel. To instruct the store to use REST proxy, we configure it with a proxy definition object with type:”rest” and then point it at our REST endpoint url.

MessageStore.js

[code lang=”java”]
Ext.define(‘JavaBeat.store.MessagesStore’, {
extend: ‘Ext.data.Store’,
config: {
model: ‘JavaBeat.model.MessageModel’,
proxy: {
type: ‘rest’,
url: ‘http://localhost:8080/SpringData-GemFire-REST-SenchaTouch-1.0/rest/messages’
}
}
});
[/code]

  • Next, create an Ext.application object using Sencha’s Ext.application shortcut function. The application object automatically resolves the location of the models, views, and stores if you follow Sencha’s default directory convention as we’ve mentioned above. You must also specify the model, view and store in the models, views, and stores arrays so that Sencha’s loader can find and fetch those files. Adding a launch callback so that the application will be composed after all files have loaded. Inside this callback, create an instance of the view and an instance of the store. Configure the store to autoload so it will immediately fetch the model at the endpoint url. After that, you have to add a load listener to move the fetched data into the view. As you’ve seen, some additional instructions that have been added for manipulating the response to be stored inside array of messages.

MessageApplication.js

[code lang=”java”]
Ext.application({
name: ‘JavaBeat’,
models: [ ‘MessageModel’ ],
stores: [ ‘MessagesStore’ ],
views: [ ‘MessageView’ ],
launch: function () {

var view = Ext.create(‘JavaBeat.view.MessageView’, {});

Ext.create(‘JavaBeat.store.MessagesStore’, {
autoLoad: true,
listeners: {
load: function (self, records) {
// Filling Array of messages
var arr = [];
for(m in records[0].raw._embedded.messages){
var message = {
message: records[0].raw._embedded.messages[m].message,
href:records[0].raw._embedded.messages[m]._links.self.href
};
arr.push(message);
}
view.setData(arr[0]);
}
}
});

}
});

Ext.Loader.setConfig({ disableCaching: false });
[/code]

10. HTML View

It’s just the HTML page where Sencha’s library (Sencha’s CDN) has been loaded and the Sencha’s MessageApplication.js (Application Object) has been referenced.

index.html

[code lang=”xml”]
<html>
<head>
<title>JavaBeat Tutorial</title>
<script src="//cdn.sencha.io/touch/sencha-touch-2.1.1/sencha-touch-all.js"></script>
<script src="MessageApplication.js"></script>
</head>
<body>
<h2>JavaBeat Tutorial</h2>
<h3>Spring Data REST – <h3>
<h3>Consuming GemFire REST Resources Using Sencha Touch</h3>
</body>
</html>
[/code]

11. Maven Build

It’s the file that responsible of collecting the dependencies required for the current application.

[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-GemFire-REST-SenchaTouch</artifactId>
<version>1.0</version>
<packaging>war</packaging>

<name>Spring Data</name>

<dependencies>
<!– Spring Data GemFire Library –>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-gemfire</artifactId>
<version>1.3.4.RELEASE</version>
</dependency>
<!– GemFire Platform –>
<dependency>
<groupId>com.gemstone.gemfire</groupId>
<artifactId>gemfire</artifactId>
<version>7.0.1</version>
</dependency>
<!– Spring Data REST MVC –>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
<!– Google List API –>
<dependency>
<groupId>com.google.collections</groupId>
<artifactId>google-collections</artifactId>
<version>1.0</version>
</dependency>
<!– Required Libraries –>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
<version>1.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency>
</dependencies>

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

<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>gemstone</id>
<url>http://dist.gemstone.com.s3.amazonaws.com/maven/release/</url>
</repository>
</repositories>

<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
[/code]

12. Spring Data REST + Sencha Touch Demo

The demonstration being seen here, shows you the exporting of gemfire repository by using the Spring REST. The message content has been shown while the href of the message has been linked under Message Link link.
Sencha Touch - Consuming GemFire Repository Through of Spring REST Demo

13. Summary

This tutorial I have explained, clarify you how to access the Spring Data REST services and  GemFire in-memory repository through the Sencha Touch components. If you have any questions, please write it in the comments section.

Download Source Code

[wpdm_file id=112]

Filed Under: Spring Framework Tagged With: GemFire, Sencha Touch, Spring Data REST

Spring Data REST + GemFire + Rest.js Integration

June 3, 2014 by Amr Mohammed Leave a Comment

In our previous tutorials I have explained about Spring Data REST + GemFire + jQuery Integration and backbone.js integration. REST (Representational State Transfer) is one of the most effective ways Spring Data REST provides for consuming services. Client can be client side frameworks like AngularJS, jQuery, Backbone and Rest libraries. In this tutorial, you’re going to see the how to use Rest.js framework for accessing the GemFire REST services.

1. Project Structure

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

2. Tools Used

  • JDK 1.6.
  • Apache Tomcat 7.
  • GemFire 7.0.1 Platform (JAR distribution)
  • Maven 3.
  • Rest.js
  • Eclipse IDE
  • Spring Data
  • Spring Framework

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 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 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:

  • Download the SoapUI for consuming a REST service.
  • 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-Rest.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 - GemFire - Exporting Resources

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-Rest.js-1.0\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), and an loader such as curl.js.

Spring Data REST - GemFire - Rest.js Integration - Bower Init - Command Execution

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

Spring Data REST - GemFire - Rest.js Integration - Bower Init - Command Result

From the command line type:

  • bower install –save rest#~1
  • bower install –save curl#~0.8

Bower will install these packages into directory.

Spring Data REST - GemFire - Rest.js Integration - Bower Install Packages - Command Execution

Where, the structure of the project looks like

Spring Data REST - GemFire - Rest.js Integration - Bower Install Packages - Command Result

And the bower.json file should look like

bower.json

[code lang="xml"]
{
  "name": "SpringData-GemFire-REST-Rest.js",
  "version": "0.0.1",
  "description": "Spring Data REST - GemFire - Rest.js Integration",
  "main": "applicationModule",
  "authors": [
    "JavaBeat"
  ],
  "license": "MIT",
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components",
    "test",
    "tests"
  ],
  "dependencies": {
    "rest": "~1",
    "curl": "~0.8"
  }
}
[/code]

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

10. Rest.js Render Module

First, create a render function to inject data into an HTML document.

render.js

[code lang="java"]
define(function (require) {

    var ready = require('curl/domReady');

    return render;

    function render (entity) {
        ready(function () {
            var idElement, nameElement;
            placeHolder = document.querySelector('[data-name="placeHolder"]');
			var messages = entity._embedded.messages;
			for(var i = 0 ; i < messages.length;i++){
				var index = i + 1;
				placeHolder.innerHTML += "Message # "+index+" :: " + messages[i].message + " :: <a href='"+messages[i]._links.self.href+"'>Message Link</a><br>";
			}
        });
    }
});
[/code]

This AMD module uses simple DOM querying and manipulation to inject text into the document. To ensure that the DOM is not used before it is ready, the render module imports and uses curl.js’s domReady function-module.

11. Develop Rest.js Composition Application Module

Next, create a module that will compose the application. Note that the composition application module has been named as the bower init main file called.

applicationModule.js

[code lang="java"]
define(function (require) {
    var rest = require('rest');
    var mime = require('rest/interceptor/mime');
    var entity = require('rest/interceptor/entity');
    var render = require('./render');
    var endpointUrl, client;
    endpointUrl = 'http://localhost:8080/SpringData-GemFire-REST-Rest.js-1.0/rest/messages';
    client = rest.chain(mime, { mime: 'application/json' }).chain(entity);
    client({ path: endpointUrl}).then(render);
});
[/code]

The main module reads the query string from the document’s location object, configures a rest.js mime client, and calls the REST endpoint.

rest.js returns a Promises/A+ promise, which will call the render function-module when the endpoint returns data. The render function expects the entity, but the rest.js client normally returns a response object. The “rest/interceptor/entity” interceptor plucks the entity from the response and forwards that onto the render function.

12. Rest.js Boot Script

Next, create the boot script, boot.js:

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

    curl.config({
        main: 'applicationModule',
        packages: {
            // Third-party packages
            curl: { location: 'bower_components/curl/src/curl' },
            rest: { location: 'bower_components/rest', main: 'rest' },
            when: { location: 'bower_components/when', main: 'when' }
        }
    });

}());
[/code]

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.

13. Example Application (index.html)

Finally, create an index.html file and add the following HTML:

index.html

[code lang="xml"]
<!doctype html>
<html>
    <head>
		<title>JavaBeat Tutorials</title>
        <script data-curl-run="boot.js" src="bower_components/curl/src/curl.js"></script>
    </head>
    <body>
        <div>
			<h2>JavaBeat Tutorial !</h2>
			<h3>Spring Data REST - GemFire - Rest.js Demo</h3>
            <p data-name="placeHolder">

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

The script element loads curl.js and then loads an application boot script named boot.js. The boot script initializes and configures an AMD module environment and then starts the client-side application code.

14. Spring Data REST & Rest.js Demo

By invoking the index.html through typing the http://localhost:8080/SpringData-GemFire-REST-Rest.js-1.0/index.html into address section within the browser, you will be getting the below result.

Spring Data REST - GemFire - Rest.js Integration - Demo

15. Summary

You’ve just developed an application that exposes a Spring Data Rest + GemFire repository to be accessed through the HTTP and a Rest.js JavaScript framework. If you have any questions, please write it in the comments section.

Download Source Code

[wpdm_file id=110]

Filed Under: Spring Framework Tagged With: GemFire, Rest.js, Spring Data REST

Spring Data REST + GemFire + AngularJS Integration

May 29, 2014 by Amr Mohammed Leave a Comment

This tutorial explains the integration between Spring Data REST, GemFire and AngularJS frameworks. We are going to develop a REST service which returns the JSON response and that will be accessed by the AngularJS web page.

1. Tools Required

We’ve developed this tutorial by using the following tools:

  • JDK 1.6.
  • Tomcat 7.
  • Maven 3.
  • GemFire 7.0.1.
  • AngularJS

2. Project Structure

Here is the project structure used for this tutorial.

Spring REST - GemFire - Eclipse Project Directory

3. Business Domain

Message is the persistence object used for storing the data in GemFire’s in-memory storage. We are using only this entity for this tutorial. If you look at the below code, the entity imports the org.springframework.data.gemfire.mapping.Region which is equivalent to the table in the relational database. This Region class used as the segment in in-memory and allocate the storage for the data.

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

It’s the repositories that enable the CRUD operations against the business domain. In our previous tutorial I have explained the Spring Data and how the repositories used for the CRUD operations.

MessageReposirory.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]

5. Spring Bean

It’s a normal spring bean that used for filling a dummy data inside the GemFire platform.

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 Configurations

It’s the Spring XML configuration file, in which the spring beans, repositories and GemFire cache are defined.

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. Maven Build

It’s the pom file that containing the needed libraries.

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-GemFire-REST</artifactId>
<version>1.0</version>
<packaging>war</packaging>

<name>Spring Data</name>

<dependencies>
<!– Spring Data GemFire Library –>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-gemfire</artifactId>
<version>1.3.4.RELEASE</version>
</dependency>
<!– GemFire Platform –>
<dependency>
<groupId>com.gemstone.gemfire</groupId>
<artifactId>gemfire</artifactId>
<version>7.0.1</version>
</dependency>
<!– Spring Data REST MVC –>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
<!– Google List API –>
<dependency>
<groupId>com.google.collections</groupId>
<artifactId>google-collections</artifactId>
<version>1.0</version>
</dependency>
<!– Required Libraries –>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
<version>1.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency>

</dependencies>

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

<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>gemstone</id>
<url>http://dist.gemstone.com.s3.amazonaws.com/maven/release/</url>
</repository>
</repositories>

<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
[/code]

8. Web Deployment Descriptor

It’s the web descriptor that used for application configuration against the JavaEE container. One important thing you need to care about it is the servlet of the Spring MVC REST that handle the requests that asked for GemFire repositories.

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]

RepositoryRestDispatcherServlet is a spring mvc resource that works in conjunction with the Spring Data REST for exposing the REST resources. In the above section you have seen how to expose REST resources using the Spring Boot, in that you’ve used @import to import the RepositoryRestMvcConfiguration. If you’re going to use the Spring old fashion configuration XML file for exposing the Spring Data REST, you should use the RepositoryRestDispatcherServlet with its mapping as you’ve noted above for exporting the resources.

9. Expose GemFire Repositories Directly

This section explains how to access the REST services using the Google Dev HTTP. 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 URL http://localhost:8080/SpringData-GemFire-REST-1.0.
  • For consuming the message 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-AngularJS-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 exposing the messages resource like below.

Spring Data REST AngularJS Demo

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

10. Accessing GemFire REST Using AngularJS

AngularJS is a JavaScript Framework for building the web application most suited to mobile devices and responsi. It is fully extensible and works well with other libraries. For including the AngularJS library into your page, a JavaScript library url https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js should be added inside a script tag. This is Content Deliver Network (CDN) approach for using the AngularJS without downloading the libraries. This can be most suitable only for the development application, for the production you have to download the libraries.

In the below example, the AngualrJS library is imported into the header of the page for being used in the REST resources consumption.

index.html

[code lang=”xml”]
<html ng-app>
<head>
<title>JavaBeat Tutorial</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="messages.js"></script>
</head>
<body>
<div style="width:50%">
<h2>JavaBeat Tutorial</h2>
<h2>GemFire + REST + AngularJS</h2>
<div ng-controller="fetch">
<h2>full json response:</h2>
<p>{{messages}}</p>
<h2>Messages:</h2>
<ul ng-repeat="message in messages">
<p>Message:</p>
<p>{{message.message}}</p>
<a href='{{message["_links"]["self"]["href"]}}’>Go To Page Addressed Message : {{message._links.self.href}}</a>
</ul>
</div>
</div>
</body>
</html>
[/code]

messages.js

[code lang=”java”]
function fetch($scope, $http) {
$http.get(‘http://localhost:8080//SpringData-GemFire-REST-1.0/rest/messages’).
success(function(data) {
$scope.messages = data["_embedded"]["messages"];
});
}
[/code]

11. Spring Data REST – GemFire – AngularJS Demo

Spring REST GemFire AngularJS Demo

11.Summary

GemFire is a platform for the in-memory persistent store, it’s mainly used for caching. This tutorial generated a war file has been deployed against Tomcat 7 and the GemFire repositories are accessed and their data is retrieved through an HTTP REST using the AngularJS.

AngularJS is a famous JavaScript framework that has the capability of reading, parsing and converting the parsed JSON response into object-based form. Parsed objects gets navigated using the dot operator as the example get involved. AngularJS can be integrated with the Spring Data REST. In this tutorial, you’ve developed a Spring Data REST application that get connected with the GemFire platform and the AngularJS is used in the presentation for displaying the messages that fetched.

Download Source Code

[wpdm_file id=106]

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

Caching Data using Spring Data GemFire

May 24, 2014 by Amr Mohammed Leave a Comment

In my previous tutorial, I have explained about the accessing data using Spring Data GemFire. GemFire is the in-memory data system used in the distributed environments. The performance and scalability achieved by GemFire by using the efficient caching techniques for storing in the in-memory. In this tutorial I will explain the purpose, in that connections will be made for http://themoneyconverter.com/ for transferring RSS Feed for different counties. After that the elapsed time should be computed by subtract of the end time from the start time.

Also read:

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

1. Business Scenario

To ensure that the Spring GemFire framework does provide a proper solution for the Cache, we created a MoneyRSS spring bean that contains a loadRss service that accept a country as an enum value. After that an HTTP connection got opened for reading the rss for the provided country. The implementation of the whole bean is provided below:

MoneyRSS.java

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

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

@Component
public class MoneyRSS {
@Cacheable("moneyRss")
public Object loadRss(Country country){
try {
URL url = new URL("http://themoneyconverter.com/rss-feed/"+country.code+"/rss.xml");
try {
return url.openConnection().getContent();
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return null;
}

public static enum Country {
INDIA("INDIA","INR"), UK("United Kingdom","GBP"), USA("United States","USD");

Country(String name, String code){
this.code = code;
}

private String code;
private String name;

public String getCode() {
return code;
}

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

public String getName() {
return name;
}

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

}
}
[/code]

2. Spring Bean Configurations

It’s the spring container configuration file that used for defining spring beans, repositories if there is one, GemFire cache, Regions, cache managers and etc.

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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="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="moneyRss"/>
<!– It’s mandatory for enabling the Cache –>
<bean id="cacheManager" class="org.springframework.data.gemfire.support.GemfireCacheManager" p:cache-ref="gemfireCache"/>
<!– Dummy Bean for EnableCaching –>
<bean id="enableCachingBean" class="net.javabeat.springdata.executable.Executable"></bean>
</beans>
[/code]

3. Maven Build File

It’s the maven build file that contains the required libraries for getting the example up and running.

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-GemFire-Cache</artifactId>
<version>1.0</version>
<packaging>jar</packaging>

<name>Spring Data</name>
<!– Just for including the Spring framework necessary libraries inone shot –>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.0.2.RELEASE</version>
</parent>

<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-gemfire</artifactId>
<version>1.3.4.RELEASE</version>
</dependency>

<dependency>
<groupId>com.gemstone.gemfire</groupId>
<artifactId>gemfire</artifactId>
<version>7.0.1</version>
</dependency>
<!– Google List API –>
<dependency>
<groupId>com.google.collections</groupId>
<artifactId>google-collections</artifactId>
<version>1.0</version>
</dependency>

</dependencies>

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

<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>gemstone</id>
<url>http://dist.gemstone.com.s3.amazonaws.com/maven/release/</url>
</repository>
</repositories>

<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>

</project>
[/code]

4. Spring Data GemFire Example Application

It’s the Spring Data GemFire Sample Application that will be used for starting up the Spring framework and for initiating an rss HTTP request through using of GemFireBean.

Executable.java

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

import net.javabeat.springdata.bean.GemFireBean;
import net.javabeat.springdata.data.MoneyRSS;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

@EnableCaching
public class Executable {
// Getting spring context
public static ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new ClassPathResource(&quot;SpringContext.xml&quot;).getPath());

// GemFireBean declaration, it’s just a normal spring bean
public static GemFireBean gfb;

public static void main(String[] args) {
// Acquiring the GemFireBean
gfb = (GemFireBean)context.getBean(&quot;gemFireBean&quot;);
loadAndTimeIt(1,gfb,MoneyRSS.Country.INDIA);
loadAndTimeIt(2,gfb,MoneyRSS.Country.INDIA);
loadAndTimeIt(3,gfb,MoneyRSS.Country.INDIA);
loadAndTimeIt(1,gfb,MoneyRSS.Country.USA);
loadAndTimeIt(2,gfb,MoneyRSS.Country.USA);
loadAndTimeIt(3,gfb,MoneyRSS.Country.USA);
loadAndTimeIt(1,gfb,MoneyRSS.Country.UK);
loadAndTimeIt(2,gfb,MoneyRSS.Country.UK);
loadAndTimeIt(3,gfb,MoneyRSS.Country.UK);
}

private static void loadAndTimeIt(int tryIndex,GemFireBean bean,MoneyRSS.Country country){
// Start Time
long start = System.currentTimeMillis();
// Load document
Object o = gfb.getMoneyRss().loadRss(country);
// End Time Computation
long elapsed = System.currentTimeMillis() – start;
// Print out the time message
System.out.println("Try # :: "+tryIndex+" :: For :: "+country+" :: Found " + o + ", and it only took " + elapsed + " ms to find out!\n");
}
}
[/code]

5. GemFire Cache Demo

It’s the demonstration of using GemFire for caching the request. This output shows the how much time taken for each request. If you look at it closely, for the first look up of the data, it took longer time, but later requests it is much faster. It shows that if you have a performance issues for fetching the data, GemFire could be good option to try out.

[code lang=”xml”]

[info 2014/05/24 01:00:24.765 EEST &lt;main&gt; tid=0x1] Defaulting license-working-dir to current working directory &quot;D:\Krishna\EclipseLink\Workspace\SpringData-GemFire-Cache&quot;.

[info 2014/05/24 01:00:24.775 EEST &lt;main&gt; tid=0x1] Acquiring default evaluation license.

[info 2014/05/24 01:00:26.554 EEST &lt;main&gt; tid=0x1] vFabric Licensing Client activation of license required 1778 milliseconds.

[info 2014/05/24 01:00:26.618 EEST &lt;main&gt; tid=0x1] Using the default evaluation license.

[info 2014/05/24 01:00:26.619 EEST &lt;main&gt; tid=0x1] Licensing required 1856 milliseconds.

[info 2014/05/24 01:00:26.758 EEST &lt;main&gt; tid=0x1] GemFire P2P Listener started on tcp:///192.168.1.100:59267

[info 2014/05/24 01:00:30.966 EEST &lt;main&gt; tid=0x1] Membership: lead member is now mohammad-amr-lt:49779

[config 2014/05/24 01:00:30.974 EEST &lt;main&gt; tid=0x1] This member, mohammad-amr-lt:49779, is becoming group coordinator.

[info 2014/05/24 01:00:31.011 EEST &lt;main&gt; tid=0x1] Entered into membership in group GF70 with ID mohammad-amr-lt:49779.

[info 2014/05/24 01:00:31.013 EEST &lt;main&gt; tid=0x1] Starting DistributionManager mohammad-amr-lt:49779.

[info 2014/05/24 01:00:31.014 EEST &lt;main&gt; tid=0x1] Initial (membershipManager) view = [mohammad-amr-lt:49779{lead}]

[info 2014/05/24 01:00:31.015 EEST &lt;main&gt; tid=0x1] Admitting member &lt;mohammad-amr-lt:49779&gt;. Now there are 1 non-admin member(s).

[info 2014/05/24 01:00:31.015 EEST &lt;main&gt; tid=0x1] mohammad-amr-lt:49779 is the elder and the only member.

[info 2014/05/24 01:00:31.130 EEST &lt;main&gt; tid=0x1] Did not hear back from any other system. I am the first one.

[info 2014/05/24 01:00:31.130 EEST &lt;main&gt; tid=0x1] DistributionManager mohammad-amr-lt:49779 started on 239.192.81.1[10334]. There were 0 other DMs. others: []

[info 2014/05/24 01:00:31.153 EEST &lt;Thread-3 StatSampler&gt; tid=0x21] Disabling statistic archival.

[info 2014/05/24 01:00:31.394 EEST &lt;main&gt; tid=0x1] Initializing region _monitoringRegion_mohammad-amr-lt49779

[config 2014/05/24 01:00:31.422 EEST &lt;main&gt; tid=0x1] Command Service could not be initialized. Could not find Spring Shell library which is needed for CLI/gfsh in classpath. Internal support for CLI &amp; gfsh is not enabled.

[info 2014/05/24 01:00:31.477 EEST &lt;main&gt; tid=0x1] Initializing region PdxTypes
Try # :: 1 :: For :: INDIA :: Found sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@629a99eb, and it only took 741 ms to find out!

Try # :: 2 :: For :: INDIA :: Found sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@629a99eb, and it only took 3 ms to find out!

Try # :: 3 :: For :: INDIA :: Found sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@629a99eb, and it only took 0 ms to find out!

Try # :: 1 :: For :: USA :: Found sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@2af4ca49, and it only took 685 ms to find out!

Try # :: 2 :: For :: USA :: Found sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@2af4ca49, and it only took 1 ms to find out!

Try # :: 3 :: For :: USA :: Found sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@2af4ca49, and it only took 0 ms to find out!

Try # :: 1 :: For :: UK :: Found sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@64ad97f5, and it only took 599 ms to find out!

Try # :: 2 :: For :: UK :: Found sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@64ad97f5, and it only took 1 ms to find out!

Try # :: 3 :: For :: UK :: Found sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@64ad97f5, and it only took 0 ms to find out!

[info 2014/05/24 01:00:33.729 EEST &lt;Distributed system shutdown hook&gt; tid=0xa] VM is exiting – shutting down distributed system
[/code]

6. Summary

You’ve just developed an application that uses the GemFire cache feature. The example provided here makes multiple requests for getting the RSS money feeds for different countries, where the first request for every single country took long time in comparison of those second and third.

Download Source Code

[wpdm_file id=103]

Filed Under: Spring Framework Tagged With: GemFire, Spring Catch, Spring Data Gemfire

Accessing Data with Spring Data GemFire

May 23, 2014 by Amr Mohammed Leave a Comment

VFabric GemFire (GemFire) is a commercially licensed data management platform that provides access to data from the distributed architectures. It is available as a standalone product and as a component of VMware vFabric Suite.

Based on the Nutshell, GemFire provides an in-memory data grid that offers extremely high throughput, low latency data access, and scalability. Beyond a distributed cache, GemFire provides advanced features including:

  • Event notification
  • OQL (Object Query Language) query syntax
  • Continuous queries
  • Transaction support
  • Remote function execution
  • WAN communications
  • Efficient and portable object serialization (PDX)
  • Tools to aid system administrators in managing and configuring the GemFire distributed
    system

This tutorial intended to provide the readers the basic idea of using GemFire for accessing the Data by reading entities from writing into memory. Before any further explanation, it’s important to know a concept that’s used when it comes to discuss the GemFire, it is Regions.

Also read:

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

By following this tutorial, feel free to write your comments if you had have any question or help. Also I have attached source code download at the end of this tutorial.

1. Region

A region is required to store and retrieve data from the cache. Region is an interface that extends java.util.Map to perform basic data access using familiar key/value semantics. The Region interface is wired into classes that require it, so the actual region type is decoupled from the programming model. Typically, each region is associated with one domain object, similar to a table in a relational database. Looking at the sample Message, you’ll see a defined @Region.

It’s very important for you to know that GemFire doesn’t manage the associations or enforce relational integrity among regions.

2. Java Beans (Business Domain)

As mentioned earlier, GemFire will operate against data that will be saved, retrieved and deleted from the memory. These data is identical to what already have been defined in the Spring Data/JPA as an example.

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]

3. GemFire Repository

It’s the same concept of the spring data repository that discussed in the previous tutorials, but this time the repository is defined using the GemFire library.

MessageReposirory.java

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

import net.javabeat.springdata.data.Message;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface MessageRepository extends CrudRepository<Message,Integer>{

}
[/code]

4. Spring Bean Definition

It’s the Spring bean definition, that will be used for configuring the Spring context. Where in the beans, repositories, properties and several other configurable objects get defined. Here, we’re using that XML document for defining and locating the GemFire repositories. Lets look at the below configurations to know how the gemfire repository is configured in the spring configuration file.

SpringContxt.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"
xsi:schemaLocation="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]

5. Spring Data + GemFire Example Application

It’s the executable Java application that contains a main implementation that does communicate directly into GemFire engine.

Executable.java

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

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

import net.javabeat.springdata.bean.GemFireBean;
import net.javabeat.springdata.data.Message;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

import com.google.common.collect.Lists;

public class Executable {
// Getting spring context
public static ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new ClassPathResource("SpringContext.xml").getPath());

// GemFireBean declaration, it’s just a normal spring bean that contains a reference for MessageRepository
public static GemFireBean gfb;

public static void main(String[] args) {
// Acquiring the GemFireBean
gfb = (GemFireBean)context.getBean("gemFireBean");
System.out.println("Before Linking GemFire … Initialized Message Objects");
Message mess1 = new Message("1","Hello JavaBeat !");
Message mess2 = new Message("2","Hello Spring Data !");
Message mess3 = new Message("3","Hello Spring Data – GemFire !");
Message mess4 = new Message("4","Just Hello !");
List<Message> messages = new ArrayList<Message>();
messages.add(mess1);
messages.add(mess2);
messages.add(mess3);
messages.add(mess4);
System.out.println("Print out all Created Messages");
for(Message m : messages){
System.out.println("Created Message ID :: "+m.getMessageId()+" :: With Content :: "+m.getMessage());
}
System.out.println("Linking GemFire for Persisting Messages …");
gfb.getMessageRepository().save(messages);
System.out.println("Persisting Process finsihed succesfully …");
// Reset the messages list
messages = null;
System.out.println("Linking GemFire for Retrieving Messages …");
messages = Lists.newArrayList(gfb.getMessageRepository().findAll());
for(Message m : messages){
System.out.println("Retrieved Message ID :: "+m.getMessageId()+" :: With Content :: "+m.getMessage());
}

System.out.println("End ::");
}
}
[/code]

6. GemFire Maven Dependencies

Using of GemFire can be done either by using GemFire vFabric product that can be installed from the link mentioned above or by adding the GemFire dependency into your pom.xml. Once, you’ve added the GemFire dependency and defined the cacheFactoryBean and LocalRegionFactoryBean, the GemFire is ready for use.

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-GemFire</artifactId>
<version>1.0</version>
<packaging>jar</packaging>

<name>Spring Data</name>
<!– Just for including the Spring framework necessary libraries in one shot –>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.0.2.RELEASE</version>
</parent>

<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-gemfire</artifactId>
<version>1.3.4.RELEASE</version>
</dependency>

<dependency>
<groupId>com.gemstone.gemfire</groupId>
<artifactId>gemfire</artifactId>
<version>7.0.1</version>
</dependency>
<!– Google List API –>
<dependency>
<groupId>com.google.collections</groupId>
<artifactId>google-collections</artifactId>
<version>1.0</version>
</dependency>

</dependencies>

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

<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>gemstone</id>
<url>http://dist.gemstone.com.s3.amazonaws.com/maven/release/</url>
</repository>
</repositories>

<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>

</project>
[/code]

7. Accessing Data By GemFire Demo

By executing the main application, you’ve got a vast amount of GemFire output in the console. Your application messages are shown below:

[code lang=”xml”]
[info 2014/05/23 12:27:29.268 EEST <main> tid=0x1] Initializing region PdxTypes
12:27:29.279 [main] INFO o.s.d.g.CacheFactoryBean – Connected to Distributed System [] as Member [mohammad-amr-lt:4894] on Host [mohammad-amr-lt].
12:27:29.279 [main] INFO o.s.d.g.CacheFactoryBean – Created new GemFire v.7.0.1 Cache [].
12:27:29.331 [main] INFO n.j.s.e.Executable$1 – Created new cache region [messages]
12:27:29.440 [main] INFO o.s.c.s.DefaultLifecycleProcessor – Starting beans in phase 2147483647
Before Linking GemFire … Initialized Message Objects
Print out all Created Messages
Created Message ID :: 1 :: With Content :: Hello JavaBeat !
Created Message ID :: 2 :: With Content :: Hello Spring Data !
Created Message ID :: 3 :: With Content :: Hello Spring Data – GemFire !
Created Message ID :: 4 :: With Content :: Just Hello !
Linking GemFire for Persisting Messages …
Persisting Process finsihed succesfully …
Linking GemFire for Retrieving Messages …
Retrieved Message ID :: 4 :: With Content :: Just Hello !
Retrieved Message ID :: 2 :: With Content :: Hello Spring Data !
Retrieved Message ID :: 3 :: With Content :: Hello Spring Data – GemFire !
Retrieved Message ID :: 1 :: With Content :: Hello JavaBeat !
End ::
12:27:29.557 [main] INFO n.j.s.e.Executable – Started Executable in 7.911 seconds (JVM running for 8.36)
[/code]

8. Summary

GemFire is a Spring framework that used for manipulating the data in the memory. It’s used as cache framework as you’ll be seeing in the next tutorials. In this tutorial, you’ve learnt the basic use of GemFrie by persisting a messages object inside a defined region called messages. The persisted messages, got read from printing process on the JVM console.

Download Source Code

[wpdm_file id=102]

Filed Under: Spring Framework Tagged With: GemFire, Spring Data, Spring Data Gemfire

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