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

Caching Data using Spring Data GemFire

May 24, 2014 by Amr Mohammed Leave a Comment

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

Also read:

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

1. Business Scenario

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

MoneyRSS.java

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

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

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

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

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

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

private String code;
private String name;

public String getCode() {
return code;
}

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

public String getName() {
return name;
}

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

}
}
[/code]

2. Spring Bean Configurations

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

SpringContext.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:gfe-data="http://www.springframework.org/schema/data/gemfire"
xmlns:gfe="http://www.springframework.org/schema/gemfire"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/data/gemfire http://www.springframework.org/schema/data/gemfire/spring-data-gemfire.xsd http://www.springframework.org/schema/gemfire http://www.springframework.org/schema/gemfire/spring-gemfire.xsd">
<!– Search for spring components –>
<context:component-scan base-package="net.javabeat"></context:component-scan>
<!– Declare GemFire Cache –>
<gfe:cache/>
<!– Local region for being used by the Message –>
<gfe:local-region id="moneyRss"/>
<!– It’s mandatory for enabling the Cache –>
<bean id="cacheManager" class="org.springframework.data.gemfire.support.GemfireCacheManager" p:cache-ref="gemfireCache"/>
<!– Dummy Bean for EnableCaching –>
<bean id="enableCachingBean" class="net.javabeat.springdata.executable.Executable"></bean>
</beans>
[/code]

3. Maven Build File

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

pom.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>net.javabeat.springdata</groupId>
<artifactId>SpringData-GemFire-Cache</artifactId>
<version>1.0</version>
<packaging>jar</packaging>

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

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

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

</dependencies>

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

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

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

</project>
[/code]

4. Spring Data GemFire Example Application

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

Executable.java

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

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

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

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

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

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

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

5. GemFire Cache Demo

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

[code lang=”xml”]

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

6. Summary

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

Download Source Code

[wpdm_file id=103]

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

Accessing Data with Spring Data GemFire

May 23, 2014 by Amr Mohammed Leave a Comment

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

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

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

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

Also read:

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

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

1. Region

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

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

2. Java Beans (Business Domain)

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

Message.java

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

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

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

public Message() {
}

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

public String getMessageId() {
return messageId;
}

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

public String getMessage() {
return message;
}

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

3. GemFire Repository

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

MessageReposirory.java

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

import net.javabeat.springdata.data.Message;

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

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

}
[/code]

4. Spring Bean Definition

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

SpringContxt.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:gfe-data="http://www.springframework.org/schema/data/gemfire"
xmlns:gfe="http://www.springframework.org/schema/gemfire"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/data/gemfire http://www.springframework.org/schema/data/gemfire/spring-data-gemfire.xsd http://www.springframework.org/schema/gemfire http://www.springframework.org/schema/gemfire/spring-gemfire.xsd">
<!– Search for spring components –>
<context:component-scan base-package="net.javabeat"></context:component-scan>
<!– Declare GemFire Cache –>
<gfe:cache/>
<!– Local region for being used by the Message –>
<gfe:local-region id="messages" value-constraint="net.javabeat.springdata.data.Message"/>
<!– Search for GemFire repositories –>
<gfe-data:repositories base-package="net.javabeat.springdata.repo"/>
</beans>
[/code]

5. Spring Data + GemFire Example Application

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

Executable.java

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

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

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

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

import com.google.common.collect.Lists;

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

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

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

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

6. GemFire Maven Dependencies

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

pom.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

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

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

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

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

</dependencies>

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

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

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

</project>
[/code]

7. Accessing Data By GemFire Demo

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

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

8. Summary

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

Download Source Code

[wpdm_file id=102]

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

PrimeFaces + Spring Roo + Spring Data + MongoDB Integration Example

May 22, 2014 by Amr Mohammed Leave a Comment

This tutorial will introduce the integration of Primefaces, Spring Data & MongoDB frameworks. This tutorial assumes the you are familiar with the Spring Roo for creating the spring applications. Also, I assume that you are familiar with the Mongo DB. If you’re not, it’s good for you to go back into the below tutorials for getting the all of mentioned important principles. By the way, all of the required steps for creating a project and configure it for using Roo Shell are also covered inside this tutorial.

Note : This tutorial focuses only on creating the project using Spring Roo. we will not explain the code snippets since everything managed by Spring Roo.

Also read:

  • Spring Roo + Spring Data + MongoDB
  • Spring Data + MongoDB 

1. Tools Used

  • JDK 1.6.
  • Spring Roo 1.2.4. (It’s required for compatibility)
  • Maven 3.
  • Tomcat 7.35.
  • MongoDB.

2. Database Model

Here is the MongoDB collections that is used for persisting the documents used in this tutorial.

Address Document Collection Structure

Employee Document Collection Structure

3. Setup Mongo Persistence Layer

By executing mongo setup –databaseName JavaBeat –host 192.168.1.100 –port 27017 instruction, the persistence layer will be added and configured to your project.

Setting of Mongo Persistence

4. Creating Entities

