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

Read Only / Write Only Operations using Spring Data Repository Services

June 16, 2014 by Amr Mohammed Leave a Comment

As we’ve learned about Spring Data Repository in our previous tutorials, it’s an abstraction layer that built in top of persistent store that leverage the ability of accessing that store for achieving CRUD operations.

Spring Data Repository had integrated seamlessly with all of the aspects that might be concerned by a developer, one of those aspect is the security. Security is the one of the main reason for why specific technology gets more importance, while others didn’t. Repository provides an open gate for accessing the persistent store with full capacity for any one has the ability of gaining its reference; either those developers have developed sub classes for it or any one has the ability of consuming that repository through whatever technique they want even using the RESTful principle.

also read:

  • Spring Data JPA
  • Spring Data MongoDB
  • Spring Data Neo4j

However, there could be scenarios in which you would like to expose or restrict only the reading methods (The R in CRUD) or simply prevent the delete methods from being exposed in your repository interface that can be accessed by every one. Spring Data now allows you to custom base repository with the following steps:

  • Create an interface either extending Repository or annotated with @Repository Definition.
  • Add all of the methods that you want to expose it, and make sure they actually match the signatures of methods provided by the Spring Data base repository interfaces.
  • Use this interface as a base interface for the interface declarations for your entities.

To illustrate this, let’s assume we’d like to expose only the findAll() method while preventing all writable methods. End of this tutorial, you can download the source code used in this example.

1. Spring Data Read Only / Write Only

MySQL database contained two tables, Address and Employee along with a Spring Data Repository for handling the all operations that you may need.

The repositories being used in two ways, ReadOnly and WriteOnly. ReadOnly repositories will provide us the ability to read the data that located in the database, while the write will be used for writing operation.

The JSF managed bean will use a Spring service for locating both of these repositories for handling the required operations, meanwhile, those repositories are also exported as a RESTful services.

You’ll see the ReadOnly REST repository for persisting a record inside the database and at the other hand, you’ll try to retrieve all the records of the database through using  WriteOnly REST repository.

2. Defining Read/Write Base Repositories

Along with the mentioned steps for creating the required repositories, we’ve developed two repositories, one for read only and second for just write operation.

BaseReadOnlyRepository.java

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

import java.io.Serializable;

import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;

@NoRepositoryBean

public interface BaseReadOnlyRepository<T, ID extends Serializable> extends Repository<T,ID>{
Iterable<T> findAll();
}

[/code]

BaseWriteOnlyRepository.java

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

import java.io.Serializable;

import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;

@NoRepositoryBean

public interface BaseWriteOnlyRepository<T, ID extends Serializable> extends Repository<T,ID>{
<S extends T> S save(S entity);
}

[/code]

3. Read Only Repository Example

In this section, we’re going to develop an Employee and Address read only repository that extends the read only base repository defined above. We would see what’s the impact of using Read-Only repositories for achieving the operations of write.

EmployeeReadOnlyRepository.java

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

import net.javabeat.springdata.jpa.data.Employee;

import org.springframework.data.rest.core.annotation.RestResource;

@RestResource(rel="employeesReadOnly",path="employeeReadOnlyRepository")
public interface EmployeeReadOnlyRepository extends BaseReadOnlyRepository<Employee,Integer>{

}

[/code]

AddressReadOnlyRepository.java

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

import net.javabeat.springdata.jpa.data.Address;

import org.springframework.data.rest.core.annotation.RestResource;

@RestResource(rel="addressesReadOnly",path="addressReadOnlyRepository")
public interface AddressReadOnlyRepository extends BaseReadOnlyRepository<Address,Integer>{

}

[/code]

RegistraionService.java

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

import net.javabeat.springdata.repo.EmployeeReadOnlyRepository;

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

@Component
public class RegistrationService {

@Autowired
private EmployeeReadOnlyRepository readOnlyRepository;

public EmployeeReadOnlyRepository getReadOnlyRepository() {
return readOnlyRepository;
}

public void setReadOnlyRepository(EmployeeReadOnlyRepository readOnlyRepository) {
this.readOnlyRepository = readOnlyRepository;
}

}

[/code]

RegistraionManagedBean.java

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

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

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

import net.javabeat.springdata.beans.RegistrationService;
import net.javabeat.springdata.jpa.data.Employee;

import com.google.common.collect.Lists;

@ManagedBean
@SessionScoped
public class RegistrationManagedBean {

private Employee employee = new Employee();

private List<Employee> employees = new ArrayList<Employee>();

@ManagedProperty(value="#{registrationService}")
private RegistrationService service;

public Employee getEmployee() {
return employee;
}

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

public List<Employee> getEmployees() {
this.employees = Lists.newArrayList(this.service.getReadOnlyRepository().findAll());
return employees;
}

public void setEmployees(List<Employee> employees) {
this.employees = employees;
}

public RegistrationService getService() {
return service;
}

public void setService(RegistrationService service) {
this.service = service;
}

}

[/code]

index.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<f:view>
<h:form prependId="false">
<h2>JavaBeat Tutorials</h2>
<h2>Spring Data + Exposing/Hiding Repository Services</h2>
<h:panelGrid columns="2">
<h:outputText value="Enter Employee Name:"/>
<p:inputText value="#{registrationManagedBean.employee.employeeName}"></p:inputText>
<h:outputText value="Enter Employee Address Country:"/>
<p:inputText value="#{registrationManagedBean.employee.address.addressCountry}"></p:inputText>
<h:outputText value="Enter Employee Address City:"/>
<p:inputText value="#{registrationManagedBean.employee.address.addressCity}"></p:inputText>
</h:panelGrid>
<p:separator/>
<h:panelGrid columns="1" width="50%">
<p:dataTable value="#{registrationManagedBean.employees}" var="employee">
<p:column headerText="Employee’s Name">
<h:outputText value="#{employee.employeeName}"/>
</p:column>
<p:column headerText="Employee’s Country">
<h:outputText value="#{employee.address.addressCountry}"/>
</p:column>
<p:column headerText="Employee’s City">
<h:outputText value="#{employee.address.addressCity}"/>
</p:column>
</p:dataTable>
</h:panelGrid>
</h:form>
</f:view>
</html>
[/code]

By defining all of the required classes as mentioned, your project structure should look like:

Project Is not compilable

As you’ve seen, the project isn’t compilable for one reason in that the EmployeeReadOnlyRepository no longer support service like save.

Save Is not defined

At the same time, no issues was reported for findAll() neither inside the Spring service nor through using of RESTful service as you’d see. Below two provided snapshots, one for using of RegistrationService, while the other for RESTful access.

ReadOnly - Employees Fetched Successfully

ReadOnly - Employees Fetched Successfully - REST

Also, for simplicity, we’ve tried to post a record of employee using the ReadOnly repository via REST-SHELL and we’ve got the following error:

Employee Insertion Using ReadOnly Repository

While by using the same operation against WriteOnly repository, we’ve got success message, and the employee has been created.

Employee Insertion Using WriteOnly Repository

And by looking into records in the database, we’ve ensured that the employee has really located there.

Real Employee Insertion

You may be asking about employeeId, which is vary from the one used in the post; the answer is the MySQL database has ignored the employeeId that passed and it’s used its sequence. Look below for another request without providing employeeId.

Create Employee Without Providing EmployeeId Real Employee Insertion - Without Using EmployeeId

By using Spring or RESTful ways, the employees are fetched successfully from the MySQL. In the first snapshot, a primefaces view has been used for displaying the employees and their respective addresses and in the second the all employees and their respective addresses got displayed using the RESTful invocation.

4. Write Only Repository Example

In this section, we’re going to develop an Employee and Address write only repository that extends the write only base repository defined above. We would see what’s the impact of using Write-Only repositories for achieving the operations of read using the RESTful service.

EmployeeWriteOnlyRepository.java

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

import net.javabeat.springdata.jpa.data.Employee;

import org.springframework.data.rest.core.annotation.RestResource;

@RestResource(rel="employeesWriteOnly",path="employeeWriteOnlyRepository")
public interface EmployeeWriteOnlyRepository extends BaseWriteOnlyRepository<Employee,Integer>{

}

[/code]

AddressWriteOnlyRepository.java

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

import net.javabeat.springdata.jpa.data.Address;

import org.springframework.data.rest.core.annotation.RestResource;

@RestResource(rel="addressesWriteOnly",path="addressWriteOnlyRepository")
public interface AddressWriteOnlyRepository extends BaseWriteOnlyRepository<Address,Integer>{

}

[/code]

RegistrationService.java

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

import net.javabeat.springdata.repo.EmployeeWriteOnlyRepository;

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

@Component
public class RegistrationService {

@Autowired
private EmployeeWriteOnlyRepository writeOnlyRepository;

public EmployeeWriteOnlyRepository getWriteOnlyRepository() {
return writeOnlyRepository;
}

public void setWriteOnlyRepository(
EmployeeWriteOnlyRepository writeOnlyRepository) {
this.writeOnlyRepository = writeOnlyRepository;
}

}

[/code]

RegistrationManagedBean.java

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

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

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

import net.javabeat.springdata.beans.RegistrationService;
import net.javabeat.springdata.jpa.data.Employee;

@ManagedBean
@SessionScoped
public class RegistrationManagedBean {

private Employee employee = new Employee();

private List<Employee> employees = new ArrayList<Employee>();

@ManagedProperty(value="#{registrationService}")
private RegistrationService service;

public Employee getEmployee() {
return employee;
}

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

public List<Employee> getEmployees() {
return employees;
}

public void setEmployees(List<Employee> employees) {
this.employees = employees;
}

public RegistrationService getService() {
return service;
}

public void setService(RegistrationService service) {
this.service = service;
}

public String register(){
this.service.getWriteOnlyRepository().save(this.employee);
return "";
}

}

[/code]

Likewise the impact of using the Read-Only repository, all of these services that are related to the Read will be eliminated and so the compiler will complaint about them.

Write Only - FindAll Causes Error

While the RESTful service won’t going far apart from the same result but using different words.

RESTful Read Employees Failed

Even if you’re using the REST-SHELL for reading an employees from WriteOnly Repository by executing the operation list which means findAll(), you will get the same result.

Read Employees By Using WriteOnly Repository - REST SHELL

5. Summary

Spring Data Repositories, have the ability of exposing/hiding the services provided by them. By making a base interface for just reading, all of those interfaces that extend it should serve as READ ONLY and if any part try to get read the data by READ ONLY repository it will get an error. The same issue when it comes for making interfaces for write.

This tutorial provides full explanation of how could you make your repositories for read only or for write. Also, it shows you the possible exceptions and errors that you may get when it comes to violate the rules of spring data repository.

Download Source Code

[wpdm_file id=114]

Filed Under: Spring Framework Tagged With: MySQL, Repositories, Spring Data

PrimeFaces 5 Features

June 10, 2014 by Amr Mohammed Leave a Comment

This tutorial highlights the new features added as part of the PrimeFaces 5 release. PrimeFaces 5 has been announced and shipped with set of new components. We’ve published set of tutorials that covered the PrimeFaces 4 earlier in our blog. To summarize, PrimeFaces 5 comes up with set of new components and lot of minor enhancements in the framework.  At the end of this tutorial, I have uploaded the source code for this tutorial. You can download that and try the PrimeFaces 5 features in your environment. PrimeFaces 5 is compatible to JSF 2.0, JSF 2.1 and JSF 2.2. If you have any questions, please write it in the comments section.

The following are the new components added as part of the new release.

  1. DataScroller
  2. Cache
  3. Spotlight
  4. ColumnToggler
  5. ContentFlow

If you are not familiar with the PrimeFaces framework or JSF, please read the list of articles suggested below to get basic idea of the frameworks.

  • Introduction to JSF
  • Setting Up JSF Web Application Using Maven

The prerequisite or knowledge for this tutorial,

  • Java Server Faces (JSF) concepts
  • PrimeFaces
  • EclipseLink / JPA (This requires to display the data from the database)

Lets look at the examples.

1. DataScroller

DataScroller displays a collection of data with on demand loading using scrolling.

1.1 DataScroller Basic Info

DataScroller - Basic Info

1.2 DataScroller Attributes

DataScroller - Attributes

  1. DataScroller requires a collection of data to display, when the page is scrolled down, datascroller will do a request with ajax to fetch the new chunk of data and append them at the bottom.
  2. Defaulted scroll mode is the document, thus, the scrolling against page is monitored by the DataScroller component and at every time you get reached into the bottom of the page, an ajax request has been initiated cause data fetching with the same amount that you’ve specified in the chunkSize.
  3. The other applicable value for the mode attribute is inline which cause scrolling event be applied against the DataScroller itself.

1.3 DataScroller Demo

Here is the implementation for the DataScroller component. Lets look at the details of the implementation. Here I have listed the primefaces view and JSF managed bean.

index.xhtml

[code lang=”xml”]
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;
xmlns:ui=&quot;http://java.sun.com/jsf/facelets&quot;
xmlns:h=&quot;http://java.sun.com/jsf/html&quot;
xmlns:f=&quot;http://java.sun.com/jsf/core&quot;
xmlns:p=&quot;http://primefaces.org/ui&quot;&gt;
&lt;h:head&gt;
&lt;script name=&quot;jquery/jquery.js&quot; library=&quot;primefaces&quot;&gt;&lt;/script&gt;
&lt;/h:head&gt;
&lt;f:view&gt;
&lt;h:form prependId=&quot;false&quot;&gt;
&lt;h2&gt;JavaBeat Tutorials&lt;/h2&gt;
&lt;h2&gt;Primefaces 5 New Components !&lt;/h2&gt;
&lt;div style=&quot;width: 700px;border: 1px;border-style: dotted;&quot;&gt;
&lt;h:panelGrid columns=&quot;2&quot;&gt;
&lt;h:outputText value=&quot;Enter Employee Name:&quot;/&gt;
&lt;p:inputText value=&quot;#{registrationManagedBean.employee.employeeName}&quot;&gt;&lt;/p:inputText&gt;
&lt;h:outputText value=&quot;Enter Employee Address Country:&quot;/&gt;
&lt;p:inputText value=&quot;#{registrationManagedBean.employee.address.addressCountry}&quot;&gt;&lt;/p:inputText&gt;
&lt;h:outputText value=&quot;Enter Employee Address City:&quot;/&gt;
&lt;p:inputText value=&quot;#{registrationManagedBean.employee.address.addressCity}&quot;&gt;&lt;/p:inputText&gt;
&lt;/h:panelGrid&gt;
&lt;p:commandButton value=&quot;Register&quot; action=&quot;#{registrationManagedBean.register}&quot; ajax=&quot;false&quot;/&gt;
&lt;p:separator/&gt;
&lt;p:dataScroller value=&quot;#{registrationManagedBean.employees}&quot; var=&quot;employee&quot; chunkSize=&quot;10&quot; mode=&quot;inline&quot; scrollHeight=&quot;80&quot;&gt;
&lt;f:facet name=&quot;header&quot;&gt;
Employees
&lt;/f:facet&gt;
&lt;f:facet name=&quot;loader&quot;&gt;
&lt;p:commandButton value=&quot;Scroll Down to Load More Employees&quot; type=&quot;button&quot;&gt;&lt;/p:commandButton&gt;
&lt;/f:facet&gt;
&lt;h:panelGrid columns=&quot;2&quot; style=&quot;width:100%&quot; columnClasses=&quot;logo,detail&quot;&gt;
&lt;p:outputPanel&gt;
&lt;h:panelGrid columns=&quot;2&quot; cellpadding=&quot;5&quot;&gt;
&lt;h:outputText value=&quot;#{employee.employeeName}&quot; style=&quot;font-weight: bold&quot;/&gt;
&lt;/h:panelGrid&gt;
&lt;/p:outputPanel&gt;
&lt;/h:panelGrid&gt;
&lt;/p:dataScroller&gt;
&lt;/div&gt;
&lt;/h:form&gt;
&lt;/f:view&gt;
&lt;/html&gt;
[/code]

RegistrationManagedBean.java

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

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

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import net.javabeat.jpa.data.Employee;

import com.google.common.collect.Lists;

@ManagedBean
@SessionScoped
public class RegistrationManagedBean {

private Employee employee = new Employee();

private List&lt;Employee&gt; employees = new ArrayList&lt;Employee&gt;();
private EntityManagerFactory factory = null;
private EntityManager service = null;

{
factory = Persistence.createEntityManagerFactory(&quot;persistenceUnit&quot;);
service = factory.createEntityManager();
}

public RegistrationManagedBean() {

}

@SuppressWarnings({ &quot;unchecked&quot;})
@PostConstruct
public void fetchEmployees() {
for (int i = 1; i &lt; 100; i++) {
Employee emp = new Employee();
emp.setEmployeeName(&quot;Employee&quot; + i);
emp.getAddress().setAddressCountry(&quot;Address&quot; + i);
emp.getAddress().setAddressCity(&quot;Address&quot; + i);
this.service.getTransaction().begin();
this.service.persist(emp);
this.service.getTransaction().commit();
emp = new Employee();
}
this.employees = Lists.newArrayList(this.service.createQuery(&quot;select e from Employee e&quot;).getResultList());
}

public Employee getEmployee() {
return employee;
}

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

public List&lt;Employee&gt; getEmployees() {
return employees;
}

public void setEmployees(List&lt;Employee&gt; employees) {
this.employees = employees;
}

@SuppressWarnings(&quot;unchecked&quot;)
public String register() {
this.service.getTransaction().begin();
this.service.persist(employee);
this.service.getTransaction().commit();
this.employees = Lists.newArrayList(this.service.createQuery(&quot;select e from Employee e&quot;).getResultList());
this.employee = new Employee();
return &quot;&quot;;
}
}
[/code]

  • Scrolling mode is inline, so the scrolling listener would be against the DataScroller itself.
  • ScrollHeight attribute is set to be 80, so that two employees should be shown. You will be able of scrolling down until you’ve finished the first chunk of data which is 10 employees as we’ve specified in the chunkSize.
  • Once we’ve reached into the last employee in the already first fetched chunk, an Ajax request has been initiated for fetching the next chunk of data and so on.
  • For simplifying the concept, we’ve used the loader facet which would be shown at every time you’ve finished scrolling of data chunk.
  • Once you’ve pressed on the button an Ajax loader image will be shown.
  • By eliminating the loader button, the chunk of data should be fetched when reaching into bottom while scrolling.

DataScroller - First Chunk

DataScroller - Fetch Second Chunk

DataScroller - Second Chunk Fetched

2. Cache

Cache component is used to reduce page load time by caching the content after initial rendering. It is one of the useful component added as part of the PrimeFaces 5 release.

2.1 Cache Basic Info

Cache Basic Info

2.2 Cache Attributes

Cache Attributes

2.3 Cache Demo

A cache store is required to use the cache component, two different providers are supported as cache implementations are EHCache and Hazelcast. Selected provider should be configured in the web.xml via a context-param.

Also there are few more steps required for configuring an EHCache. Defining cache regions are supported by using the cache tag which contains set of attributes used for defining the all required aspects of caching mechanism.

The Wiring of cache component with the cache mechanism that defined in the ehcache.xml is done via mentioning the cache name inside the XML in the region attribute for the cache component.

Once the page is loaded initially, content inside p:cache component is cached inside the cache region of the cache provider. Postbacks on the same page or reopening the page will retrieve the output from cache instead of rendering the content regularly.

The demonstration below shows you the impact of using the cache component into resolving the #{registrationManagedBean.employees} where the invocation of getEmployees() should be processed while the invocation isn’t Postback. After that every invocation is loaded from the cache.

index.xhtml

[code lang=”xml”]
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;
xmlns:ui=&quot;http://java.sun.com/jsf/facelets&quot;
xmlns:h=&quot;http://java.sun.com/jsf/html&quot;
xmlns:f=&quot;http://java.sun.com/jsf/core&quot;
xmlns:p=&quot;http://primefaces.org/ui&quot;&gt;
&lt;h:head&gt;
&lt;script name=&quot;jquery/jquery.js&quot; library=&quot;primefaces&quot;&gt;&lt;/script&gt;
&lt;/h:head&gt;
&lt;f:view&gt;
&lt;h:form prependId=&quot;false&quot;&gt;
&lt;h2&gt;JavaBeat Tutorials&lt;/h2&gt;
&lt;h2&gt;Primefaces + Cache&lt;/h2&gt;
&lt;div style=&quot;width: 700px;border: 1px;border-style: dotted;&quot;&gt;
&lt;h:panelGrid columns=&quot;2&quot;&gt;
&lt;h:outputText value=&quot;Enter Employee Name:&quot;/&gt;
&lt;p:inputText value=&quot;#{registrationManagedBean.employee.employeeName}&quot;&gt;&lt;/p:inputText&gt;
&lt;h:outputText value=&quot;Enter Employee Address Country:&quot;/&gt;
&lt;p:inputText value=&quot;#{registrationManagedBean.employee.address.addressCountry}&quot;&gt;&lt;/p:inputText&gt;
&lt;h:outputText value=&quot;Enter Employee Address City:&quot;/&gt;
&lt;p:inputText value=&quot;#{registrationManagedBean.employee.address.addressCity}&quot;&gt;&lt;/p:inputText&gt;
&lt;/h:panelGrid&gt;
&lt;p:commandButton value=&quot;Register&quot; action=&quot;#{registrationManagedBean.register}&quot; ajax=&quot;false&quot;/&gt;
&lt;p:separator/&gt;
&lt;p:cache region=&quot;cache&quot; key=&quot;dataScrollerKey&quot;&gt;
&lt;p:dataScroller value=&quot;#{registrationManagedBean.employees}&quot; var=&quot;employee&quot; chunkSize=&quot;10&quot; mode=&quot;inline&quot; scrollHeight=&quot;80&quot;&gt;
&lt;f:facet name=&quot;header&quot;&gt;
Employees
&lt;/f:facet&gt;
&lt;f:facet name=&quot;loader&quot;&gt;
&lt;p:commandButton value=&quot;Scroll Down to Load More Employees&quot; type=&quot;button&quot;&gt;&lt;/p:commandButton&gt;
&lt;/f:facet&gt;
&lt;h:panelGrid columns=&quot;2&quot; style=&quot;width:100%&quot; columnClasses=&quot;logo,detail&quot;&gt;
&lt;p:outputPanel&gt;
&lt;h:panelGrid columns=&quot;2&quot; cellpadding=&quot;5&quot;&gt;
&lt;h:outputText value=&quot;#{employee.employeeName}&quot; style=&quot;font-weight: bold&quot;/&gt;
&lt;/h:panelGrid&gt;
&lt;/p:outputPanel&gt;
&lt;/h:panelGrid&gt;
&lt;/p:dataScroller&gt;
&lt;/p:cache&gt;
&lt;/div&gt;
&lt;/h:form&gt;
&lt;/f:view&gt;
&lt;/html&gt;
[/code]

RegistrationManagedBean.java

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

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

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import net.javabeat.jpa.data.Employee;

import com.google.common.collect.Lists;