For creating the required entities, you should follow the below steps:

  • By executing the entity mongo –class ~.roo.data.Address –identifierType java.math.BigInteger instruction, an Address entity has been created.
  • Add the addressCountry field by executing field string –fieldName addressCountry –notNull instruction.
  • Add the addressCity field by executing field string –fieldName addressCity –notNull instruction.
  • By executing the entity mongo –class ~.roo.data.Employee –identifierType java.math.BigInteger instruction, an Employee entity has been created.
  • Add the employeeName by executing field string –fieldName employeeName –notNull instruction.
  • Add the address reference into Employee entity by executing field reference –fieldName address –type ~.roo.data.Address –notNull instruction.

Creating Mongo Entities

5. Create Spring Data Repository

Spring Data Repository setup for MongoDB doesn’t differ from what’s happening in the Spring Roo & JPA. Here you just use a mongo keyword.

For creating Spring Data Repository, you have to execute the following commands:

  • For creating Employee Repository execute repository mongo –interface ~.roo.repo.EmployeeRepository –entity ~.roo.data.Employee
  • For creating Address Repository execute repository mongo –interface ~.roo.repo.AddressRepository –entity ~.roo.data.Address

Mongo Repositories

6. Setup PrimeFaces Web Layer

The creating of web layer using JSF/Primefaces is identical to what you’ve achieved before in a previous tutorials. The different here, is that, we would create a Primefaces layer rather using of Spring MVC. By executing web jsf setup –implementation ORACLE_MOJARRA –library PRIMEFACES –theme EGGPLANT instruction, you’ve requested from Spring Roo to setup the required configuration files as well as the theme that would be used.

Setup Primefaces Configuration

7. Create Managed Beans

For creating managed beans inside Spring Roo, all what you have to do is to execute the web jsf all –package ~.roo.web instruction.

Primefaces Managed Beans Created

Once, you’ve done creating the web application, you need to comment the Spring OpenEntityManagerInViewFilter and its filter mapping. That change is required to be able to running the application.

8. Build WAR using Maven

Navigate into your project directory using Windows command and execute the mvn clean package for generating the required WAR.

Mongo Primefaces Artifact Generation

9. Install the Application Into Tomcat 7

Now, just copy the .war generated file into your Tomcat7 directory’s webapp folder and start your tomcat using the startup.bat.

War Inside Tomcat 7 Webapp

10. Spring Roo + Spring Data + PrimFaces + MongoDB Demo

MongoDB Primefaces Home

MongoDB All Addresses

MongoDB All Employees

MongoDB Add Employee

MongoDB Added Employee Successfully

11. MongoDB Documents

MongoDB Address Document

MongoDB Employee Documents

12. Summary

You’ve just developed a PrimeFaces web application that adhered the Spring Data repositories using Spring Roo. Your application is capable of persisting against MongoDB. If you have any questions, please write it in the comments section

Download Source Code

[wpdm_file id=105]

Filed Under: Spring Framework Tagged With: MongoDB, PrimeFaces, Spring Data Mongo, Spring ROO

PrimeFaces + Spring Roo + Spring Data JPA Integration Example

May 21, 2014 by Amr Mohammed Leave a Comment

This tutorial presents how to develop a web application using PrimeFaces using Spring ROO and Spring Data JPA. In our previous tutorials we have explained each topic with more examples. Spring ROO is the rapid application development tool for the spring applications. It improves the productivity of software development.

To Getting started this tutorial, be sure that you are familiar with the Spring Roo, how to install Roo command shell and installing Roo plugin into Eclipse IDE. If you’re not, you can refer into one or more of the published tutorials below.

Also read:

    • Spring Roo + Spring Data JPA Repositories + Eclipse Integration
    • Spring Roo + Spring Data + MongoDB Integeration

1.Tools Required

The following tools are used for completing this tutorial. Before start working on this tutorial, lets install all the softwares mentioned in the below list.

  • JDK 1.7.
  • Maven 3.2.1.
  • Spring Roo 1.2.5.
  • Eclipse IDE Kepler 4.3.
  • MySQL 5.
  • Tomcat 8.

2. Database Model

It’s just database tables, that created into MySQL and it will be used for persisting the data that the example application should use.

Employee Table

Employee Foreign Key

Address Table

3. Creating Spring Roo Project & Prepare Roo Shell

It’s the required steps for creating a Spring Roo project inside Eclipse IDE. After creating the Spring Roo project, Spring Roo instructions will be executed from there. So, follow the below steps:

  • Open Eclipse IDE.
  • Right-Click on the project explorer -> New -> Other -> select Spring Roo Project.

Select Spring Roo Project

  • Click Next.
  • Type inside Project name the name you want. For us, we use SpringRoo-SpringData-Primefaces.
  • Type inside the Top level package name the package hierarchy you want. For us we use net.javabeat.
  • From Roo Installation, be sure that you’re using the installed Roo 1.2.5.
  • From Package Provider, select the WAR.

Fill Roo Project Required Info

  • Click Next & Finish.
  • Wait for being Roo command shell ready for use.
  • If you’ve got message likewise Please stand by until the Roo Shell is completely loaded. You can avoid it by restarting the Eclipse IDE.
  • Inside your Roo Shell area inside Eclipse you must see Open Roo Shell for projects. Just click on it.
  • Select your Roo project that you want the Roo commands to be executed against it. For our case, select the same name of the created project. Click Okay.
  • Roo shell must be opened and get ready for use.

Roo Shell Ready For Use

  • The Roo project has been created and the Spring Roo shell is ready.
  • The same project can be created through Roo shell by executing the project –topLevelPackage net.javabeat –projectName SpringRoo-SpringData-Primefaces –java 6 –packaging WAR

Project Directory

4. Creating Entities

Once project structure is created using the Spring Roo command shell or Eclipse, here is the required instructions that will be executed for creating the persistence entities . Once the Roo shell be ready for accepting your commands, you’ll start creating the persistence layer.

  • Executing of persistence setup –database MYSQL –provider ECLIPSELINK –hostName localhost –userName root –password root –databaseName javabeat will create the required persistence configuration for you.

Project Directory - Persistence Layer Configured

Preparing the persistence layer is necessary for getting started creating the required entities (business domain). For simplicity, we’ve provided only two entities; an Employee and Address are associated each together through a one to one relationship. So, let’s start creating the Address.

  • Execute entity jpa –class ~.roo.data.Address
  • Add addressId by executing field number –fieldName addressId –type java.lang.Integer –notNull 
  • Add addressCountry by executing field string –fieldName addressCountry –notNull 
  • Add addressCity by executing field string –fieldName addressCity –notNull 

Project Directory - Address Entity Created

Now, let’s creating the Employee.

  • Execute entity jpa –class ~.roo.data.Employee
  • Add employeeId by executing field number –fieldName employeeId –type java.lang.Integer –notNull 
  • Add employeeName by executing field string –fieldName employeeName –notNull 
  • Add address association member by executing field reference –type ~.roo.data.Address –fieldName address –notNull –cardinality ONE_TO_ONE

Project Directory - Employee Entity Created

You are ready with the entities class in your Spring Roo project.

5. Creating Spring Data Repository

Here is the required instructions that needs to be executed for creating the Spring Repositories that used for handling the CRUD operations against defined entities. For creating your repositories, you have to execute the following instructions.

  • Creating EmployeeRepository will be done through using of repository jpa –interface ~.roo.repo.EmployeeRepository –entity ~.roo.data.Employee instruction.
  • Creating AddressRepository will be done through using of repository jpa –interface ~.roo.repo.AddressRepository –entity ~.roo.data.Address instruction.

Project Directory - Repositories Created

6. Creating Primefaces / Web Layer

In the above steps, we have created the persistence entities using the Spring Roo commands, now the next task would be to create the web application. Here is the required instructions that will be used for creating the presentation layer using PrimeFaces and its JSF managed beans.

  • Setup the web layer by executing web jsf setup –implementation ORACLE_MOJARRA –library PRIMEFACES –theme EGGPLANT , by running this command, all artifacts that needed for configuring a web will be added in addition to all of those libraries that needed for configuring the PrimeFaces. That is awesome work from SpringRoo.
  • Creating your managed beans should be done through executing of web jsf all –package ~.roo.web

Project Directory - Primefaces-JSF Web Layer Added

7. Build the Application Using Maven

Now its time to build the the application using installed Maven. Navigate into your project using windows command and execute mvn clean package for getting a deployable WAR file. You can control the name of the generated WAR by changing the name of the artifact inside the pom.xml.

Package WAR By Maven

The WAR file it will be generated and located under target folder. Copy it from there and put it inside the your Apache Tomcat webapps folder and start your Apache Tomcat instance.

WAR Packaged

8. Spring Roo + Spring Data + PrimeFaces Application

Primefaces Deployable App - List Address Primefaces Deployable App - List EmployeesPrimefaces Deployable App - Create Employee

One major point for this example we’ve left the <property name=”eclipselink.ddl-generation” value=”drop-and-create-tables”/> as is, in order to allow the persistence layer dropping tables and re-generate them accordingly to those defined entities.

9. Database Record

Primefaces Application - Database Records

Primefaces Application - Database Record - After Additonal Insertion

10. Summary

You’ve just developed a Spring Roo application that combine the integration with the Spring Data repositories and PrimeFaces. It is awesome that Spring Roo does everything for you. If you have any questions, please write it in the comments section.

Download Source Code

[wpdm_file id=104]

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

PrimeFaces 5 + Spring Data + MySQL Integration

May 20, 2014 by Amr Mohammed Leave a Comment

This tutorial guides you through creating a web application that integrates between PrimeFaces 5, Spring Data and MySQL database. It’s important for you to learn the basics of the technologies PrimeFaces and Spring Data before start reading this tutorial.

Also read:

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

 

1. Tools Required

It’s the required tools for being able to develop this tutorial:

  • JDK 1.6+.
  • Tomcat 7+.
  • Spring 3.
  • Primefaces 5.
  • MySQL 5.

2. Java Beans (Business Domain)

Beans Address and Employees will be used as the entities for 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]

3. Persistence Context

Here is the required persistence configuration, which contains the targeted database schema and its credential details and any additional configuration required like logging level and etc. Also this persistence configuration declare the above listed beans as the persistence entities.