@ManagedBean
@SessionScoped
public class RegistrationManagedBean {

private Employee employee = new Employee();

private List&lt;Employee&gt; employees = new ArrayList&lt;Employee&gt;();
private EntityManagerFactory factory = null;
private EntityManager service = null;

{
factory = Persistence.createEntityManagerFactory(&quot;persistenceUnit&quot;);
service = factory.createEntityManager();
}

public RegistrationManagedBean() {

}

@SuppressWarnings({ &quot;unchecked&quot;})
@PostConstruct
public void fetchEmployees() {
for (int i = 1; i &lt; 100; i++) {
Employee emp = new Employee();
emp.setEmployeeName(&quot;Employee&quot; + i);
emp.getAddress().setAddressCountry(&quot;Address&quot; + i);
emp.getAddress().setAddressCity(&quot;Address&quot; + i);
this.service.getTransaction().begin();
this.service.persist(emp);
this.service.getTransaction().commit();
emp = new Employee();
}
this.employees = Lists.newArrayList(this.service.createQuery(&quot;select e from Employee e&quot;).getResultList());
}

public Employee getEmployee() {
return employee;
}

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

public List&lt;Employee&gt; getEmployees() {
if(FacesContext.getCurrentInstance().isPostback()){
System.out.println(&quot;:: Postpack invocation :: Employees List is loaded from the cache ::&quot;);
}
else {
System.out.println(&quot;:: Initial Invocation :: Employees List is loaded and returned ::&quot;);
}
return employees;
}

public void setEmployees(List&lt;Employee&gt; employees) {
this.employees = employees;
}

@SuppressWarnings(&quot;unchecked&quot;)
public String register() {
this.service.getTransaction().begin();
this.service.persist(employee);
this.service.getTransaction().commit();
this.employees = Lists.newArrayList(this.service.createQuery(&quot;select e from Employee e&quot;).getResultList());
this.employee = new Employee();
return &quot;&quot;;
}
}
[/code]

ehcache.xml

[code lang=”xml”]
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;ehcache xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:noNamespaceSchemaLocation=&quot;ehcache.xsd&quot; updateCheck=&quot;true&quot;
monitoring=&quot;autodetect&quot; dynamicConfig=&quot;true&quot;&gt;
&lt;diskStore path=&quot;java.io.tmpdir&quot; /&gt;
&lt;defaultCache maxEntriesLocalHeap=&quot;10000&quot; eternal=&quot;false&quot;
timeToIdleSeconds=&quot;120&quot; timeToLiveSeconds=&quot;120&quot; diskSpoolBufferSizeMB=&quot;30&quot;
maxEntriesLocalDisk=&quot;10000000&quot; diskExpiryThreadIntervalSeconds=&quot;120&quot;
memoryStoreEvictionPolicy=&quot;LRU&quot;&gt;
&lt;persistence strategy=&quot;localTempSwap&quot;/&gt;
&lt;/defaultCache&gt;
&lt;cache name=&quot;cache&quot; maxEntriesLocalHeap=&quot;10000&quot; eternal=&quot;false&quot;
timeToIdleSeconds=&quot;120&quot; timeToLiveSeconds=&quot;120&quot; diskSpoolBufferSizeMB=&quot;30&quot;
maxEntriesLocalDisk=&quot;10000000&quot; diskExpiryThreadIntervalSeconds=&quot;120&quot;
memoryStoreEvictionPolicy=&quot;LRU&quot;&gt;
&lt;persistence strategy=&quot;localTempSwap&quot; /&gt;
&lt;/cache&gt;
&lt;/ehcache&gt;
[/code]

web.xml