persistence.xml

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

4. Spring Data Repositories

Here is the spring data repository for each of the above entities. If you are familiar with the spring data repositories, these are just an abstract behaviour where the real implementation would be provided by the spring container at run time. It is the greatest advantage of using the spring data.

AddressRepository.java

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

import net.javabeat.springdata.jpa.data.Address;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface AddressRepository extends CrudRepository<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.CrudRepository;
import org.springframework.stereotype.Repository;

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

5. Spring Service

It’s just a spring bean that used for preventing the presentation layer talking directly with the repository. It’s just a type of orchestration that you would use. Spring bean will contain an instance of those defined repositories.

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. Spring Context Configurations

It’s the minimal amount of lines that should be updated in the spring context, from which the Spring Container could initialize the beans and any other environment information needed for the spring container.

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]

7. Primefaces / JSF Faces Configuration

It’s the faces configuration XML file, defines the managed beans and spring expression resolver.

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 / JSF Managed Bean

It’s the user defined managed bean that contain the business logic of the registration business scenario used in this tutorial.

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;

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.getEmployeeRepository().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;
}

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

9. Primefaces View

It’s the view that will be used for presenting the required primefaces UI components for Employee & Address registration business scenario.

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 + MySQL</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:commandButton value="Register" action="#{registrationManagedBean.register}" ajax="false"/>
<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]

10. Web Deployment Descriptor

It’s the required XML file that used by the Java EE container for understanding of the web application that will be getting deployed.

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]

11. PrimeFaces 5 + Spring Data + MySQL Demo

Primefaces Spring Data Registration View
Primefaces Spring Data Registered Employee

12. Database Records

Primefaces Registered Employees

13. Summary

Finally, we have  implemented a web application that uses the PrimeFaces 5, Spring Data & MySQL. If you have any questions, please write it in the comments section.

Download Source Code

[wpdm_file id=101]

Filed Under: Spring Framework Tagged With: MySQL, Primefaces 5, Spring Data, Spring JPA

Spring Data + MongoDB + REST Shell Integration

May 19, 2014 by Amr Mohammed Leave a Comment

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

Also read:

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

1. Tools Required

The required platforms and environments for this tutorial:

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

2. Java Beans (Entities)

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

Address.java

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

import javax.persistence.Id;

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

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

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

Employee.java

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

import javax.persistence.Id;

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

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

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

3. Spring Data Repositories

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

AddressRepository.java

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

import net.javabeat.springdata.data.Address;

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

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

EmployeeRepository.java

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

import net.javabeat.springdata.data.Employee;

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

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

4. Spring Context Configuration

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

SpringContext.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

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

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

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

</beans>
[/code]

5. Executable Application

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

Executable.java

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

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

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

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

6. Maven Dependencies

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

pom.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

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

<name>Spring Data</name>

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

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

<dependencies>

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

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

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

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

</project>

[/code]

7. Install REST Shell

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

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

Rest-Shell Starting Up

8. MongoDB + Spring Data Repository + Spring REST Demo

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

List all of collections inside MongoDB

Follow address - getting the address of id 1

Follow employee - getting the employee of id 1

Create Employee and Associate it with the already created Address entity

List of Addresses

List all employees

9. MongoDB Collections

Database address records

Database employee records

10. Accessing Through HTTP

HTTP employees list

11. Summary

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

Download Source Code

[wpdm_file id=100]

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

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

May 16, 2014 by Amr Mohammed Leave a Comment

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

Also read:

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

1. Java Beans

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

Address.java

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

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

@NodeEntity
public class Address{

@GraphId
private Long id;

private String addressCountry;

private String addressCity;

public Long getId() {
return id;
}

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

public String getAddressCountry() {
return addressCountry;
}

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

public String getAddressCity() {
return addressCity;
}

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

Employee.java

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

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

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

private String employeeName;

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

public Long getId() {
return id;
}

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

public String getEmployeeName() {
return employeeName;
}

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

public Address getAddress() {
return address;
}

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

2. Spring Data Neo4j Repositories

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

EmployeeRepository.java

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

import net.javabeat.springdata.data.Employee;

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

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

}
[/code]

AddressRepository.java

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

import net.javabeat.springdata.data.Address;

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

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

}

[/code]

3. Spring Controller

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

DataController.java

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

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

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

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class DataController {

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

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

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

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

4. Thymeleaf Templates

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

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

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

queryTemplate.html

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

resultTemplate.html

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

4. Executable Application

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

Executable.java

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

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

public Executable() {
}

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

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

5. Run the Service

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

Execute Spring Boot Application Using JAVA

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

6. Build WAR File

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

7. Initialize the Servlet

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

WebXML.java

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

import net.javabeat.springdata.executable.Executable;

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

public class WepXML extends SpringBootServletInitializer {

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

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

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

8. Run the WAR file

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

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

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

Download Source Code

[wpdm_package id=’23180′]

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

Spring Data Neo4j 3 REST Exporter (Java Application)

May 16, 2014 by Amr Mohammed Leave a Comment

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

Also read:

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

1. Install Eclipse Tomcat 8 Plugin

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

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

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

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

2. Java Beans

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

Address.java

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

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

@NodeEntity
public class Address{

@GraphId
private Long id;

private String addressCountry;

private String addressCity;

public Long getId() {
return id;
}

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

public String getAddressCountry() {
return addressCountry;
}

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

public String getAddressCity() {
return addressCity;
}

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

Employee.java

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

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

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

private String employeeName;

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

public Long getId() {
return id;
}

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

public String getEmployeeName() {
return employeeName;
}

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

public Address getAddress() {
return address;
}

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

3. Spring Data Repositories

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

EmployeeRepositories.java

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

import net.javabeat.springdata.data.Employee;

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

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

AddressRepositories.java

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

import net.javabeat.springdata.data.Address;

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

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

4. Executable Application

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

Executable.java

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

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

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

public Executable() {
}

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

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

5. Maven Dependencies

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

pom.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>next.javabeat.jsf</groupId>
<artifactId>JavaBeat-Neo4j-REST</artifactId>
<packaging>jar</packaging>
<version>1.0</version>

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

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

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

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

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

</project>
[/code]

6. Neo4j REST Demo

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

Neo4j REST

Neo4j-REST-ADDRESS

Neo4j-REST-EMPLOYEE

Download Source Code

[wpdm_package id=’23182′]

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

PrimeFaces + Spring Data + Neo4j Integration

May 15, 2014 by Amr Mohammed Leave a Comment

This tutorial provides example code for integrating PrimeFaces 5, Spring Data and Neo4j technologies.  In our previous tutorials, I have explained about the PrimeFaces and Spring Data integration with other databases MongoDB and Redis. Also read our previous tutorials on installation of Neo4j and Spring Data Neo4j tutorial.

I have used PrimeFaces 5 for this example. At the end of this article, download the source code for the demo. If you have any questions, please write it in the comments section.

Also read:

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

1. Java Beans

We have used Address and Employee entities in this example.

Address.java

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

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

@NodeEntity
public class Address{

@GraphId
private Long id;

private String addressCountry;

private String addressCity;

public Long getId() {
return id;
}

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

public String getAddressCountry() {
return addressCountry;
}

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

public String getAddressCity() {
return addressCity;
}

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

Employee.java

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

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

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

private String employeeName;

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

public Long getId() {
return id;
}

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

public String getEmployeeName() {
return employeeName;
}

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

public Address getAddress() {
return address;
}

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

2. Spring Configurations

Spring configuration will contains about the required beans, repositories and the Neo4j service.

SpringContext.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/data/neo4j http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

<context:component-scan base-package="net.javabeat.springdata.beans"></context:component-scan>

<bean id="graphDatabaseService" class="org.springframework.data.neo4j.rest.SpringRestGraphDatabase">
<constructor-arg value="http://localhost:7474/db/data/" />
</bean>

<neo4j:config graphDatabaseService="graphDatabaseService" base-package="net.javabeat.springdata.data"/>

<neo4j:repositories base-package="net.javabeat.springdata.repo" />
</beans>
[/code]

3.  Spring Data Neo4j Repository

For accessing the Neo4j, Spring Data provides the Spring Developer an API for doing that. Spring Data Neo4j allow the developer for accessing the Neo4j to achieve CRUD operations through a pre defined repositories. We have to just implement the repository, rest of the things will be handled by the spring container at run time.

EmployeeRepository.java

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

import net.javabeat.springdata.data.Employee;

import org.springframework.data.neo4j.repository.GraphRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EmployeeRepository extends GraphRepository<Employee>{}
[/code]

4. Spring Bean Service

It’s RegistrationService that already scanned by the Spring Container when the Spring context has initialized. It’s responsible for hosting instances for those defined in repositories.

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 repo;

public EmployeeRepository getRepo() {
return repo;
}

public void setRepo(EmployeeRepository repo) {
this.repo = repo;
}
}
[/code]

5. PrimeFaces / JSF Configurations

A non trivial configuration is required when it comes to inject a spring bean into faces managed bean, that’s done by adding a spring expression language resolver into faces-config.xml.

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]

6. PrimeFaces Managed Bean

RegsitrationManagedBean.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 com.google.common.collect.Lists;

import net.javabeat.springdata.beans.RegistrationService;
import net.javabeat.springdata.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() {
this.employees = Lists.newArrayList(this.service.getRepo().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;
}

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

7. Web Deployment Descriptor

It’s the deployment descriptor that contains the definition of the web application that is used by the Java EE container.

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]

8. Maven Dependencies

To defining the required dependencies for our example, we’ve used a Maven as a build and dependencies management tool. The pom.xml file will contain the required dependencies.

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

9. The PrimeFaces 5 View

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 + Neo4j</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:commandButton value="Register" action="#{registrationManagedBean.register}" ajax="false"/>
<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]

9. PrimeFaces 5 + Spring Data + Neo4j + Spring Web Demo

Neo4j + Spring Data + Primefaces Example 1

Neo4j + Spring Data + Primefaces Example 2

10. Persisted Neo4j Records

If you run the above example, you could see the records in the Neo4j database.

Neo4j + Spring Data + Primefaces Example 3

Neo4j + Spring Data + Primefaces Example 4

Download Source Code

[wpdm_file id=94]

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

java.lang.IncompatibleClassChangeError: class org.springframework.core.type.classreading.ClassMetadataReadingVisitor has interface org.springframework.asm.ClassVisitor as super class

May 15, 2014 by Amr Mohammed Leave a Comment

Why java.lang.IncompatibleClassChangeError Exception Thrown?

If you are working with Spring MVC and Spring Data Neo4j, then there is greater possibility that you would get the following exception when it comes to run the application using one of the Java EE container like Apache. I’ve used Apache Tomcat 7.35 for deploying a PrimeFaces 5 application with Spring MVC & Spring Neo4j using the following maven pom file. Note that, this exception could be thrown for some other frameworks as well.

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-Neo4j</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>
<!– SLF4J dependency –>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
<!– Neo4j support for Spring Data –>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j</artifactId>
<version>2.3.5.RELEASE</version>
</dependency>
<!– Advanced Mapping support for Spring Data Neo4j –>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j-aspects</artifactId>
<version>2.3.5.RELEASE</version>
</dependency>
<!– Neo4j transaction library –>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j-tx</artifactId>
<version>2.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j-rest</artifactId>
<version>2.3.5.RELEASE</version>
</dependency>
<!– Google List Library –>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>r09</version>
</dependency>
<!– Dependency for REST Exporter –>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
</dependencies>

</project>
[/code]

By deploying that application you will be getting an exception like the one below:

[code]
May 15, 2014 12:52:52 AM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.6.0_26\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files\Java\jdk1.6.0_26\jre\bin;org.C:\Program Files (x86)\Common Files\NetSarang;D:\QTEL\Work\Oraclexe\app\oracle\product\10.2.0\server\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x86;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64;D:\Maven\apache-maven-3.2.1\bin;D:\Ant\apache-ant-1.9.2\bin;jrockit_160_14_R27.6.5-32\bin;D:/php/php-5.5.8;D:\SpringRoo\spring-roo-1.2.5.RELEASE\bin;%HADOOP_PREFIX%\bin;C:\Python27;.
May 15, 2014 12:52:53 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property ‘source’ to ‘org.eclipse.jst.jee.server:JavaBeat-Primefaces-SpringData-Neo4j’ did not find a matching property.
May 15, 2014 12:52:53 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
May 15, 2014 12:52:53 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
May 15, 2014 12:52:53 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 832 ms
May 15, 2014 12:52:53 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
May 15, 2014 12:52:53 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.35
May 15, 2014 12:52:59 AM org.apache.catalina.core.StandardContext addApplicationListener
INFO: The listener "com.sun.faces.config.ConfigureListener" is already configured for this context. The duplicate definition has been ignored.
May 15, 2014 12:52:59 AM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
May 15, 2014 12:52:59 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
May 15, 2014 12:52:59 AM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: file [D:\Krishna\EclipseLink\Workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\JavaBeat-Primefaces-SpringData-Neo4j\WEB-INF\classes\net\javabeat\springdata\beans\RegistrationService.class]; nested exception is java.lang.IncompatibleClassChangeError: class org.springframework.core.type.classreading.ClassMetadataReadingVisitor has interface org.springframework.asm.ClassVisitor as super class
at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.findCandidateComponents(ClassPathScanningCandidateComponentProvider.java:301)
at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:242)
at org.springframework.context.annotation.ComponentScanBeanDefinitionParser.parse(ComponentScanBeanDefinitionParser.java:85)
at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:74)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1424)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1414)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:187)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:141)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:110)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:508)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:391)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:335)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:303)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:187)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:540)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:454)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:381)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:293)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4797)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5291)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.IncompatibleClassChangeError: class org.springframework.core.type.classreading.ClassMetadataReadingVisitor has interface org.springframework.asm.ClassVisitor as super class
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2904)
at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1173)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1681)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2904)
at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1173)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1681)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:63)
at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:82)
at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:102)
at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.findCandidateComponents(ClassPathScanningCandidateComponentProvider.java:277)
… 33 more
May 15, 2014 12:52:59 AM com.sun.faces.config.ConfigureListener contextInitialized
INFO: Initializing Mojarra 2.2.4 ( 20131003-1354 https://svn.java.net/svn/mojarra~svn/tags/2.2.4@12574) for context ‘/JavaBeat-Primefaces-Web’
May 15, 2014 12:53:00 AM com.sun.faces.spi.InjectionProviderFactory createInstance
INFO: JSF1048: PostConstruct/PreDestroy annotations present. ManagedBeans methods marked with these annotations will have said annotations processed.
May 15, 2014 12:53:01 AM org.primefaces.webapp.PostConstructApplicationEventListener processEvent
INFO: Running on PrimeFaces 5.0.RC2
May 15, 2014 12:53:01 AM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
May 15, 2014 12:53:01 AM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/JavaBeat-Primefaces-Web] startup failed due to previous errors
May 15, 2014 12:53:01 AM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
May 15, 2014 12:53:01 AM org.apache.catalina.core.StandardContext listenerStop
SEVERE: Exception sending context destroyed event to listener instance of class org.springframework.web.context.ContextLoaderListener
java.lang.IllegalStateException: BeanFactory not initialized or already closed – call ‘refresh’ before accessing beans via the ApplicationContext
at org.springframework.context.support.AbstractRefreshableApplicationContext.getBeanFactory(AbstractRefreshableApplicationContext.java:170)
at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:921)
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:841)
at org.springframework.web.context.ContextLoader.closeWebApplicationContext(ContextLoader.java:551)
at org.springframework.web.context.ContextLoaderListener.contextDestroyed(ContextLoaderListener.java:115)
at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4837)
at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5484)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:160)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
May 15, 2014 12:53:01 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
May 15, 2014 12:53:01 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
May 15, 2014 12:53:01 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 8241 ms
[/code]