[code lang=”xml”]
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; xmlns:web=&quot;http://java.sun.com/xml/ns/javaee&quot;
xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
id=&quot;WebApp_ID&quot; metadata-complete=&quot;true&quot; version=&quot;2.5&quot;&gt;
&lt;context-param&gt;
&lt;description&gt;State saving method: ‘client’ or ‘server’
(=default). See JSF Specification 2.5.2
&lt;/description&gt;
&lt;param-name&gt;javax.faces.STATE_SAVING_METHOD&lt;/param-name&gt;
&lt;param-value&gt;server&lt;/param-value&gt;
&lt;/context-param&gt;
&lt;context-param&gt;
&lt;param-name&gt;javax.faces.application.CONFIG_FILES&lt;/param-name&gt;
&lt;param-value&gt;/WEB-INF/faces-config.xml&lt;/param-value&gt;
&lt;/context-param&gt;
&lt;context-param&gt;
&lt;param-name&gt;primefaces.CACHE_PROVIDER&lt;/param-name&gt;
&lt;param-value&gt;org.primefaces.cache.EHCacheProvider&lt;/param-value&gt;
&lt;/context-param&gt;
&lt;servlet&gt;
&lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
&lt;servlet-class&gt;javax.faces.webapp.FacesServlet&lt;/servlet-class&gt;
&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;
&lt;servlet-mapping&gt;
&lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
&lt;url-pattern&gt;/faces/*&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;servlet-mapping&gt;
&lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
&lt;url-pattern&gt;*.xhtml&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;listener&gt;
&lt;listener-class&gt;com.sun.faces.config.ConfigureListener&lt;/listener-class&gt;
&lt;/listener&gt;
&lt;/web-app&gt;
[/code]

pom.xml (Maven Build)

[code lang=”xml”]
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd&quot;&gt;
&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
&lt;groupId&gt;next.javabeat.jsf&lt;/groupId&gt;
&lt;artifactId&gt;JavaBeat-Primefaces-JPA&lt;/artifactId&gt;
&lt;packaging&gt;war&lt;/packaging&gt;
&lt;version&gt;1.0&lt;/version&gt;

&lt;properties&gt;
&lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
&lt;java.version&gt;1.7&lt;/java.version&gt;
&lt;junit.version&gt;4.9&lt;/junit.version&gt;
&lt;slf4j.version&gt;1.6.4&lt;/slf4j.version&gt;
&lt;logback.version&gt;1.0.1&lt;/logback.version&gt;
&lt;log4j.version&gt;1.2.14&lt;/log4j.version&gt;

&lt;servlet.version&gt;2.5&lt;/servlet.version&gt;
&lt;jsp.version&gt;2.1&lt;/jsp.version&gt;
&lt;jstl.version&gt;1.2&lt;/jstl.version&gt;
&lt;taglibs-standard.version&gt;1.1.2&lt;/taglibs-standard.version&gt;

&lt;maven.compiler.plugin&gt;2.3.2&lt;/maven.compiler.plugin&gt;
&lt;maven.failsafe.plugin&gt;2.4.3-alpha-1&lt;/maven.failsafe.plugin&gt;

&lt;/properties&gt;

&lt;build&gt;
&lt;plugins&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
&lt;version&gt;3.1&lt;/version&gt;
&lt;configuration&gt;
&lt;source&gt;1.6&lt;/source&gt;
&lt;target&gt;1.6&lt;/target&gt;
&lt;encoding&gt;UTF-8&lt;/encoding&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;
&lt;/plugins&gt;
&lt;/build&gt;

&lt;repositories&gt;
&lt;repository&gt;
&lt;id&gt;prime-repo&lt;/id&gt;
&lt;name&gt;PrimeFaces Maven Repository&lt;/name&gt;
&lt;url&gt;http://repository.primefaces.org&lt;/url&gt;
&lt;layout&gt;default&lt;/layout&gt;
&lt;/repository&gt;
&lt;/repositories&gt;

&lt;dependencies&gt;
&lt;!– Servlet –&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.servlet&lt;/groupId&gt;
&lt;artifactId&gt;servlet-api&lt;/artifactId&gt;
&lt;version&gt;${servlet.version}&lt;/version&gt;
&lt;scope&gt;provided&lt;/scope&gt;
&lt;/dependency&gt;
&lt;!– Faces Implementation –&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.sun.faces&lt;/groupId&gt;
&lt;artifactId&gt;jsf-impl&lt;/artifactId&gt;
&lt;version&gt;2.2.4&lt;/version&gt;
&lt;/dependency&gt;
&lt;!– Faces Library –&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.sun.faces&lt;/groupId&gt;
&lt;artifactId&gt;jsf-api&lt;/artifactId&gt;
&lt;version&gt;2.2.4&lt;/version&gt;
&lt;/dependency&gt;
&lt;!– Primefaces Version 5 –&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.primefaces&lt;/groupId&gt;
&lt;artifactId&gt;primefaces&lt;/artifactId&gt;
&lt;version&gt;5.0.RC2&lt;/version&gt;
&lt;/dependency&gt;
&lt;!– JSP Library –&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.servlet.jsp&lt;/groupId&gt;
&lt;artifactId&gt;javax.servlet.jsp-api&lt;/artifactId&gt;
&lt;version&gt;2.3.1&lt;/version&gt;
&lt;/dependency&gt;
&lt;!– JSTL Library –&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.servlet&lt;/groupId&gt;
&lt;artifactId&gt;jstl&lt;/artifactId&gt;
&lt;version&gt;1.1.2&lt;/version&gt;
&lt;/dependency&gt;
&lt;!– Google List Library –&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.google.guava&lt;/groupId&gt;
&lt;artifactId&gt;guava&lt;/artifactId&gt;
&lt;version&gt;r09&lt;/version&gt;
&lt;/dependency&gt;
&lt;!– Dependencies for Eclipse JPA Persistence API –&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.eclipse.persistence&lt;/groupId&gt;
&lt;artifactId&gt;eclipselink&lt;/artifactId&gt;
&lt;version&gt;2.5.0-RC1&lt;/version&gt;
&lt;exclusions&gt;
&lt;exclusion&gt;
&lt;groupId&gt;org.eclipse.persistence&lt;/groupId&gt;
&lt;artifactId&gt;commonj.sdo&lt;/artifactId&gt;
&lt;/exclusion&gt;
&lt;/exclusions&gt;
&lt;/dependency&gt;
&lt;!– Dependency for MySql Java connector –&gt;
&lt;dependency&gt;
&lt;groupId&gt;mysql&lt;/groupId&gt;
&lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
&lt;version&gt;5.1.30&lt;/version&gt;
&lt;/dependency&gt;
&lt;!– Dependency for ehcache provider –&gt;
&lt;dependency&gt;
&lt;groupId&gt;net.sf.ehcache&lt;/groupId&gt;
&lt;artifactId&gt;ehcache-core&lt;/artifactId&gt;
&lt;version&gt;2.6.9&lt;/version&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;

&lt;/project&gt;
[/code]

Cache - Demo

  • Even we’ve provided a message print when the request become Postback, but it’s not shown.
  • The second Postback request is processed by the cache, thus the message of Postback in the getEmployees() hasn’t invoked.
  • Initial invocation has been displayed three times, cause nature of JSF lifecycle.

3. Spotlight

Spotlight highlights a certain component on page.

3.1 Spotlight Basic Info

Spotlight Basic Info

3.2 Spotlight Attributes

Spotlight Attributes

3.3 Spotlight Demo

Spotlight component is accessed by using the client side API. Before registration of new employee, nothing shown at all. Once Register action has been activated by clicking , an employees Table got highlighted for a while and all components are disabled except that highlighted one. Once the action has been returned and Register method finished, the highlight is never seen and everything got be normal again.
index.hxtml

[code lang=”xml”]
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;
xmlns:ui=&quot;http://java.sun.com/jsf/facelets&quot;
xmlns:h=&quot;http://java.sun.com/jsf/html&quot;
xmlns:f=&quot;http://java.sun.com/jsf/core&quot;
xmlns:p=&quot;http://primefaces.org/ui&quot;&gt;
&lt;h:head&gt;
&lt;script name=&quot;jquery/jquery.js&quot; library=&quot;primefaces&quot;&gt;&lt;/script&gt;
&lt;/h:head&gt;
&lt;f:view&gt;
&lt;h:form prependId=&quot;false&quot;&gt;
&lt;h2&gt;JavaBeat Tutorials&lt;/h2&gt;
&lt;h2&gt;Primefaces + Cache&lt;/h2&gt;
&lt;div style=&quot;width: 700px;border: 1px;border-style: dotted;&quot;&gt;
&lt;h:panelGrid columns=&quot;2&quot;&gt;
&lt;h:outputText value=&quot;Enter Employee Name:&quot;/&gt;
&lt;p:inputText value=&quot;#{registrationManagedBean.employee.employeeName}&quot;&gt;&lt;/p:inputText&gt;
&lt;h:outputText value=&quot;Enter Employee Address Country:&quot;/&gt;
&lt;p:inputText value=&quot;#{registrationManagedBean.employee.address.addressCountry}&quot;&gt;&lt;/p:inputText&gt;
&lt;h:outputText value=&quot;Enter Employee Address City:&quot;/&gt;
&lt;p:inputText value=&quot;#{registrationManagedBean.employee.address.addressCity}&quot;&gt;&lt;/p:inputText&gt;
&lt;/h:panelGrid&gt;
&lt;p:commandButton value=&quot;Register&quot; action=&quot;#{registrationManagedBean.register}&quot; ajax=&quot;false&quot; onclick=&quot;PF(‘spot’).show()&quot;/&gt;
&lt;p:spotlight target=&quot;dataScroller&quot; widgetVar=&quot;spot&quot;&gt;&lt;/p:spotlight&gt;
&lt;p:separator/&gt;
&lt;p:dataScroller id=&quot;dataScroller&quot; value=&quot;#{registrationManagedBean.employees}&quot; var=&quot;employee&quot; chunkSize=&quot;10&quot; mode=&quot;inline&quot; scrollHeight=&quot;80&quot;&gt;
&lt;f:facet name=&quot;header&quot;&gt;
Employees
&lt;/f:facet&gt;
&lt;f:facet name=&quot;loader&quot;&gt;
&lt;p:commandButton value=&quot;Scroll Down to Load More Employees&quot; type=&quot;button&quot;&gt;&lt;/p:commandButton&gt;
&lt;/f:facet&gt;
&lt;h:panelGrid columns=&quot;2&quot; style=&quot;width:100%&quot; columnClasses=&quot;logo,detail&quot;&gt;
&lt;p:outputPanel&gt;
&lt;h:panelGrid columns=&quot;2&quot; cellpadding=&quot;5&quot;&gt;
&lt;h:outputText value=&quot;#{employee.employeeName}&quot; style=&quot;font-weight: bold&quot;/&gt;
&lt;/h:panelGrid&gt;
&lt;/p:outputPanel&gt;
&lt;/h:panelGrid&gt;
&lt;/p:dataScroller&gt;
&lt;/div&gt;
&lt;/h:form&gt;
&lt;/f:view&gt;
&lt;/html&gt;
[/code]

RegistrationManagedBean.java

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

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

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import net.javabeat.jpa.data.Employee;

import com.google.common.collect.Lists;

@ManagedBean
@SessionScoped
public class RegistrationManagedBean {

private Employee employee = new Employee();

private List&lt;Employee&gt; employees = new ArrayList&lt;Employee&gt;();
private EntityManagerFactory factory = null;
private EntityManager service = null;

{
factory = Persistence.createEntityManagerFactory(&quot;persistenceUnit&quot;);
service = factory.createEntityManager();
}

public RegistrationManagedBean() {

}

@SuppressWarnings({ &quot;unchecked&quot;})
@PostConstruct
public void fetchEmployees() {
this.employees = Lists.newArrayList(this.service.createQuery(&quot;select e from Employee e&quot;).getResultList());
}

public Employee getEmployee() {
return employee;
}

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

public List&lt;Employee&gt; getEmployees() {
if(FacesContext.getCurrentInstance().isPostback()){
System.out.println(&quot;:: Postpack invocation :: Employees List is loaded from the cache ::&quot;);
}
else {
System.out.println(&quot;:: Initial Invocation :: Employees List is loaded and returned ::&quot;);
}
return employees;
}

public void setEmployees(List&lt;Employee&gt; employees) {
this.employees = employees;
}

@SuppressWarnings(&quot;unchecked&quot;)
public String register() throws InterruptedException {
this.service.getTransaction().begin();
this.service.persist(employee);
this.service.getTransaction().commit();
this.employees = Lists.newArrayList(this.service.createQuery(&quot;select e from Employee e&quot;).getResultList());
Thread.currentThread().sleep(800);
this.employee = new Employee();
return &quot;&quot;;
}
}
[/code]

Before Highlighting Employees Table

After Highlighting Employees Table

Employee Registration Had Finished

4. ColumnToggler

Visibility of dataTable columns can be controlled through using of column Toggler component. Regardless of the location that you’ve positioned column Toggler component inside your Table, either inside the head of the table or in one of those columns you’ve defined.

Once you’ve trigger the toggler by clicking on the trigger itself (which might be command button) a list of all dataTable columns become seen for your visibility control. Just check those columns you would see and uncheck those you wouldn’t.

ColumnToggler component has provided two mandatory attributes you must define when it comes to be used.

  • Datasource (Table) in which the ColumnToggler component will get the columns ready for being controlled and the trigger by which the toggler get displayed for controlling.
  • The remaining attributes are just normal ones, id, binding and rendered.

Toggler Displaying Controls

Toggler Controlling Columns

As you’ve seen, by toggling the dataTable columns above, you are able to seeing/hiding what you want of those columns in a fancy, easy-peasy way. Look below at the implementation required for Primefaces view where the managed bean isn’t changed.

index.xhtml

[code lang=”xml”]
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;
xmlns:ui=&quot;http://java.sun.com/jsf/facelets&quot;
xmlns:h=&quot;http://java.sun.com/jsf/html&quot;
xmlns:f=&quot;http://java.sun.com/jsf/core&quot;
xmlns:p=&quot;http://primefaces.org/ui&quot;&gt;
&lt;h:head&gt;
&lt;script name=&quot;jquery/jquery.js&quot; library=&quot;primefaces&quot;&gt;&lt;/script&gt;
&lt;/h:head&gt;
&lt;f:view&gt;
&lt;h:form prependId=&quot;false&quot;&gt;
&lt;h2&gt;JavaBeat Tutorials&lt;/h2&gt;
&lt;h2&gt;Primefaces + Column Toggler&lt;/h2&gt;
&lt;div style=&quot;width: 700px;border: 1px;border-style: dotted;&quot;&gt;
&lt;h:panelGrid columns=&quot;2&quot;&gt;
&lt;h:outputText value=&quot;Enter Employee Name:&quot;/&gt;
&lt;p:inputText value=&quot;#{registrationManagedBean.employee.employeeName}&quot;&gt;&lt;/p:inputText&gt;
&lt;h:outputText value=&quot;Enter Employee Address Country:&quot;/&gt;
&lt;p:inputText value=&quot;#{registrationManagedBean.employee.address.addressCountry}&quot;&gt;&lt;/p:inputText&gt;
&lt;h:outputText value=&quot;Enter Employee Address City:&quot;/&gt;
&lt;p:inputText value=&quot;#{registrationManagedBean.employee.address.addressCity}&quot;&gt;&lt;/p:inputText&gt;
&lt;/h:panelGrid&gt;
&lt;p:commandButton value=&quot;Register&quot; action=&quot;#{registrationManagedBean.register}&quot; ajax=&quot;false&quot;/&gt;
&lt;p:separator/&gt;
&lt;p:dataTable id=&quot;employeesSource&quot; value=&quot;#{registrationManagedBean.employees}&quot; var=&quot;employee&quot;&gt;
&lt;f:facet name=&quot;header&quot;&gt;
Employees
&lt;p:commandButton id=&quot;toggler&quot; type=&quot;button&quot; value=&quot;Columns&quot; style=&quot;float:right&quot; icon=&quot;ui-icon-calculator&quot; /&gt;
&lt;p:columnToggler datasource=&quot;employeesSource&quot; trigger=&quot;toggler&quot; /&gt;
&lt;/f:facet&gt;
&lt;p:column&gt;
&lt;f:facet name=&quot;header&quot;&gt;
&lt;p:outputLabel value=&quot;Employee Id&quot;&gt;&lt;/p:outputLabel&gt;
&lt;/f:facet&gt;
&lt;p:outputLabel value=&quot;#{employee.employeeId}&quot;&gt;&lt;/p:outputLabel&gt;
&lt;/p:column&gt;
&lt;p:column&gt;
&lt;f:facet name=&quot;header&quot;&gt;
&lt;p:outputLabel value=&quot;Employee Name&quot;&gt;&lt;/p:outputLabel&gt;
&lt;/f:facet&gt;
&lt;p:outputLabel value=&quot;#{employee.employeeName}&quot;&gt;&lt;/p:outputLabel&gt;
&lt;/p:column&gt;
&lt;p:column&gt;
&lt;f:facet name=&quot;header&quot;&gt;
&lt;p:outputLabel value=&quot;Employee’s Address Country&quot;&gt;&lt;/p:outputLabel&gt;
&lt;/f:facet&gt;
&lt;p:outputLabel value=&quot;#{employee.address.addressCountry}&quot;&gt;&lt;/p:outputLabel&gt;
&lt;/p:column&gt;
&lt;p:column&gt;
&lt;f:facet name=&quot;header&quot;&gt;
&lt;p:outputLabel value=&quot;Employee’s Address City&quot;&gt;&lt;/p:outputLabel&gt;
&lt;/f:facet&gt;
&lt;p:outputLabel value=&quot;#{employee.address.addressCity}&quot;&gt;&lt;/p:outputLabel&gt;
&lt;/p:column&gt;
&lt;/p:dataTable&gt;
&lt;/div&gt;
&lt;/h:form&gt;
&lt;/f:view&gt;
&lt;/html&gt;
[/code]

5. Content Flow

Content flow is a horizontal content gallery component with a slide animation.

5.1 Content Flow Basic Info

ContentFlow - Basic Info

5.2 Content Flow Attributes

ContentFlow - Attributes

5.3 Content Flow Demo

ContentFlow requires content as children that can either be defined dynamically using iteration or one by one. Each item must have the content style class applied as well.

indexContentFlow.xhtml

[code lang=”xml”]
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;
xmlns:ui=&quot;http://java.sun.com/jsf/facelets&quot;
xmlns:h=&quot;http://java.sun.com/jsf/html&quot;
xmlns:f=&quot;http://java.sun.com/jsf/core&quot;
xmlns:p=&quot;http://primefaces.org/ui&quot;&gt;
&lt;h:head&gt;
&lt;script name=&quot;jquery/jquery.js&quot; library=&quot;primefaces&quot;&gt;&lt;/script&gt;
&lt;/h:head&gt;
&lt;f:view&gt;
&lt;h:form prependId=&quot;false&quot;&gt;
&lt;h2&gt;JavaBeat Tutorials&lt;/h2&gt;
&lt;h2&gt;Primefaces + ContentFlow&lt;/h2&gt;
&lt;p:outputPanel style=&quot;width: 700px;border: 1px;border-style: dotted;&quot;&gt;
&lt;p:contentFlow id=&quot;contentFlow&quot; value=&quot;#{imageView.images}&quot; var=&quot;image&quot;&gt;
&lt;h:graphicImage url=&quot;/resources/images/Image-#{image}.jpg&quot; styleClass=&quot;content&quot;&gt;&lt;/h:graphicImage&gt;
&lt;/p:contentFlow&gt;
&lt;/p:outputPanel&gt;
&lt;/h:form&gt;
&lt;/f:view&gt;
&lt;/html&gt;
[/code]

ImageView.java

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

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

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

@ManagedBean
@RequestScoped
public class ImageView {
private List&lt;String&gt; images = new ArrayList&lt;String&gt;();

public ImageView(){
this.images.add(&quot;1&quot;);
this.images.add(&quot;2&quot;);
}

public List&lt;String&gt; getImages() {
return images;
}

public void setImages(List&lt;String&gt; images) {
this.images = images;
}
}
[/code]

PrimeFaces 5 Project Structure

ContentFlow - Project Structure - Images Location

ContentFlow Demo

6. Persistence Entities

As per our explanation, we’ve introduced a JPA operations in our examples. These operations are done by a JPA entities and those entities are:

Address.java

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

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

@Entity(name = &quot;address&quot;)
public class Address {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer addressId;
private String addressCountry = &quot;&quot;;
private String addressCity = &quot;&quot;;

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

public Employee getEmployee() {
return employee;
}

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

public Integer getAddressId() {
return addressId;
}

public void setAddressId(Integer 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]

Employee.java

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

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

@Entity
public class Employee {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer employeeId;

@Basic(optional = false)
private String employeeName;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = &quot;Address&quot;)
private Address address = new 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;
}
}
[/code]

7. Known issue

As you’ve seen, Primefaces content flow component doesn’t work for versions 5.0, 5.0.RC1, 5.0.RC2. We’ve opened a case at the Primefaces forums and this tutorial will be updated accordingly to the forum post.

8. Summary

Primefaces is one of the popular library for implementing JavaServer Faces UI. This tutorial has discussed most of the components introduced as part of the PrimeFaces 5. DataScroller, Cache, Spotlight, ColumnToggler and ContentFlow providing you a additional features in for UI design that your application may need.

Download Source Code for PrimeFaces 5

[wpdm_file id=113]

Filed Under: JSF Tagged With: PrimeFaces

Bower – Web Package Manager

June 10, 2014 by Amr Mohammed Leave a Comment

Bower is a package manager for the web. It offers a generic solution to the problem of front-end package management. Using of Bower will eliminate the need of downloading the JavaScript libraries into your project, so all the developer have to do, is to initiate a Bower into their own project and installing the required libraries by using Bower instructions.

This tutorial explains how to install bower and use it in your machine. Before discussing about Bower, it’s important to list of all prerequisite software and install them before going into Bower installation and use. Also end of this tutorial, I have explained how to import jQuery libraries using the bower commands. If you have any questions, please write it in the comments section.

Bower Package Manager

1. Install Git

Git, Git is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency. To install Git into your machine you have to do the following:

  • Download Git binary from its official site.
  • Double click on the downloaded file which might be Git-1.9.2-preview20140411.exe.

Git Initial Screen

  • Click Next.

Git License

  • Click Next.

Git- Specify Installation Destination

  • Specify the installation destination and click Next.

Git - Components Installed

  • Let default selected components & click Next.

Git - Start Menu Option

  • Let default start menu value and click Next.

Git - Adjusting Your Path Environment

  • Select the second option “Use Git from the Windows Command Prompt” and click Next.

Git - Configutring the line ending conversion

  • Let the default line ending and click Next.
  • Wait for a while being Git installed.

Git - Installing

  • Click Finish.
  • To make sure that you’ve installed Git properly, just open a command line window and type git, as a result of it should be shown like this:

Git - Command Line

Now you have installed the git in your system.

2. Install Node.js

Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. For installing the node.js you have to follow the below steps:

  • Download the node.js software; the version we used is for 64bit.

Node - Welcome Message

  • Click Next.

Node - Accept Agreement

  • Accept the agreement and click Next.

Node - Specify Installation Destination

  • Specify the destination required.

Node -  Select Installed Features

  • Click Next & Install.

Node - Installing

  • Click Finish.
  • Open the CMD and type node -v for node version.
  • Open the CMD and type npm -version for npm version.

After finish the installation, you’re ready for getting started using Bower. Bower depends on Node and npm.

3. Install Bower

Once the above installations are completed, now it is time to install the Bower to your system. Lets follow the below steps for downloading and installing the bower:

  • Open a Command Line for windows.
  • Type into command line npm install -g bower .
  • Wait for a while until the installing has been finished, as your console should look like

Installing Bower

  • The bower will be installed into your profile beneath the path C:\Users\YourAccount\AppData\Roaming\npm

Bower Installtion Path

  • To ensure that you have a proper bower installed, just type into your command console bower -version and for sure you must get a version like below.

Bower Version

4. Bower Example

We have completed the installation of bower in the above section, now we will write a simple example using the bower. It’s good for you going through a example of how could you use the Bower for installing the required libraries. For that, I have created an empty folder called BowerExample located at the D:\BowerExample path and we’re going to use an HTML page referencing a jQuery library. Now, we will not install the jQuery library from the jQuery site and it will not referenced by using the CDN jQuery library path.

To get jQuery referenced and used from within a BowerExample folder you have to follow the below steps:

  • As a first step, you have to initialize the BowerExample empty folder by using the command line, just initiate the Bower by typing the command “bower init” for preparing the Bower json files which will contain the required information for your project as you’ve seen in the below screenshot.
  • Bower has prompted you set of configuration questions like:
    • the name of the project
    • version
    • descriptions
    • type of modules being used and others.
  • In case you’re not pretty sure from your answering just pressing enter for taking the default value.

Initiate Bower

  • Now, it’s the time for looking up jQuery library so just type bower lookup jQuery. That look up will help you determining if you can install it into your project or not.

Looking up jQuery Library using Bower 

  • It would help you ensuring that the library is found and it can be installed as response like Package not found gives you an indication of package is not available and could not be detected by the Bower.
  • Now, it’s time to install the jQuery library, so just typing bower install followed by the green name printed out in the previous step which lead us for bower install jQuery.

Bower Installing jQuery

  • The final structure of the example become as below:

Bower Example Structure

The index.html is just a simple HTML page and it might be more complicated than what you’ve seen below

index.html

[code lang=”xml”]
<html>
<head>
<script src="bower_components\jQuery\dist\jquery.min.js"></script>
<Script>
alert("JQuery Used For Referencing Div Component :: "+$("#div"));
</script>
</head>
<body>
<h2>JavaBeat Tutorials</h2>
<h2>Installing JavaScript Libraries Using Bower</h2>
<div id="div"></div>
</body>
</html>
[/code]

Double click on the index.html cause the above HTML to be executed via the browser.

Running Bower Example

  • Also additional jQuery libraries are installed beside all of the core jQuery library as you’ve seen inside the project structure itself.

Filed Under: JavaScript Tagged With: Bower, Git, NodeJS Basics, npm

Spring Data JPA : Custom Repository / Query Methods Example

June 8, 2014 by Amr Mohammed Leave a Comment

In this tutorial i am going to explain how to use query methods and custom repository implementation in Spring Data JPA framework. I have used Primfaces and JSF to develop the front end to access data using Spring Data infrastructure.

When you’re developing a Spring Data Repository, you’ll have three options:

  1. Using of a CRUD operations that implemented by the Spring Data infrastructure
  2. Defining of a query methods and
  3. Manually implementing your own custom repositories.

The following are the sections covered in this tutorial.

  1. Introduction
  2. Query Methods
  3. Spring Data Custom Repository
  4. Spring Configurations
  5. Persistence Entities
  6. Spring Service
  7. Primefaces / JSF Managed Bean
  8. JSF Configurations
  9. Maven Build
  10. Spring Data + Custom Repository + Query Methods Demo
  11. Database Table Queries
  12. Summary
  13. Download Source Code

1. Introduction

In our previous tutorials, we have explained the first option, in that, a vast amount of tutorials had used the infrastructure repositories. We have not explored any samples for the query methods and custom repository in our previous tutorials. In this tutorial, you would see how could we implement a Query methods and how to implement a custom repositories in spring data.

  • Spring Data provides the developers ability to define their own custom queries by declaring a method.
  • The method declaration will be inspected by the infrastructure and parsed, and a store-specific query was derived eventually.
  • However, as the queries become more complex, the method names would become awkwardly, until you’ve reached into level the keywords supported by the method parser wouldn’t even suffice.
  • Thus, Spring Data provides you a special annotation @Query that would take a query as a string that formed in the store-specific query language.

In this tutorial, we would use the MySQL as a persistent store, thus, JPA (Java Persistence API) & JPQL for defining the mapping and queries.

2. Query Methods

The query derivation mechanism built into the Spring Data repository infrastructure is useful to build constraining queries over entities of the repository. The below points represent the major points for creating a query method in your own repository.

  • Start the method name with one of the prefixes findBy, readBy and getBy.
  • Complete the method name by adding one or more of the entity’s properties and concatenate them with And and Or.
  • Operators like Between, LessThan, GreaterThan & Like are also applicable.
  • Define a nested properties is applicable (Employees have addresses).
  • Once you’ve finished writing your own query methods, a compilation error time could be raised if your query couldn’t be parsed.

Find below EmployeeRepository that we’ve defined in our previous tutorials. This time the repository has a set of query methods which derived from the Employee entity.

At the same time, a not valid query methods cause you will find an error like below:

Spring Data - Not Valid Query Methods

3. Spring Data Custom Repository

Until now, you’ve created repositories that exposed a CRUD methods or a query methods. Both types are implemented by the Spring Data infrastructure, either by a backing implementation (Repository proxy) or the query execution engine (Query Derivation). These two cases will probably cover a broad range of data access operations you’ll face when building applications. Often, it is necessary to provide a custom implementation for a certain repository methods.

Spring Data provides you an intelligent way to integrate your custom repository code and integrate it with the generic CRUD abstraction and query method functionality.

To enrich a repository with custom functionality you first define an interface and an implementation for the custom functionality. Use the repository interface you provided to extend the custom interface.

EmployeeRepositoryCustom.java

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

import java.util.List;

import net.javabeat.springdata.jpa.data.Employee;

public interface EmployeeRepositoryCustom {

public List<Employee> readByEmployeeName(String name);

}

[/code]

EmployeeRepositoryImpl.java

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

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import net.javabeat.springdata.jpa.data.Employee;

public class EmployeeRepositoryImpl implements EmployeeRepositoryCustom{
@PersistenceContext
private EntityManager entityManager;

@SuppressWarnings("unchecked")
@Override
public List<Employee> readByEmployeeName(String name) {
return this.entityManager.
createQuery("select e from Employee e where e.employeeName like ‘"+name+"’").
getResultList();
}

}

[/code]

Your custom repository as you’ve seen doesn’t depend on the Spring Data, it’s like a normal Spring Bean. So it’s possible to contain an injection aspect or any other aspect you want supported by Spring framework. As you’ve noted the entityManager has been injected into our custom implementation.

After finished your custom repository and its implementation, it’s the time for you to upgrade your abstract repository (EmployeeRepository) so that it contains the custom behaviors. Just makes it extends another interface as below.

EmployeeRepository.java

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

import java.util.List;

import net.javabeat.springdata.jpa.data.Employee;

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

@Repository
public interface EmployeeRepository extends CrudRepository<Employee, Integer>,EmployeeRepositoryCustom{

public List<Employee> findByEmployeeName(String name);
public List<Employee> getByEmployeeId(Integer id);
public List<Employee> findByEmployeeNameAndEmployeeId(String name, Integer id);
public List<Employee> findByEmployeeIdGreaterThan(Integer id);
public List<Employee> findByEmployeeIdBetween(Integer lowerValue, Integer upperValue);
public List<Employee> findByAddressAddressCountry(String country);
public List<Employee> findAll();
}

[/code]

For now, you’ve created your own custom repository and it’s implementation and added your custom behaviors into your original repository. But a big question here is, how could your custom repository been detected by the Spring Data specifically, we’ve not used any type of annotations related to neither inside the interface nor inside the implementation,  except that responsible for injecting the persistence context.

That’s what Spring Data called the configuration of the custom repositories, in that, if you use namespace configuration (XML Spring Bean Definition), the repository infrastructure tries to auto detect custom implementations by scanning for classes below the package we found a repository in. These classes need to follow the naming convention of appending the namespace element’s attribute repository-impl-postfix to the found repository interface name. This postfix defaults to Impl and for that our custom repository named as EmployeeRepositoryImpl.

4. Spring Configurations

Here is the complete Spring namespace configuration, meanwhile i’ll provide you a fragment of how the form of repository-impl-postfix attribute could be.

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]

SpringContext.xml (Non defaulted postfix)

[code lang=”xml”]
<!– For bootstrapping the Spring Repository –>
<jpa:repositories base-package="net.javabeat.springdata.repo" repository-impl-postfix="DetectPostfixToken"/>
[/code]

In case, you’ve provided the repository-impl-postfix attribute, you should comply when defining your custom repositories.

5. Persistence Entities

These are the entities used in this tutorial.

Address.java

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

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

@Entity(name = "address")
public class Address {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
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 Integer getAddressId() {
return addressId;
}

public void setAddressId(Integer 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]

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.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

@Entity
public class Employee {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer employeeId;

@Basic(optional = false)
private String employeeName;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "Address")
private Address address = new 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;
}
}
[/code]

6. Spring Service

It’s just a bean used for referencing both of Spring Data default repository and that custom one. All of those methods contained in the custom repository are also contained in the Spring Data default repository, but the service below presents the concept of autowiring those custom repositories.

RegistrationService.java

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

import net.javabeat.springdata.repo.EmployeeRepository;
import net.javabeat.springdata.repo.EmployeeRepositoryImpl;

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

@Component
public class RegistrationService {
@Autowired
private EmployeeRepositoryImpl employeeRepositoryImpl;

@Autowired
private EmployeeRepository employeeRepository;

public EmployeeRepositoryImpl getEmployeeRepositoryImpl() {
return employeeRepositoryImpl;
}

public void setEmployeeRepositoryImpl(EmployeeRepositoryImpl employeeRepositoryImpl) {
this.employeeRepositoryImpl = employeeRepositoryImpl;
}

public EmployeeRepository getEmployeeRepository() {
return employeeRepository;
}

public void setEmployeeRepository(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}

}

[/code]

7. Primefaces / JSF Managed Bean

It’s a managed bean for handling the presentation logic.

RegistrationManagedBean.java

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

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

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

import net.javabeat.springdata.beans.RegistrationService;
import net.javabeat.springdata.jpa.data.Employee;

import com.google.common.collect.Lists;

@ManagedBean
@SessionScoped
public class RegistrationManagedBean {

private Employee employee = new Employee();

private List<Employee> employees = new ArrayList<Employee>();

public RegistrationManagedBean(){
}

@PostConstruct
public void fetchEmployees(){
this.employees = Lists.newArrayList(this.service.getEmployeeRepository().findAll());
}

@ManagedProperty(value="#{registrationService}")
private RegistrationService service;

public Employee getEmployee() {
return employee;
}

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

public List<Employee> getEmployees() {
return employees;
}

public void setEmployees(List<Employee> employees) {
this.employees = employees;
}

public RegistrationService getService() {
return service;
}

public void setService(RegistrationService service) {
this.service = service;
}

public String register(){
this.service.getEmployeeRepository().save(this.employee);
this.employees = this.service.getEmployeeRepository().findAll();
this.employee = new Employee();
return "";
}

public void findByEmployeeName(){
this.employees = Lists.newArrayList(this.service.getEmployeeRepository().readByEmployeeName(this.employee.getEmployeeName()));
}

public void findByEmployeeAddressAddressCountry(){
this.employees = Lists.newArrayList(this.service.getEmployeeRepository().findByAddressAddressCountry(this.employee.getAddress().getAddressCountry()));

}

}

[/code]

8. JSF Configurations

It’s faces configuration file that used for configuring the JSF framework in this tutorial.

  • Also Read : Introduction to JSF

faces-config.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd" version="2.2">
<application>
<resource-bundle>
<base-name>net.javabeat.jsf.application</base-name>
<var>msg</var>
</resource-bundle>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
</faces-config>

[/code]

9. Maven Build

Here is the complete maven build file for downloading dependencies used for 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-Primefaces-SpringData-QueryMethods-ManualRepository</artifactId>
<packaging>war</packaging>
<version>1.0</version>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.7</java.version>
<junit.version>4.9</junit.version>
<slf4j.version>1.6.4</slf4j.version>
<logback.version>1.0.1</logback.version>
<log4j.version>1.2.14</log4j.version>

<servlet.version>2.5</servlet.version>
<jsp.version>2.1</jsp.version>
<jstl.version>1.2</jstl.version>
<taglibs-standard.version>1.1.2</taglibs-standard.version>

<maven.compiler.plugin>2.3.2</maven.compiler.plugin>
<maven.failsafe.plugin>2.4.3-alpha-1</maven.failsafe.plugin>

</properties>

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

<repositories>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>

<dependencies>
<!– Servlet –>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<!– Faces Implementation –>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.4</version>
</dependency>
<!– Faces Library –>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.4</version>
</dependency>
<!– Primefaces Version 5 –>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>5.0.RC2</version>
</dependency>
<!– JSP Library –>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<!– JSTL Library –>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<!– Spring Core –>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<!– Spring Web –>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<!– Google List Library –>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>r09</version>
</dependency>
<!– 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>
<!– Spring Data Dependency –>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.5.2.RELEASE</version>
</dependency> <!– Dependency for MySql Java connector –>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
</dependencies>

</project>

[/code]

10. Spring Data + Custom Repository + Query Methods Demo

Spring Data - Custom Repository - Query Derivation - Demo

Spring Data - Custom Repository - Query Derivation - Demo II

Spring Data - Custom Repository - Query Derivation - Demo III

11. Database Tables Queries

Here is the database table creation and data population scripts used for populating sample data for this tutorial.

[code lang=”xml”]
CREATE TABLE `address` (
`addressId` bigint(20) NOT NULL AUTO_INCREMENT,
`addressCountry` varchar(45) DEFAULT NULL,
`addressCity` varchar(45) DEFAULT NULL,
PRIMARY KEY (`addressId`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
SELECT * FROM javabeat.employee;

CREATE TABLE `employee` (
`employeeId` bigint(20) NOT NULL AUTO_INCREMENT,
`employeeName` varchar(20) DEFAULT NULL,
`address` bigint(20) DEFAULT NULL,
PRIMARY KEY (`employeeId`),
KEY `FK_EMP_ADD` (`address`),
CONSTRAINT `FK_EMP_ADD` FOREIGN KEY (`address`) REFERENCES `address` (`addressId`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

[/code]

12. Summary

In this tutorial I have explained how to use the query methods and custom repository in Spring Data. This is useful when you want to define your own repository for your application. By looking at the above explanation, implementing custom repository is simple for the spring data developers. If you have any questions, please write it in the comments section. Please download the complete source code in the next section.

13. Download Source Code

[wpdm_file id=111]

Filed Under: Spring Framework Tagged With: PrimeFaces, Spring Data JPA

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&amp;amp;lt;Message,Integer&amp;amp;gt; {}
[/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"]
&amp;amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;amp;gt;
&amp;amp;lt;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"&amp;amp;gt;
&amp;amp;lt;!-- Search for spring components --&amp;amp;gt;
&amp;amp;lt;context:component-scan base-package="net.javabeat"&amp;amp;gt;&amp;amp;lt;/context:component-scan&amp;amp;gt;
&amp;amp;lt;!-- Declare GemFire Cache --&amp;amp;gt;
&amp;amp;lt;gfe:cache/&amp;amp;gt;
&amp;amp;lt;!-- Local region for being used by the Message --&amp;amp;gt;
&amp;amp;lt;gfe:local-region id="messages" value-constraint="net.javabeat.springdata.data.Message"/&amp;amp;gt;
&amp;amp;lt;!-- Search for GemFire repositories --&amp;amp;gt;
&amp;amp;lt;gfe-data:repositories base-package="net.javabeat.springdata.repo"/&amp;amp;gt;
&amp;amp;lt;/beans&amp;amp;gt;
[/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"]
&amp;amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;amp;gt;
&amp;amp;lt;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"&amp;amp;gt;
&amp;amp;lt;context-param&amp;amp;gt;
&amp;amp;lt;param-name&amp;amp;gt;contextConfigLocation&amp;amp;lt;/param-name&amp;amp;gt;
&amp;amp;lt;param-value&amp;amp;gt;/WEB-INF/spring-config/SpringContext.xml&amp;amp;lt;/param-value&amp;amp;gt;
&amp;amp;lt;/context-param&amp;amp;gt;
&amp;amp;lt;servlet&amp;amp;gt;
&amp;amp;lt;servlet-name&amp;amp;gt;rest&amp;amp;lt;/servlet-name&amp;amp;gt;
&amp;amp;lt;servlet-class&amp;amp;gt;org.springframework.data.rest.webmvc.RepositoryRestDispatcherServlet&amp;amp;lt;/servlet-class&amp;amp;gt;
&amp;amp;lt;/servlet&amp;amp;gt;
&amp;amp;lt;servlet-mapping&amp;amp;gt;
&amp;amp;lt;servlet-name&amp;amp;gt;rest&amp;amp;lt;/servlet-name&amp;amp;gt;
&amp;amp;lt;url-pattern&amp;amp;gt;/rest/*&amp;amp;lt;/url-pattern&amp;amp;gt;
&amp;amp;lt;/servlet-mapping&amp;amp;gt;
&amp;amp;lt;listener&amp;amp;gt;
&amp;amp;lt;listener-class&amp;amp;gt;org.springframework.web.context.ContextLoaderListener&amp;amp;lt;/listener-class&amp;amp;gt;
&amp;amp;lt;/listener&amp;amp;gt;
&amp;amp;lt;/web-app&amp;amp;gt;
[/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"]
&amp;amp;lt;!doctype html&amp;amp;gt;
&amp;amp;lt;html&amp;amp;gt;
&amp;amp;lt;head&amp;amp;gt;
&amp;amp;lt;title&amp;amp;gt;GemFire Backbone&amp;amp;lt;/title&amp;amp;gt;
&amp;amp;lt;script data-curl-run="boot.js" src="bower_components/curl/src/curl.js"&amp;amp;gt;&amp;amp;lt;/script&amp;amp;gt;
&amp;amp;lt;script type="text/html" id="gemfire-template"&amp;amp;gt;
&amp;amp;lt;% _.each(_embedded.messages, function(message) { %&amp;amp;gt;
Message :: &amp;amp;lt;%= message.message %&amp;amp;gt; :: &amp;amp;lt;a href='&amp;amp;lt;%= message._links.self.href%&amp;amp;gt;'&amp;amp;gt;Message Link&amp;amp;lt;/a&amp;amp;gt;
&amp;amp;lt;br/&amp;amp;gt;
&amp;amp;lt;% }); %&amp;amp;gt;
&amp;amp;lt;/script&amp;amp;gt;
&amp;amp;lt;/head&amp;amp;gt;
&amp;amp;lt;body&amp;amp;gt;
&amp;amp;lt;h2&amp;amp;gt;JavaBeat Tutorials&amp;amp;lt;/h2&amp;amp;gt;
&amp;amp;lt;h3&amp;amp;gt;Spring Data REST - GemFire - Backbone Integration&amp;amp;lt;/h3&amp;amp;gt;
&amp;amp;lt;div class="messages"&amp;amp;gt;

&amp;amp;lt;/div&amp;amp;gt;
&amp;amp;lt;/body&amp;amp;gt;
&amp;amp;lt;/html&amp;amp;gt;
[/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"]
&amp;amp;lt;script data-curl-run="boot.js" src="lib/curl/src/curl.js"&amp;amp;gt;&amp;amp;lt;/script&amp;amp;gt;
[/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"]
&amp;amp;lt;script type="text/html" id="gemfire-template"&amp;amp;gt;
&amp;amp;lt;% _.each(_embedded.messages, function(message) { %&amp;amp;gt;
Message :: &amp;amp;lt;%= message.message %&amp;amp;gt; :: &amp;amp;lt;a href='&amp;amp;lt;%= message._links.self.href%&amp;amp;gt;'&amp;amp;gt;Message Link&amp;amp;lt;/a&amp;amp;gt;
&amp;amp;lt;br/&amp;amp;gt;
&amp;amp;lt;% }); %&amp;amp;gt;
&amp;amp;lt;/script&amp;amp;gt;
[/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"]
&amp;amp;lt;div class="messages"&amp;amp;gt;&amp;amp;lt;/div&amp;amp;gt;
[/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&lt;Message,Integer&gt; {}
[/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”]
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;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"&gt;
&lt;!– Search for spring components –&gt;
&lt;context:component-scan base-package="net.javabeat"&gt;&lt;/context:component-scan&gt;
&lt;!– Declare GemFire Cache –&gt;
&lt;gfe:cache/&gt;
&lt;!– Local region for being used by the Message –&gt;
&lt;gfe:local-region id="messages" value-constraint="net.javabeat.springdata.data.Message"/&gt;
&lt;!– Search for GemFire repositories –&gt;
&lt;gfe-data:repositories base-package="net.javabeat.springdata.repo"/&gt;
&lt;/beans&gt;
[/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”]
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;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"&gt;
&lt;context-param&gt;
&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
&lt;param-value&gt;/WEB-INF/spring-config/SpringContext.xml&lt;/param-value&gt;
&lt;/context-param&gt;
&lt;servlet&gt;
&lt;servlet-name&gt;rest&lt;/servlet-name&gt;
&lt;servlet-class&gt;org.springframework.data.rest.webmvc.RepositoryRestDispatcherServlet&lt;/servlet-class&gt;
&lt;/servlet&gt;
&lt;servlet-mapping&gt;
&lt;servlet-name&gt;rest&lt;/servlet-name&gt;
&lt;url-pattern&gt;/rest/*&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;listener&gt;
&lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
&lt;/listener&gt;
&lt;/web-app&gt;
[/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:’&lt;p&gt;Message #1 :: {message} :: &lt;a href=’+"{href}"+’&gt;Message Link&lt;/a&gt;&lt;/p&gt;’
}
});
[/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”]
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;JavaBeat Tutorial&lt;/title&gt;
&lt;script src="//cdn.sencha.io/touch/sencha-touch-2.1.1/sencha-touch-all.js"&gt;&lt;/script&gt;
&lt;script src="MessageApplication.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h2&gt;JavaBeat Tutorial&lt;/h2&gt;
&lt;h3&gt;Spring Data REST – &lt;h3&gt;
&lt;h3&gt;Consuming GemFire REST Resources Using Sencha Touch&lt;/h3&gt;
&lt;/body&gt;
&lt;/html&gt;
[/code]

11. Maven Build

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

[code lang=”xml”]
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;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"&gt;
&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

&lt;groupId&gt;net.javabeat.springdata&lt;/groupId&gt;
&lt;artifactId&gt;SpringData-GemFire-REST-SenchaTouch&lt;/artifactId&gt;
&lt;version&gt;1.0&lt;/version&gt;
&lt;packaging&gt;war&lt;/packaging&gt;

&lt;name&gt;Spring Data&lt;/name&gt;

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

&lt;build&gt;
&lt;plugins&gt;
&lt;plugin&gt;
&lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
&lt;version&gt;2.3.2&lt;/version&gt;
&lt;/plugin&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
&lt;/plugin&gt;
&lt;/plugins&gt;
&lt;/build&gt;

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

&lt;pluginRepositories&gt;
&lt;pluginRepository&gt;
&lt;id&gt;spring-snapshots&lt;/id&gt;
&lt;name&gt;Spring Snapshots&lt;/name&gt;
&lt;url&gt;http://repo.spring.io/libs-snapshot&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;true&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/pluginRepository&gt;
&lt;/pluginRepositories&gt;
&lt;/project&gt;
[/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

PrimeFaces + Spring Data using PagingAndSortingRepository Example

June 4, 2014 by Amr Mohammed Leave a Comment

In general, Spring Data JPA module implements the Spring Data Commons repository abstraction to ease repository implementations. As well as the Spring Data repository approach allows you to get rid of most of the implementation code by using a plain interface definition. You’ve leveraged repository implementation in your applications by creating an interfaces that extends the Repository that provided by the Spring Data infrastructure.

The Spring Data Repository captures the type of domain class as well as the type identity. But that isn’t the whole story, Spring Data, also provides different kinds of repositories.

So Spring Data provides you the following repositories.

  • Repository: A plain marker interface to let the Spring Data infrastructure pick up user defined repositories (configuration wise).
  • CrudRepository: Extends Repository and adds basic persistence methods like saving, finding and deleting entities.
  • PagingAndSortingRepositories: Extends CrudRepository and adds methods for accessing entities page by page ans sorting them by given criteria.

This tutorial guides you through a sample application to implement PrimeFaces, Spring Data and MySQL database using the PagingAndSortingRepositories to paginate the display of data. If you have any questions, please write it in the comments section.

Also read:

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

Lets look at how EmployeeRepository inherits the CrudRespository provided by Spring Data.

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.stereotype.Repository;

@Repository
public interface EmployeeRepository extends CrudRepository<Employee,Integer>{
}
[/code]

The EmployeeRepository interface now will inherit all of these methods defined in the CurdRepository which lead us for repository containing those defined methods in the CurdRepository itself.

CrudRepository.java (This is Spring Data API implementation)

[code lang=”java”]
public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {
<S extends T> save(S entity);
<S extends T> Iterable<S> save(Iterable<S> entities);
T findOne(ID id);
Iterable<T> findAll();
void delete(ID id);
void delete(T entity);
void deleteAll();
}
[/code]

So, it contains methods to save a single entity as well as an Iterable of entities, finder methods for single entity or all entities, and delete methods of different flavors. PagingAndSortingRepository now in turn extends CrudRepository and adds methods to allow handing instances of Pagable and Sort into the generic findAll methods to actually access entities page by page.

This tutorial would give the PagingAndSortingRepository example application with user interface developed using PrimeFaces.

1. Database Tables

It’s just a depicts for the database models that used for implementing the enterprise sample that really depends on a real record.

Queries For Tables Creation

[code lang=”xml”]
CREATE TABLE `address` (
`addressId` bigint(20) NOT NULL AUTO_INCREMENT,
`addressCountry` varchar(45) DEFAULT NULL,
`addressCity` varchar(45) DEFAULT NULL,
PRIMARY KEY (`addressId`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
SELECT * FROM javabeat.employee;

CREATE TABLE `employee` (
`employeeId` bigint(20) NOT NULL AUTO_INCREMENT,
`employeeName` varchar(20) DEFAULT NULL,
`address` bigint(20) DEFAULT NULL,
PRIMARY KEY (`employeeId`),
KEY `FK_EMP_ADD` (`address`),
CONSTRAINT `FK_EMP_ADD` FOREIGN KEY (`address`) REFERENCES `address` (`addressId`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
[/code]

Address Table

Employee Table

Employee Foreign Key

2. Business Domain

As you knew before, the JPA contains two major parts, the mapping and the entity manager. Here, we’ll list the mapping classes, which will be used later for achieving the CRUD operations against defined database models mentioned in the previous section.

Address.java

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

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

@Entity(name = "address")
public class Address {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
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 Integer getAddressId() {
return addressId;
}

public void setAddressId(Integer 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]

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.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

@Entity
public class Employee {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer employeeId;

@Basic(optional = false)
private String employeeName;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "Address")
private Address address = new 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;
}
}
[/code]

3. Spring Data Repositories

PagingAndSortingRepository would be used for implementing the Spring Data operations. It is the specialized version of the CrudRepository interface. PagingAndSortingRepository defines extra methods for finding the rows by passing the page numbers. Lets look at the example implementation for AddressRepository and EmployeeRepository classes.

AddressRepositiry.java

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

import net.javabeat.springdata.jpa.data.Address;

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

@Repository
public interface AddressRepository extends PagingAndSortingRepository<Address,Integer>{
}
[/code]

EmployeeRepository.java

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

import net.javabeat.springdata.jpa.data.Employee;

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

@Repository
public interface EmployeeRepository extends PagingAndSortingRepository<Employee,Integer>{

}
[/code]

4. Spring Context Configuration

Here is the XML Spring configuration that used for configuring Spring beans, repositories and MySQL entity manager.

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 Bean Service

Here is the Spring component had used for retaining a repositories proxies.

RegistrationService.java

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

import net.javabeat.springdata.repo.EmployeeRepository;

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

@Component
public class RegistrationService {
@Autowired
private EmployeeRepository employeeRepository;

public EmployeeRepository getEmployeeRepository() {
return employeeRepository;
}

public void setEmployeeRepository(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
}
[/code]

6. Primefaces Managed Beans

It’s the managed bean that used for holding the business logic for the primefaces view.

RegistrationManagedBean.java

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

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

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

import net.javabeat.springdata.beans.RegistrationService;
import net.javabeat.springdata.jpa.data.Employee;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;

@ManagedBean
@SessionScoped
public class RegistrationManagedBean {

private Employee employee = new Employee();

private List<Employee> employees = new ArrayList<Employee>();

private Page<Employee> page;

public RegistrationManagedBean(){
}

@PostConstruct
public void postInitialization(){
// Create & Initialize a Sort Object
Sort sort = new Sort(Direction.ASC,"employeeName");
// Create & Initialize a Page Object
page = this.service.getEmployeeRepository().findAll(new PageRequest(0, 3,sort));
// Fetch the employees from the page object
this.employees = page.getContent();
}

@ManagedProperty(value="#{registrationService}")
private RegistrationService service;

public Employee getEmployee() {
return employee;
}

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

public List<Employee> getEmployees() {
return employees;
}

public void setEmployees(List<Employee> employees) {
this.employees = employees;
}

public String nextEmployees(){
if(page.hasNextPage()){
this.page = this.service.getEmployeeRepository().findAll(page.nextPageable());
this.employees = page.getContent();
}
return "";
}

public String previousEmployees(){
if(page.hasPreviousPage()){
this.page = this.service.getEmployeeRepository().findAll(page.previousPageable());
this.employees = page.getContent();
}
return "";
}

public String sortByEmployeeName(){
if(page != null){
if(page.getSort() != null){
Sort sort= new Sort(Direction.ASC,"employeeName");
this.page = this.service.getEmployeeRepository().findAll(new PageRequest(this.page.getNumber(), this.page.getSize(), sort));
this.employees = this.page.getContent();
}
}
return "";
}

public String sortByEmployeeId(){
if(page != null){
if(page.getSort() != null){
Sort sort= new Sort(Direction.ASC,"employeeId");
this.page = this.service.getEmployeeRepository().findAll(new PageRequest(this.page.getNumber(), this.page.getSize(), sort));
this.employees = this.page.getContent();
}
}
return "";
}

public RegistrationService getService() {
return service;
}

public void setService(RegistrationService service) {
this.service = service;
}

public Page<Employee> getPage() {
return page;
}

public void setPage(Page<Employee> page) {
this.page = page;
}

public String register(){
this.service.getEmployeeRepository().save(this.employee);
this.employee = new Employee();
return "";
}
}
[/code]

7. Faces Configuration File

For making the Spring beans referenced by the faces managed beans, your face-config.xml should look like

faces-config.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
version="2.2">
<application>
<resource-bundle>
<base-name>net.javabeat.jsf.application</base-name>
<var>msg</var>
</resource-bundle>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
</faces-config>
[/code]

8. Primefaces View

It’s the primefaces view page.

index.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<f:view>
<h:form prependId="false">
<h2>JavaBeat Tutorials</h2>
<h2>Primefaces + Spring Data + PagingAndSortingRepository + MySQL</h2>
<div style="width: 700px;border: 1px;border-style: dotted;">
<h:panelGrid columns="2">
<h:outputText value="Enter Employee Name:"/>
<p:inputText value="#{registrationManagedBean.employee.employeeName}"></p:inputText>
<h:outputText value="Enter Employee Address Country:"/>
<p:inputText value="#{registrationManagedBean.employee.address.addressCountry}"></p:inputText>
<h:outputText value="Enter Employee Address City:"/>
<p:inputText value="#{registrationManagedBean.employee.address.addressCity}"></p:inputText>
</h:panelGrid>
<p:commandButton value="Register" action="#{registrationManagedBean.register}" ajax="false"/>
<p:separator/>
<h:panelGrid columns="1" width="100%">
<p:dataTable value="#{registrationManagedBean.employees}" var="employee" style="width:100%">
<p:column headerText="Employee’s Name">
<h:outputText value="#{employee.employeeName}"/>
</p:column>
<p:column headerText="Employee’s Country">
<h:outputText value="#{employee.address.addressCountry}"/>
</p:column>
<p:column headerText="Employee’s City">
<h:outputText value="#{employee.address.addressCity}"/>
</p:column>
</p:dataTable>
<h:panelGrid columns="4" width="100%">
<p:commandButton value="Next Employees" action="#{registrationManagedBean.nextEmployees}" ajax="false"/>
<p:commandButton value="Previous Employees" action="#{registrationManagedBean.previousEmployees}" ajax="false"/>
<p:commandButton value="Sort By Employee Name" action="#{registrationManagedBean.sortByEmployeeName}" ajax="false"/>
<p:commandButton value="Sort By Employee Id" action="#{registrationManagedBean.sortByEmployeeId}" ajax="false"/>
</h:panelGrid>
</h:panelGrid>
</div>
</h:form>
</f:view>
</html>
[/code]

9. Web Deployment Descriptor

It’s the deployment descriptor for this sample application.

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>
<description>State saving method: ‘client’ or ‘server’
(=default). See JSF Specification 2.5.2
</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
<context-param>
<param-name>javax.faces.application.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config/*.xml</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
</web-app>
[/code]

10. Maven Build File

This is maven build file used for building this application.

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-Primefaces-SpringData-PagingAndSortingRepository-MySQL</artifactId>
<packaging>war</packaging>
<version>1.0</version>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.7</java.version>
<junit.version>4.9</junit.version>
<slf4j.version>1.6.4</slf4j.version>
<logback.version>1.0.1</logback.version>
<log4j.version>1.2.14</log4j.version>

<servlet.version>2.5</servlet.version>
<jsp.version>2.1</jsp.version>
<jstl.version>1.2</jstl.version>
<taglibs-standard.version>1.1.2</taglibs-standard.version>

<maven.compiler.plugin>2.3.2</maven.compiler.plugin>
<maven.failsafe.plugin>2.4.3-alpha-1</maven.failsafe.plugin>

</properties>

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

<repositories>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>

<dependencies>
<!– Servlet –>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<!– Faces Implementation –>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.4</version>
</dependency>
<!– Faces Library –>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.4</version>
</dependency>
<!– Primefaces Version 5 –>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>5.0.RC2</version>
</dependency>
<!– JSP Library –>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<!– JSTL Library –>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<!– Spring Core –>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<!– Spring Web –>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<!– Google List Library –>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>r09</version>
</dependency>
<!– 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>
<!– Spring Data Dependency –>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.5.2.RELEASE</version>
</dependency> <!– Dependency for MySql Java connector –>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
</dependencies>

</project>
[/code]

11. PagingAndSortingRepository Demo

The scenario implemented here contains of set of employees that could be paginated. For every single page the total amount of employees that shown inside is three. The user has the ability to add employees, see the next page, see the previous page and sorting by employee name and employee Id.

PagingAndSortingRepository - The Initial View
PagingAndSortingRepository - The Next Employees
PagingAndSortingRepository - Sorting By Employee Id

12. Summary

You’ve just developed a Spring Data application using PagingAndSortingRepository. That repository provides you a pagination feature for your data. If you have any questions. please write it in the comments section.

Download Source Code

[wpdm_file id=108]

Filed Under: Spring Framework Tagged With: MySQL, PrimeFaces, Spring Data, Spring Repository

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&amp;lt;Message,Integer&amp;gt; {}
[/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"]
&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;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"&amp;gt;
	&amp;lt;!-- Search for spring components --&amp;gt;
	&amp;lt;context:component-scan base-package="net.javabeat"&amp;gt;&amp;lt;/context:component-scan&amp;gt;
	&amp;lt;!-- Declare GemFire Cache --&amp;gt;
	&amp;lt;gfe:cache/&amp;gt;
	&amp;lt;!-- Local region for being used by the Message --&amp;gt;
	&amp;lt;gfe:local-region id="messages" value-constraint="net.javabeat.springdata.data.Message"/&amp;gt;
	&amp;lt;!-- Search for GemFire repositories --&amp;gt;
	&amp;lt;gfe-data:repositories base-package="net.javabeat.springdata.repo"/&amp;gt;
&amp;lt;/beans&amp;gt;
[/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"]
&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;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"&amp;gt;
	&amp;lt;context-param&amp;gt;
		&amp;lt;param-name&amp;gt;contextConfigLocation&amp;lt;/param-name&amp;gt;
		&amp;lt;param-value&amp;gt;/WEB-INF/spring-config/SpringContext.xml&amp;lt;/param-value&amp;gt;
	&amp;lt;/context-param&amp;gt;
	&amp;lt;servlet&amp;gt;
		&amp;lt;servlet-name&amp;gt;rest&amp;lt;/servlet-name&amp;gt;
		&amp;lt;servlet-class&amp;gt;org.springframework.data.rest.webmvc.RepositoryRestDispatcherServlet&amp;lt;/servlet-class&amp;gt;
	&amp;lt;/servlet&amp;gt;
	&amp;lt;servlet-mapping&amp;gt;
		&amp;lt;servlet-name&amp;gt;rest&amp;lt;/servlet-name&amp;gt;
		&amp;lt;url-pattern&amp;gt;/rest/*&amp;lt;/url-pattern&amp;gt;
	&amp;lt;/servlet-mapping&amp;gt;
	&amp;lt;listener&amp;gt;
		&amp;lt;listener-class&amp;gt;org.springframework.web.context.ContextLoaderListener&amp;lt;/listener-class&amp;gt;
	&amp;lt;/listener&amp;gt;
&amp;lt;/web-app&amp;gt;
[/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 &amp;lt; messages.length;i++){
				var index = i + 1;
				placeHolder.innerHTML += "Message # "+index+" :: " + messages[i].message + " :: &amp;lt;a href='"+messages[i]._links.self.href+"'&amp;gt;Message Link&amp;lt;/a&amp;gt;&amp;lt;br&amp;gt;";
			}
        });
    }
});
[/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"]
&amp;lt;!doctype html&amp;gt;
&amp;lt;html&amp;gt;
    &amp;lt;head&amp;gt;
		&amp;lt;title&amp;gt;JavaBeat Tutorials&amp;lt;/title&amp;gt;
        &amp;lt;script data-curl-run="boot.js" src="bower_components/curl/src/curl.js"&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;/head&amp;gt;
    &amp;lt;body&amp;gt;
        &amp;lt;div&amp;gt;
			&amp;lt;h2&amp;gt;JavaBeat Tutorial !&amp;lt;/h2&amp;gt;
			&amp;lt;h3&amp;gt;Spring Data REST - GemFire - Rest.js Demo&amp;lt;/h3&amp;gt;
            &amp;lt;p data-name="placeHolder"&amp;gt;

			&amp;lt;/p&amp;gt;
        &amp;lt;/div&amp;gt;
    &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
[/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&lt;Message,Integer&gt; {}
[/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”]
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;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"&gt;
&lt;!– Search for spring components –&gt;
&lt;context:component-scan base-package="net.javabeat"&gt;&lt;/context:component-scan&gt;
&lt;!– Declare GemFire Cache –&gt;
&lt;gfe:cache/&gt;
&lt;!– Local region for being used by the Message –&gt;
&lt;gfe:local-region id="messages" value-constraint="net.javabeat.springdata.data.Message"/&gt;
&lt;!– Search for GemFire repositories –&gt;
&lt;gfe-data:repositories base-package="net.javabeat.springdata.repo"/&gt;
&lt;/beans&gt;
[/code]

7. Maven Build

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

pom.xml

[code lang=”xml”]
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;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"&gt;
&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

&lt;groupId&gt;net.javabeat.springdata&lt;/groupId&gt;
&lt;artifactId&gt;SpringData-GemFire-REST&lt;/artifactId&gt;
&lt;version&gt;1.0&lt;/version&gt;
&lt;packaging&gt;war&lt;/packaging&gt;

&lt;name&gt;Spring Data&lt;/name&gt;

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

&lt;/dependencies&gt;

&lt;build&gt;
&lt;plugins&gt;
&lt;plugin&gt;
&lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
&lt;version&gt;2.3.2&lt;/version&gt;
&lt;/plugin&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
&lt;/plugin&gt;
&lt;/plugins&gt;
&lt;/build&gt;

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

&lt;pluginRepositories&gt;
&lt;pluginRepository&gt;
&lt;id&gt;spring-snapshots&lt;/id&gt;
&lt;name&gt;Spring Snapshots&lt;/name&gt;
&lt;url&gt;http://repo.spring.io/libs-snapshot&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;true&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/pluginRepository&gt;
&lt;/pluginRepositories&gt;
&lt;/project&gt;
[/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”]
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;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"&gt;
&lt;context-param&gt;
&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
&lt;param-value&gt;/WEB-INF/spring-config/SpringContext.xml&lt;/param-value&gt;
&lt;/context-param&gt;
&lt;servlet&gt;
&lt;servlet-name&gt;rest&lt;/servlet-name&gt;
&lt;servlet-class&gt;org.springframework.data.rest.webmvc.RepositoryRestDispatcherServlet&lt;/servlet-class&gt;
&lt;/servlet&gt;
&lt;servlet-mapping&gt;
&lt;servlet-name&gt;rest&lt;/servlet-name&gt;
&lt;url-pattern&gt;/rest/*&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;listener&gt;
&lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
&lt;/listener&gt;
&lt;/web-app&gt;
[/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”]
&lt;html ng-app&gt;
&lt;head&gt;
&lt;title&gt;JavaBeat Tutorial&lt;/title&gt;
&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"&gt;&lt;/script&gt;
&lt;script src="messages.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div style="width:50%"&gt;
&lt;h2&gt;JavaBeat Tutorial&lt;/h2&gt;
&lt;h2&gt;GemFire + REST + AngularJS&lt;/h2&gt;
&lt;div ng-controller="fetch"&gt;
&lt;h2&gt;full json response:&lt;/h2&gt;
&lt;p&gt;{{messages}}&lt;/p&gt;
&lt;h2&gt;Messages:&lt;/h2&gt;
&lt;ul ng-repeat="message in messages"&gt;
&lt;p&gt;Message:&lt;/p&gt;
&lt;p&gt;{{message.message}}&lt;/p&gt;
&lt;a href='{{message["_links"]["self"]["href"]}}’&gt;Go To Page Addressed Message : {{message._links.self.href}}&lt;/a&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
[/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

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&lt;Message,Integer&gt; {}
[/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”]
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;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"&gt;
&lt;!– Search for spring components –&gt;
&lt;context:component-scan base-package="net.javabeat"&gt;&lt;/context:component-scan&gt;
&lt;!– Declare GemFire Cache –&gt;
&lt;gfe:cache/&gt;
&lt;!– Local region for being used by the Message –&gt;
&lt;gfe:local-region id="messages" value-constraint="net.javabeat.springdata.data.Message"/&gt;
&lt;!– Search for GemFire repositories –&gt;
&lt;gfe-data:repositories base-package="net.javabeat.springdata.repo"/&gt;
&lt;/beans&gt;
[/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”]
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;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"&gt;
&lt;context-param&gt;
&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
&lt;param-value&gt;/WEB-INF/spring-config/SpringContext.xml&lt;/param-value&gt;
&lt;/context-param&gt;
&lt;servlet&gt;
&lt;servlet-name&gt;rest&lt;/servlet-name&gt;
&lt;servlet-class&gt;org.springframework.data.rest.webmvc.RepositoryRestDispatcherServlet&lt;/servlet-class&gt;
&lt;/servlet&gt;
&lt;servlet-mapping&gt;
&lt;servlet-name&gt;rest&lt;/servlet-name&gt;
&lt;url-pattern&gt;/rest/*&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;listener&gt;
&lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
&lt;/listener&gt;
&lt;/web-app&gt;
[/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”]
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;JavaBeat Tutorial&lt;/title&gt;
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"&gt;&lt;/script&gt;
&lt;script src="messages.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div style="width:50%"&gt;
&lt;h2&gt;JavaBeat Tutorial&lt;/h2&gt;
&lt;h2&gt;GemFire + REST + JQuery&lt;/h2&gt;
&lt;div id="messages"&gt;

&lt;/div&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
[/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 :: &lt;a href=’"+messages[0]._links.self.href+"’&gt;Link&lt;/a&gt;" + ‘&lt;br&gt;’ +
"Message #2 :: Message Content :: " + messages[1].message + " :: Message Link :: &lt;a href=’"+messages[1]._links.self.href+"’&gt;Link&lt;/a&gt;");
});
});
[/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

  • 1
  • 2
  • 3
  • …
  • 15
  • Next Page »

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