If you’ve just noticed that exception which tells you that a class ClassMetadataReadingVisitor causing incompatibleClassChangeError. The reason is that, it doesn’t implements an interface in the Spring asm library.

Problem Resolution

For investigating the problem we need to use the dependency tree tool, in that the command mvn dependency:tree has been invoked against the above pom file which would display the below result:

[code]

D:\Krishna\EclipseLink\Workspace\JavaBeat-Primefaces-SpringData-Neo4j>mvn dependency:tree
Bad level value for property: .level
Bad level value for property: java.util.logging.ConsoleHandler.level
[INFO] Scanning for projects…
[INFO]
[INFO] Using the builder org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder with a thread count of 1
[INFO]
[INFO] ————————————————————————
[INFO] Building JavaBeat-Primefaces-SpringData-Neo4j 1.0
[INFO] ————————————————————————
[INFO]
[INFO] — maven-dependency-plugin:2.8:tree (default-cli) @ JavaBeat-Primefaces-SpringData-Neo4j —
[INFO] next.javabeat.jsf:JavaBeat-Primefaces-SpringData-Neo4j:war:1.0
[INFO] +- javax.servlet:servlet-api:jar:2.5:provided
[INFO] +- com.sun.faces:jsf-impl:jar:2.2.4:compile
[INFO] +- com.sun.faces:jsf-api:jar:2.2.4:compile
[INFO] +- org.primefaces:primefaces:jar:5.0.RC2:compile
[INFO] +- javax.servlet.jsp:javax.servlet.jsp-api:jar:2.3.1:compile
[INFO] +- javax.servlet:jstl:jar:1.1.2:compile
[INFO] +- org.slf4j:slf4j-log4j12:jar:1.6.1:compile
[INFO] | +- org.slf4j:slf4j-api:jar:1.6.1:compile
[INFO] | \- log4j:log4j:jar:1.2.16:compile
[INFO] +- org.springframework:spring-tx:jar:4.0.0.RELEASE:compile
[INFO] | +- aopalliance:aopalliance:jar:1.0:compile
[INFO] | \- org.springframework:spring-beans:jar:4.0.0.RELEASE:compile
[INFO] +- javax.validation:validation-api:jar:1.0.0.GA:compile
[INFO] +- org.springframework:spring-core:jar:4.0.0.RELEASE:compile
[INFO] | \- commons-logging:commons-logging:jar:1.1.1:compile
[INFO] +- org.springframework:spring-webmvc:jar:4.0.0.RELEASE:compile
[INFO] | +- org.springframework:spring-context:jar:4.0.0.RELEASE:compile
[INFO] | +- org.springframework:spring-expression:jar:4.0.0.RELEASE:compile
[INFO] | \- org.springframework:spring-web:jar:4.0.0.RELEASE:compile
[INFO] +- org.springframework.data:spring-data-neo4j:jar:2.3.5.RELEASE:compile
[INFO] | +- org.springframework:spring-aspects:jar:3.1.4.RELEASE:compile
[INFO] | | \- org.springframework:spring-context-support:jar:3.1.4.RELEASE:compile
[INFO] | +- org.aspectj:aspectjrt:jar:1.7.2:compile
[INFO] | +- org.springframework.data:spring-data-commons:jar:1.6.5.RELEASE:compile
[INFO] | +- org.neo4j:neo4j-cypher-dsl:jar:1.9:compile
[INFO] | +- org.neo4j:neo4j:jar:1.9.3:compile
[INFO] | | +- org.neo4j:neo4j-lucene-index:jar:1.9.3:compile
[INFO] | | | \- org.apache.lucene:lucene-core:jar:3.6.2:compile
[INFO] | | +- org.neo4j:neo4j-graph-algo:jar:1.9.3:compile
[INFO] | | +- org.neo4j:neo4j-udc:jar:1.9.3:compile
[INFO] | | +- org.neo4j:neo4j-graph-matching:jar:1.9.3:compile
[INFO] | | \- org.neo4j:neo4j-jmx:jar:1.9.3:compile
[INFO] | +- org.neo4j:neo4j-cypher:jar:1.9.3:compile
[INFO] | | +- org.scala-lang:scala-library:jar:2.10.0:compile
[INFO] | | \- com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:jar:1.3.1:compile
[INFO] | \- org.slf4j:jcl-over-slf4j:jar:1.7.1:runtime
[INFO] +- org.springframework.data:spring-data-neo4j-aspects:jar:2.3.5.RELEASE:compile
[INFO] | +- org.springframework:spring-aop:jar:3.1.4.RELEASE:compile
[INFO] | | \- org.springframework:spring-asm:jar:3.1.4.RELEASE:compile
[INFO] | +- org.neo4j:neo4j-kernel:jar:1.9.3:compile
[INFO] | | \- org.apache.geronimo.specs:geronimo-jta_1.1_spec:jar:1.1.1:compile
[INFO] | \- cglib:cglib:jar:2.2.2:compile
[INFO] | \- asm:asm:jar:3.3.1:compile
[INFO] +- org.springframework.data:spring-data-neo4j-tx:jar:2.3.5.RELEASE:compile
[INFO] +- org.springframework.data:spring-data-neo4j-rest:jar:2.3.5.RELEASE:compile
[INFO] | +- org.neo4j:neo4j-rest-graphdb:jar:1.9:compile
[INFO] | | \- org.neo4j:server-api:jar:1.9:compile
[INFO] | | +- org.neo4j.3rdparty.javax.ws.rs:jsr311-api:jar:1.1.2.r612:compile
[INFO] | | +- commons-configuration:commons-configuration:jar:1.6:compile
[INFO] | | | +- commons-collections:commons-collections:jar:3.2.1:compile
[INFO] | | | +- commons-lang:commons-lang:jar:2.4:compile
[INFO] | | | \- commons-beanutils:commons-beanutils-core:jar:1.8.0:compile
[INFO] | | \- commons-digester:commons-digester:jar:1.8.1:compile
[INFO] | | \- commons-beanutils:commons-beanutils:jar:1.8.0:compile
[INFO] | +- org.codehaus.jackson:jackson-jaxrs:jar:1.9.7:compile
[INFO] | | \- org.codehaus.jackson:jackson-core-asl:jar:1.9.7:compile
[INFO] | +- org.codehaus.jackson:jackson-mapper-asl:jar:1.9.7:compile
[INFO] | \- com.sun.jersey:jersey-client:jar:1.4:compile
[INFO] | \- com.sun.jersey:jersey-core:jar:1.4:compile
[INFO] +- com.google.guava:guava:jar:r09:compile
[INFO] \- org.springframework.data:spring-data-rest-webmvc:jar:2.0.2.RELEASE:compile
[INFO] +- org.springframework.data:spring-data-rest-core:jar:2.0.2.RELEASE:compile
[INFO] | +- org.springframework.hateoas:spring-hateoas:jar:0.9.0.RELEASE:compile
[INFO] | | \- org.objenesis:objenesis:jar:1.3:compile
[INFO] | +- org.springframework.plugin:spring-plugin-core:jar:1.0.0.RELEASE:compile
[INFO] | \- org.atteo:evo-inflector:jar:1.0.1:compile
[INFO] \- com.fasterxml.jackson.core:jackson-databind:jar:2.3.1:compile
[INFO] +- com.fasterxml.jackson.core:jackson-annotations:jar:2.3.0:compile
[INFO] \- com.fasterxml.jackson.core:jackson-core:jar:2.3.1:compile
[INFO] ————————————————————————
[INFO] BUILD SUCCESS
[INFO] ————————————————————————
[INFO] Total time: 1.794 s
[INFO] Finished at: 2014-05-15T00:56:09+02:00
[INFO] Final Memory: 40M/64M
[INFO] ————————————————————————
D:\Krishna\EclipseLink\Workspace\JavaBeat-Primefaces-SpringData-Neo4j>
[/code]

The Spring asm version that imported is org.springframework:spring-asm:jar:3.1.4.RELEASE:compile which consider older than required for spring core library. That is the main reason why this exception is thrown.

The library that caused that error is:

[code]
[INFO] +- org.springframework.data:spring-data-neo4j-aspects:jar:2.3.5.RELEASE:compile
[INFO] | +- org.springframework:spring-aop:jar:3.1.4.RELEASE:compile
[INFO] | | \- org.springframework:spring-asm:jar:3.1.4.RELEASE:compile
[/code]

So, let’s exclude the Spring asm from this dependency by using exclusions maven tag. By that the pom.xml file should look like

[code lang=”xml”]
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j-aspects</artifactId>
<version>2.3.5.RELEASE</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-asm</artifactId>
</exclusion>
</exclusions>
</dependency>
[/code]

By excluding the old spring-asm dependency the new asm 3.3.1  dependency should be imported automatically and your application should be running smoothly.

If you haven’t added any library in your application such as CGLIB that could contain the asm 3.3.1 you can add the following dependency for your pom.xml file.

[code lang=”xml”]
<!– Separate ASM Library –>
<dependency>
<groupId>asm</groupId>
<artifactId>asm-all</artifactId>
<version>3.3.1</version>
</dependency>
[/code]

Filed Under: Spring Framework Tagged With: Spring Exceptions

  • « Previous Page
  • 1
  • 2
  • 3
  • 4
  • …
  • 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