Aspect Oriented Programming – Advices

Aspect oriented Programming is a cross cutting concepts to OOP. AOP in Spring is used in replacement to EJB for it’s declarative programming style. in this tutorial we will look into different advices that AspectJ supports in Spring.

First of all an Advice is a functionality that we want to execute before or after some method is getting executed.
There are 4 types of Advices that Spring Supports.

  • BeforeAdvice : this advice is executed before every method call
  • AfterAdvice : this advice is executed after every method call. please note that this will not get executed if a method throws some exception
  • AfterThrowingAdvice : this advice is executed after every method throws some configured exceptions
  • AroundAdvice : this advice is executed before and after every method call

let us dive directly to code part as the above explanation is straight forward.
Step1: Let us look into POM.xml file

<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>com.spark.aop</groupId>
	<artifactId>AOPTutorial</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>AOPTutorial</name>
	<description>AOPTutorial</description>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.8.5</version>
		</dependency>
		<dependency>
			<groupId>aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.5.4</version>
		</dependency>
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>3.1</version>
		</dependency>
	</dependencies>

	<properties>
		<spring.version>4.1.8.RELEASE</spring.version>
	</properties>
</project>

Step2: let us look into our application-context.xml file, which acts as the spring configuration file.

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">

	<bean id="customerService" class="com.spark.aop.service.CustomerService">
		<property name="customerId" value="10"></property>
	</bean>

	<bean id="beforeAdvice" class="com.spark.aop.advice.BeforeAdvice" />
	<bean id="afterAdvice" class="com.spark.aop.advice.AfterAdvice" />
	<bean id="throwAdvice" class="com.spark.aop.advice.ThrowAdvice" />

	<bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">

		<property name="target" ref="customerService" />

		<property name="interceptorNames">
			<list>
				<value>beforeAdvice</value>
				<value>afterAdvice</value>
				<value>throwAdvice</value>
			</list>
		</property>
	</bean>
</beans>

now let us start writing the classes that were shown in the above configuration file.
Step3: write a class named BeforeAdvice.java which will implement MethodBeforeAdvice.java interface. this interface has before method which gets executed before every method call

package com.spark.aop.advice;

import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;

/**
 * @author Sony
 *
 */
public class BeforeAdvice implements MethodBeforeAdvice {
	public void before(Method method, Object[] args, Object target) throws Throwable {
		System.out.println("BeforeAdvice class : Before method !");
	}
}

Step4: Now let us write the service class as shown below, which has got some specific operations to be done.

/**
 * 
 */
package com.spark.aop.service;

/**
 * @author Sony
 *
 */
public class CustomerService {

	private int customerId;

	public int getCustomerId() {
		return customerId;
	}

	public void setCustomerId(int customerId) {
		this.customerId = customerId;
	}

	public void getCustomerById() {
		System.out.println("******* CustomerService*********"+customerId);
	}
	
	public void getException() throws IllegalArgumentException {
		 throw new IllegalArgumentException();
	}
}

Step5: finally let us code our main program through which we can start test our advice functionality.

package com.spark.aop.main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spark.aop.service.CustomerService;

public class App {
	public static void main(String[] args) {
		ApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] { "application-context.xml" });

		CustomerService cust = (CustomerService) appContext.getBean("customerServiceProxy");

		System.out.println("************Main Method*************");
		cust.getCustomerById();
		System.out.println("************Going to throw Exception*************");
		try {
			cust.getException();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		
	}
}

Misc : the code for AfterAdvice.java and ThrowAdvice.java are given below.

/**
 * 
 */
package com.spark.aop.advice;

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;

/**
 * @author Sony
 *
 */
public class AfterAdvice implements AfterReturningAdvice {

	public void afterReturning(Object object, Method method, Object[] objects, Object object2) throws Throwable {
		
		System.out.println("AfterAdvice class : After method !");
	}

}

/**
 * 
 */
package com.spark.aop.advice;

import org.springframework.aop.ThrowsAdvice;

/**
 * @author Sony
 *
 */
public class ThrowAdvice implements ThrowsAdvice{

	public void afterThrowing(IllegalArgumentException e) throws Throwable {
		System.out.println("ThrowAdvice class : Method Thrown exception !");
	}
}

That’s it guys we have finished coding advices in spring.
practical scenario : this kind of approach is very much useful while writing logging facility in projects.
please test the code on your own, and let me know if anything is needed.

Happy Advices πŸ™‚

Using SpringBoot , SpringData and MongoDB

Hello everybody, its a long gap that i have not written a post in my blog. This post could be my last post in 2015. today we are going to see how to integrate Spring’s one of the best feature Spring Boot with Spring data and MongoDB.

Spring Boot:(courtesy Spring.io) Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”. Most Spring Boot applications need very little Spring configuration.


Features:

  • Create stand-alone Spring applications
  • Embed Tomcat, Jetty
  • Automatically configure Spring whenever possible
  • Absolutely no code generation and no requirement for XML configuration

Now let us create a project that can integrate the above mentioned technology stack.
spring-boot-proj

Step 1: create the mongo-db.properties file in src/main/resources folder

MONGO_DB_HOST=127.0.0.1
MONGO_DB_PORT=27017
DB=school

Step 2: create the application configuration java class which is responsible for creating the MongoTemplate object. below is AppConfig.java

/**
 * 
 */
package com.spark.spring.practice.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;

/**
 * @author Sony
 *
 */
@Configuration
@PropertySource(value = "classpath:mongo-config.properties")
public class AppConfig {

	@Value("${MONGO_DB_HOST}")
	private String MONGO_DB_HOST;

	@Value("${MONGO_DB_PORT}")
	private int MONGO_DB_PORT;

	@Value("${DB}")
	private String DB;

	protected String getDatabaseName() {
		return DB;
	}

	@Bean
	public Mongo getMongo() throws Exception {
		return new MongoClient(MONGO_DB_HOST, MONGO_DB_PORT);
	}

	@Bean
	public MongoDbFactory mongoDbFactory() throws Exception {
		return new SimpleMongoDbFactory(getMongo(), getDatabaseName());
	}

	@Bean
	public MongoTemplate mongoTemplate() throws Exception {

		MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());

		return mongoTemplate;

	}
}

Step 3: create the pojo classes which are mapped as documents in mongodb. below are the Student.java and Score.java respectively

/**
 * 
 */
package com.spark.spring.practice.beans;

import java.util.List;

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

/**
 * @author Sony
 *
 */
@Document(collection = "students")
public class Student {

	@Id
	private int _id;
	@Field(value="name")
	private String name;
	@Field(value="scores")
	List<Score> scores;

	public int get_id() {
		return _id;
	}

	public void set_id(int _id) {
		this._id = _id;
	}

	public String getName() {
		return name;
	}

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

	public List<Score> getScores() {
		return scores;
	}

	public void setScores(List<Score> scores) {
		this.scores = scores;
	}

}

/**
 * 
 */
package com.spark.spring.practice.beans;

/**
 * @author Sony
 *
 */
public class Score {

	private String type;
	private double score;

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public double getScore() {
		return score;
	}

	public void setScore(double score) {
		this.score = score;
	}

}

Step 4: create the controller class which can handle the request coming from client. in this example the controller is called GlobalController.java. The controller class is autowired with MongoTemplate Object and StudentRepository, so let us create StudentRepository so that it will get injected into the controller, when the class loads to spring container. MongoTemplate is readily configured in the AppConfig.java file.

/**
 * 
 */
package com.spark.spring.practice.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.spark.spring.practice.beans.Student;
import com.spark.spring.practice.repositories.StudentRepository;

/**
 * @author Sony
 *
 */
@RestController
@RequestMapping(value = "/rest/v1/students")
public class GlobalController {
	
	Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private MongoTemplate mongoTemplate;
	
	@Autowired
	private StudentRepository studentRepository;

	@RequestMapping(value = "/findall", method = RequestMethod.GET)
	public List<Student> getAllStudents() {
		List<Student> students = studentRepository.findAll();
		return students;
	}
}

Step 5: create the repository interface which will extend the MongRepository<T,ID> interface from spring library.

/**
 * 
 */
package com.spark.spring.practice.repositories;

import org.springframework.data.mongodb.repository.MongoRepository;

import com.spark.spring.practice.beans.Student;

/**
 * @author Sony
 *
 */
public interface StudentRepository extends MongoRepository<Student, Integer> {

}

Step 6: create the main class which will act as booting mechanism and will start the project with the help of @SpringBootApplication & @EnableMongoRepositories annotations

/**
 * 
 */
package com.spark.spring.practice.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

/**
 * @author Sony
 *
 */
@SpringBootApplication
@ComponentScan(basePackages={"com.spark.spring.practice"})
@EnableMongoRepositories(basePackages={"com.spark.spring.practice"})
public class SpringBootMain {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		SpringApplication.run(SpringBootMain.class, args);
	}

}

that’s all guys we are done with coding part. Its time for us to run the project. once you ran the project with out errors then below is the kind of output that can be seen on console.
Spring-boot-console

now open the REST-client add-on either in chrome or firefox and test your services.
Happy Spring-booting πŸ™‚

Spring Data Rest + AngularJS + MongoDB

Hello everybody, this time i took little long time to post an article here. Here i came up with a very powerful integration pack called “Integration of Spring data rest with AngularJS and MongoDB”. Now a days this combination is best suited for SPA – “Single Page Application” with light weight back end support with mongodb. Now we will have a Jump start into the tutorial. this tutorial will assume the prior basic knowledge of

  • Java8
  • Spring & Spring Data Rest
  • MongoDB

the project structure looks as below.
SpringAngularJSProj

Before proceeding with the Spring integration with angularjs and mongodb, please install mongodb and start the mongodb server. if everything goes well server startup should look as below.
mongodb_server_start

Now install any GUI client for mongodb for easy access, we can even access mongodb with out client but this is for better user experience. I personally use “Robomongo” and once you connect Robomongo to MongoDB server that will look as below.
robomongo

Once everything is ready and inplace, let us start with writing the code. I have used Maven to manage the dependencies and hence the pom.xml looks as below.

<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>com.spark.ng.spring</groupId>
	<artifactId>AngularSpring</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>AngularSpring</name>
	<description>AngularSpring</description>

	<properties>
		<spring-version>4.1.2.RELEASE</spring-version>
		<jdk-version>1.8</jdk-version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring-version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring-version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring-version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring-version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring-version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-rest-core</artifactId>
			<version>2.3.0.RELEASE</version>
		</dependency>

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

		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-rest-webmvc</artifactId>
			<version>2.3.0.RELEASE</version>
		</dependency>

		<!-- mongodb java driver -->
		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
			<version>2.11.0</version>
		</dependency>
		
		<!-- Servlet 3.x api -->
		 <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>
        
	</dependencies>

	<build>
		<finalName>AngularSpring</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.4</version>
				<configuration>
					<warSourceDirectory>src/main/webapp</warSourceDirectory>
					<warName>AngularSpring</warName>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Once the dependencies are downloaded let us start with the configuration. In this tutorial i am moving with NoXml style of configuration.
ApplicationConfig.java

/**
 * 
 */
package com.spark.ng.spring.config;

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.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import com.mongodb.MongoClient;

/**
 * @author Mantha Pavan Kumar
 *
 */
@Configuration
@EnableWebMvc
@ComponentScan(basePackages={"com.spark.ng.spring"})
@EnableMongoRepositories(basePackages={"com.spark.ng.spring.data.repository"})
@Import(RepositoryRestMvcConfiguration.class)
public class ApplicationConfig {
	
	public @Bean
    MongoDbFactory mongoDbFactory() throws Exception {
		MongoClient mongoClient = new MongoClient("localhost",27017);
        return new SimpleMongoDbFactory(mongoClient, "Customer");
    }

    public @Bean
    MongoTemplate mongoTemplate() throws Exception {
        MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
        return mongoTemplate;
    }
    
	@Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".html");
 
        return viewResolver;
    }
}

WebApplicationConfig.java

/**
 * 
 */
package com.spark.ng.spring.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * @author Mantha Pavan Kumar
 *
 */
public class WebApplicationConfig implements WebApplicationInitializer{

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		
		AnnotationConfigWebApplicationContext annotationConfigWebApplicationContext = new AnnotationConfigWebApplicationContext();
		annotationConfigWebApplicationContext.register(ApplicationConfig.class);
		annotationConfigWebApplicationContext.setServletContext(servletContext);
		
		ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(annotationConfigWebApplicationContext));
		servlet.setLoadOnStartup(1);
		servlet.addMapping("/rest/*");
	}

}

With the above two files we are done with the configuration part. Let us talk about ApplicationConfig.java a little more in deep. At the top of the class please take a close look, i have annotated the class with “@EnableWebMvc”, which will enable all “@Component” based class and scans them when the application is loaded by the web container. The annotation “@EnableWebMvc” is equivalent to “”. Moving little forward “@ComponentScan” will scan all the @Component based classes. Now comes the “@EnableMongoRepositories” which will load all the repositories. Finally we have imported a core class from the Spring API called “RepositoryRestMvcConfiguration” this is the class responsible for converting the domain objects back and forth to JSON format and acts as a communication bridge between clint(browser) & backend. In this class we have innitialised two beans called “MongoDBFactory” & “MongoTemplate” since if we have any operation to do apart from Repository implementation then we can use of “MongoTemplate” object to fulfill that.

Let us have a look at the domain object Customer.java

/**
 * 
 */
package com.spark.ng.spring.domain.objects;

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


/**
 * @author PavanKumar Mantha
 *
 */
@Document(collection="customer")
public class Customer {

	@Id
	@Field
	private String id;
	@Field
	private String customerId;
	@Field
	private String firstName;
	@Field
	private String lastName;
	@Field
	private String contactAddr;
	@Field
	private String mobileNumber;
	

	/**
	 * @return the customerId
	 */
	public String getCustomerId() {
		return customerId;
	}

	/**
	 * @param customerId
	 *            the customerId to set
	 */
	public void setCustomerId(String customerId) {
		this.customerId = customerId;
	}

	/**
	 * @return the firstName
	 */
	public String getFirstName() {
		return firstName;
	}

	/**
	 * @param firstName
	 *            the firstName to set
	 */
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	/**
	 * @return the lastName
	 */
	public String getLastName() {
		return lastName;
	}

	/**
	 * @param lastName
	 *            the lastName to set
	 */
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	/**
	 * @return the contactAddr
	 */
	public String getContactAddr() {
		return contactAddr;
	}

	/**
	 * @param contactAddr
	 *            the contactAddr to set
	 */
	public void setContactAddr(String contactAddr) {
		this.contactAddr = contactAddr;
	}

	/**
	 * @return the mobileNumber
	 */
	public String getMobileNumber() {
		return mobileNumber;
	}

	/**
	 * @param mobileNumber
	 *            the mobileNumber to set
	 */
	public void setMobileNumber(String mobileNumber) {
		this.mobileNumber = mobileNumber;
	}

}

A generic Response object with which we can send messages back to browser.

/**
 * 
 */
package com.spark.ng.spring.domain.objects;

/**
 * @author Sony
 *
 */
public class ResponseObject {

	private String message;

	/**
	 * @return the message
	 */
	public String getMessage() {
		return message;
	}

	/**
	 * @param message
	 *            the message to set
	 */
	public void setMessage(String message) {
		this.message = message;
	}

}

The class “ApplicationRepositoryUtil.java will get us all the objects that are required using the @Autowired annotation.

/**
 * 
 */
package com.spark.ng.spring.data.repository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

/**
 * @author Sony
 *
 */
@Service
public class ApplicationRepositoryUtil {

	@Autowired
	private MongoTemplate mongoTemplate;
	@Autowired
	private CustomerRepository customerRepository;

	/**
	 * @return the mongoTemplate
	 */
	public MongoTemplate getMongoTemplate() {
		return mongoTemplate;
	}

	/**
	 * @return the customerRepository
	 */
	public CustomerRepository getCustomerRepository() {
		return customerRepository;
	}

}

Here comes the exact repository that we were talking from little while. Please observe the repository carefully. Its an interface extending one more interface called “MongoRepository”.The goal of Spring Data repository abstraction is to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores.The central interface in Spring Data repository abstraction is Repository (probably not that much of a surprise). It takes the domain class to manage as well as the id type of the domain class as type arguments. This interface acts primarily as a marker interface to capture the types to work with and to help you to discover interfaces that extend this one. The CrudRepository provides sophisticated CRUD functionality for the entity class that is being managed. MongoRepository extends the basic CrudRepository.

/**
 * 
 */
package com.spark.ng.spring.data.repository;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import com.spark.ng.spring.domain.objects.Customer;

/**
 * @author Sony
 *
 */
@RepositoryRestResource(collectionResourceRel="customer",path="customer")
public interface CustomerRepository extends MongoRepository<Customer, Integer> {

}

Here is a simple controller that will receive the requests from clients and delegates them to appropriate layers.

/**
 * 
 */
package com.spark.ng.spring.controller;

import java.util.function.Supplier;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.spark.ng.spring.data.repository.ApplicationRepositoryUtil;
import com.spark.ng.spring.domain.objects.ResponseObject;

/**
 * @author Sony
 *
 */
@RestController
@RequestMapping(value = "/app")
public class ApplicationController {

	@Autowired
	ApplicationRepositoryUtil applicationRepositoryUtil;

	@RequestMapping("/test")
	public ResponseObject handleRequest() {
		System.out
				.println("---------------------Testing method called---------------- Mongo Template :"
						+ applicationRepositoryUtil.getMongoTemplate()
						+ " Repository Object : "
						+ applicationRepositoryUtil.getCustomerRepository());
		Supplier<ResponseObject> supplier = ResponseObject::new;
		ResponseObject responseObject = supplier.get();

		responseObject.setMessage("Sample Data Object");
		return responseObject;

	}
}

Now we done with the java part and now its time for us to write the Html and java script. please download latest AngularJS library and include the “angular.min.js” inside your project, after including please write a file called “mongo.module.js” and out the following content into it.

/**
 * 
 */
var myApp = angular.module('myApp', ['controllers']);

Now write an AngularJs controller which is responsible for firing the Ajax request to the Spring and get the data in REST format. create a folder called “controllers” and create a file “controllers.js” and put the following content into it.

/**
 * 
 */

var controllersModule = angular.module('controllers', []);

controllersModule.controller('SampleController', function($scope) {
	console.log('Sample Load done !');
});

controllersModule.controller('ajaxController', function($scope, $http) {
	$http.get('/AngularSpring/rest/customer/').success(function(data) {
		console.log(data);
	});
});

Let us create an Html file “index.html” with the below content

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="ISO-8859-1">
<title>Index Page</title>
<script type="text/javascript" src="jsLib/angular.min.js"></script>
</head>
<body>
	<div ng-controller="SampleController">Hello AngularJs</div>
	<div ng-controller="ajaxController">Hello Spring Data Rest & MongoDB</div>

</body>
<script type="text/javascript" src="mongo.module.js"></script>
<script type="text/javascript" src="controllers/controllers.js"></script>
</html>

That is it guys we are done from coding part and its time for us to build the application and deploy it to server.
Once we deploy the application into the server, please install an Add on to firefox or chrome called “RESTClient” from which we can test our repositories are working or not.
RestClient

Once you fire the request as shown in the above screen shot, we should get the response from the service as below.
REST_Response

Now try to open our page “index.html” and in firebug console we could see the same response as above which means pur angularjs is firing the request and our Spring repositories are responding to the request.

index

Happy Spring Data REst + AngularJS + MongoDB πŸ™‚
Happy Coding πŸ™‚

Oracle Fusion Middleware – “How to Query Oracle Coherence” ?

In my previous post “Oracle Fusion Middleware – Concepts of Oracle Coherence” i have explained how to preLoad cache which means get all the required details for the first time and put that into cache. Today i am going to explain how to query the cache once we have the details.

Querying in Oracle Coherence is obtained by set of Filters that the Coherence has provided us. Please be noted that queries apply only to currently cached data thus, the data set should be loaded entirely into cache before queries are performed(go through my preLoading concept in the previous post).

The concept of querying is based on the ValueExtractor interface. A value extractor is used to extract an attribute from a given object for querying Most developers need only the ReflectionExtractor implementation of this interface. The implementation uses reflection to extract an attribute from a value object by referring to a method name which is typically a getter method

Let me show you the example which is connected to my previous post:

/**
 * 
 */
package com.spark.coherence.cache.filters;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.spark.coherence.cache.repository.CacheRepository;
import com.spark.coherence.pof.beans.EmployeeBean;
import com.tangosol.util.Filter;
import com.tangosol.util.ValueExtractor;
import com.tangosol.util.extractor.ReflectionExtractor;
import com.tangosol.util.filter.EqualsFilter;
import com.tangosol.util.filter.GreaterEqualsFilter;
import com.tangosol.util.filter.GreaterFilter;

/**
 * @author Sony
 *
 */
public class EmployeeFilter {

	ValueExtractor valueExtractor;

	@SuppressWarnings("rawtypes")
	public EmployeeBean equalsFilter(String methodName, String methodParam) {
		valueExtractor = new ReflectionExtractor(methodName);
		Filter filter = new EqualsFilter(valueExtractor, methodParam);
		EmployeeBean person = null;
		for (Iterator iter = CacheRepository.getEmployeeCache().entrySet(filter).iterator(); iter.hasNext();) {
			Map.Entry entry = (Map.Entry) iter.next();
			Integer key = (Integer) entry.getKey();
			person = (EmployeeBean) entry.getValue();
		}
		return person;
	}
	
	@SuppressWarnings("rawtypes")
	public List<EmployeeBean> greaterThanFilter(String methodName, int methodParam) {
		valueExtractor = new ReflectionExtractor(methodName);
		Filter filter = new GreaterEqualsFilter(valueExtractor, methodParam);
		List<EmployeeBean> employeeBeans = new ArrayList<>();
		for (Iterator iter = CacheRepository.getEmployeeCache().entrySet(filter).iterator(); iter.hasNext();) {
			Map.Entry entry = (Map.Entry) iter.next();
			Integer key = (Integer) entry.getKey();
			EmployeeBean person = (EmployeeBean) entry.getValue();
			employeeBeans.add(person);
		}
		return employeeBeans;
	}

}

Happy Caching..Happy Coding πŸ™‚

Integrating Spring with MongoDB

Hi all from past few weeks i was doing research on NoSql, so in the research i found that NoSql has been categorized into three types “Document Database”,”Column Database”,”Graph Based Database”. I have chose two database to integrate with spring one is MongoDB(Document based database) and the other is Apache Cassandra (Column Family Database). In this post i am going to explain how to integrate MongoDB with Spring. In later posts i will explain how to integrate Spring with Cassandra.

Note : before start reading this post please install MongoDB, based on your OS compatibility.

Let us talk about mongodb a little bit before we dive into the tutorial.
MongoDB is cross-platform document oriented database that provide high reliability and scalability, this works on concepts of documents and collections.

A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection’s documents may hold different types of data.

A collection is set of documents, this collection can exist in single or multi-node cluster database. A document with in a collection can have different fields.

the project structure looks as below.
mongo-proj-struct

let us see the pom.xml configuration. This project is compatible with java 8 specification.
pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.spark.springdata.mongodb</groupId>
	<artifactId>SpringDataMongoDB</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringDataMongoDB</name>
	<description>SpringDataMongoDB</description>

	<properties>
		<spring-version>3.2.8.RELEASE</spring-version>
	</properties>

	<!-- Spring framework -->

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring-version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring-version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring-version}</version>
		</dependency>

		<!-- mongodb java driver -->
		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
			<version>2.11.0</version>
		</dependency>

		<!-- Spring data mongodb -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-mongodb</artifactId>
			<version>1.2.0.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2.2</version>
		</dependency>

		<!-- oracle and mysql -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.6</version>
		</dependency>

		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc14</artifactId>
			<version>14.0.0</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.2</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

Now let us take a look at the Spring configuration file application-context.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:cache="http://www.springframework.org/schema/cache"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
		http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.2.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">

	<context:property-placeholder location="classpath:jdbc.properties" />

	<bean id="orclDataSource" class="oracle.jdbc.pool.OracleDataSource"
		destroy-method="close">
		<property name="URL" value="${orcl.jdbc.url}" />
		<property name="user" value="${orcl.jdbc.username}" />
		<property name="password" value="${orcl.jdbc.password}" />
		<property name="connectionCachingEnabled" value="true" />
	</bean>

	<bean name="mysqlDataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${mysql.jdbc.driver}" />
		<property name="url" value="${mysql.jdbc.url}" />
		<property name="username" value="${mysql.jdbc.user}" />
		<property name="password" value="${mysql.jdbc.password}" />
	</bean>

	<context:component-scan base-package="com.spark.spring.data" />

	<!-- Factory bean that creates the Mongo instance -->
	<bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
		<property name="host" value="localhost" />
	</bean>

	<!-- MongoTemplate for connecting and quering the documents in the database -->
	<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
		<constructor-arg name="mongo" ref="mongo" />
		<constructor-arg name="databaseName" value="person" />
	</bean>
	
	<bean id="personService" class="com.spark.spring.data.service.PersonService">
	    <constructor-arg name="mongoTemplate" ref="mongoTemplate"/>
	</bean>
</beans>

Now let us look at the Utility class that will help us to load the configuration file and fetch the different bean objects.

/**
 * 
 */
package com.spark.spring.data.util;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.mongodb.core.MongoTemplate;

/**
 * @author PavanKumar Mantha
 * 
 */
public class SpringDataUtil {

	private static Future<ApplicationContext> applicationContext;

	static {
		ExecutorService executorService = Executors.newFixedThreadPool(1);
		applicationContext = executorService
				.submit(new Callable<ApplicationContext>() {
					public ApplicationContext call() throws Exception {
						return new ClassPathXmlApplicationContext(
								"application-context.xml");
					}

				});
	}

	/**
	 * @return
	 */
	public static ApplicationContext getContext() {
		try {
			return applicationContext.get();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	/**
	 * @return
	 */
	public static DataSource getOracleDataSource() {
		try {
			return (DataSource) getContext().getBean("orclDataSource");
		} catch (Exception e) {
			throw new RuntimeException();
		}
	}

	/**
	 * @return
	 */
	public static DataSource getMysqleDataSource() {
		try {
			return (DataSource) getContext().getBean("mysqlDataSource");
		} catch (Exception e) {
			throw new RuntimeException();
		}
	}

	/**
	 * @param beanName
	 * @return
	 */
	public static Object getObject(String beanName) {
		return getContext().getBean(beanName);
	}

	public static MongoTemplate getMongoTemplate(){
		return (MongoTemplate) getContext().getBean("mongoTemplate");
	}
	
}

Let us create the domain objects in order to hold the data and these are the objects that gets persisted as documents inside mongodb.
Person.java

/**
 * 
 */
package com.spark.spring.data.document.obj;

import java.util.List;
import java.util.Set;

import org.springframework.data.annotation.Id;

/**
 * @author PavanKumar Mantha
 *
 */
public class Person {

	@Id
	private int id;
	private String firstName;
	private String lastName;
	private Set<String> phoneNumbers;
	private List<Address> address;

	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}

	/**
	 * @return the firstName
	 */
	public String getFirstName() {
		return firstName;
	}

	/**
	 * @param firstName
	 *            the firstName to set
	 */
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	/**
	 * @return the lastName
	 */
	public String getLastName() {
		return lastName;
	}

	/**
	 * @param lastName
	 *            the lastName to set
	 */
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	/**
	 * @return the phoneNumbers
	 */
	public Set<String> getPhoneNumbers() {
		return phoneNumbers;
	}

	/**
	 * @param phoneNumbers
	 *            the phoneNumbers to set
	 */
	public void setPhoneNumbers(Set<String> phoneNumbers) {
		this.phoneNumbers = phoneNumbers;
	}

	/**
	 * @return the address
	 */
	public List<Address> getAddress() {
		return address;
	}

	/**
	 * @param address
	 *            the address to set
	 */
	public void setAddress(List<Address> address) {
		this.address = address;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((address == null) ? 0 : address.hashCode());
		result = prime * result
				+ ((firstName == null) ? 0 : firstName.hashCode());
		result = prime * result + id;
		result = prime * result
				+ ((lastName == null) ? 0 : lastName.hashCode());
		result = prime * result
				+ ((phoneNumbers == null) ? 0 : phoneNumbers.hashCode());
		return result;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Person other = (Person) obj;
		if (address == null) {
			if (other.address != null)
				return false;
		} else if (!address.equals(other.address))
			return false;
		if (firstName == null) {
			if (other.firstName != null)
				return false;
		} else if (!firstName.equals(other.firstName))
			return false;
		if (id != other.id)
			return false;
		if (lastName == null) {
			if (other.lastName != null)
				return false;
		} else if (!lastName.equals(other.lastName))
			return false;
		if (phoneNumbers == null) {
			if (other.phoneNumbers != null)
				return false;
		} else if (!phoneNumbers.equals(other.phoneNumbers))
			return false;
		return true;
	}
	
	

}

Adddress.java

/**
 * 
 */
package com.spark.spring.data.document.obj;

import org.springframework.data.annotation.Id;

/**
 * @author Sony
 *
 */
public class Address {

	@Id
	private int id;
	private String doorNo;
	private String street;
	private String city;
	private String country;
	private String zipcode;

	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}

	/**
	 * @return the doorNo
	 */
	public String getDoorNo() {
		return doorNo;
	}

	/**
	 * @param doorNo
	 *            the doorNo to set
	 */
	public void setDoorNo(String doorNo) {
		this.doorNo = doorNo;
	}

	/**
	 * @return the street
	 */
	public String getStreet() {
		return street;
	}

	/**
	 * @param street
	 *            the street to set
	 */
	public void setStreet(String street) {
		this.street = street;
	}

	/**
	 * @return the city
	 */
	public String getCity() {
		return city;
	}

	/**
	 * @param city
	 *            the city to set
	 */
	public void setCity(String city) {
		this.city = city;
	}

	/**
	 * @return the country
	 */
	public String getCountry() {
		return country;
	}

	/**
	 * @param country
	 *            the country to set
	 */
	public void setCountry(String country) {
		this.country = country;
	}

	/**
	 * @return the zipcode
	 */
	public String getZipcode() {
		return zipcode;
	}

	/**
	 * @param zipcode
	 *            the zipcode to set
	 */
	public void setZipcode(String zipcode) {
		this.zipcode = zipcode;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((city == null) ? 0 : city.hashCode());
		result = prime * result + ((country == null) ? 0 : country.hashCode());
		result = prime * result + ((doorNo == null) ? 0 : doorNo.hashCode());
		result = prime * result + ((street == null) ? 0 : street.hashCode());
		result = prime * result + ((zipcode == null) ? 0 : zipcode.hashCode());
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Address other = (Address) obj;
		if (city == null) {
			if (other.city != null)
				return false;
		} else if (!city.equals(other.city))
			return false;
		if (country == null) {
			if (other.country != null)
				return false;
		} else if (!country.equals(other.country))
			return false;
		if (doorNo == null) {
			if (other.doorNo != null)
				return false;
		} else if (!doorNo.equals(other.doorNo))
			return false;
		if (street == null) {
			if (other.street != null)
				return false;
		} else if (!street.equals(other.street))
			return false;
		if (zipcode == null) {
			if (other.zipcode != null)
				return false;
		} else if (!zipcode.equals(other.zipcode))
			return false;
		return true;
	}

}

Once the document objects are ready in hand let us start writing the service implementation. Please observe service class the MongoTemplate (Similar to JdbcTemplate) of SpringFramework gets injected as constructor argument and this is responsible of doing different operations on database.
PersonService.java

/**
 * 
 */
package com.spark.spring.data.service;

import java.util.List;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import com.spark.spring.data.document.obj.Person;

/**
 * @author PavanKumar Mantha
 * 
 */
public class PersonService {

	private MongoTemplate mongoTemplate;
	private static final String COLLECTION_NAME = "person";

	/**
	 * @param mongoTemplate
	 */
	public PersonService(MongoTemplate mongoTemplate) {
		this.mongoTemplate = mongoTemplate;
	}
	
	public void setMongoTemplateObject(MongoTemplate mongoTemplate) {
		this.mongoTemplate = mongoTemplate;
	}

	/**
	 * @param person
	 * @return
	 */
	public boolean addPerson(Person person) {
		boolean status = false;
		try {
			if (!mongoTemplate.collectionExists(Person.class)) {
				mongoTemplate.createCollection(Person.class);
			}
			mongoTemplate.insert(person, COLLECTION_NAME);
			status = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return status;
	}

	/**
	 * @return
	 */
	public List<Person> listPerson() {
		return mongoTemplate.findAll(Person.class, COLLECTION_NAME);
	}

	/**
	 * @param person
	 */
	public void deletePerson(Person person) {
		mongoTemplate.remove(person, COLLECTION_NAME);
	}
	
	/**
	 * 
	 */
	public void deleteAll() {
		mongoTemplate.getDb().dropDatabase();
	}
	
	/**
	 * @param id
	 * @return
	 */
	public Person findPersonById(String id){
		//BasicQuery query = new BasicQuery("{Name:'"+name+"'}");
		
		Query query = new Query();
		query.addCriteria(Criteria.where("_id").is(id));
		
		Person person = mongoTemplate.findOne(query, Person.class);
		return person;
	}
	
	/**
	 * @param id
	 * @return
	 */
	public boolean deletePersonById(String id){
		Person person = findPersonById(id);
		boolean status = false; 
		try {
			mongoTemplate.remove(person, COLLECTION_NAME);
			status = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return status;
	}

	/**
	 * @param person
	 */
	public void updatePerson(Person person) {
		mongoTemplate.save(person, COLLECTION_NAME);
	}
}

Once the service class is ready in hand it’s time for us to test this class, before running the test class make sure your mongodb is up and running.
SpringMongoTest.java

/**
 * 
 */
package com.spark.spring.data.mongo.test;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import org.springframework.data.mongodb.core.MongoTemplate;

import com.spark.spring.data.document.obj.Address;
import com.spark.spring.data.document.obj.Person;
import com.spark.spring.data.service.PersonService;
import com.spark.spring.data.util.SpringDataUtil;

/**
 * @author PavanKumar Mantha
 * 
 */
public class SpringMongoTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Person person = new Person();
		
		Address residenceAddress = new Address();
		residenceAddress.setId(1);
		residenceAddress.setDoorNo("7-48/4");
		residenceAddress.setStreet("Shankar Nagar");
		residenceAddress.setCity("Hyderabad");
		residenceAddress.setCountry("India");
		residenceAddress.setZipcode("500098");
		
		Address officeAddress = new Address();
		officeAddress.setId(2);
		officeAddress.setDoorNo("Ness Technologies");
		officeAddress.setStreet("Maximus 2B, Raheja Mind Space, HitechCity");
		officeAddress.setCity("Hyderabad");
		officeAddress.setCountry("India");
		officeAddress.setZipcode("500098");
		
		List<Address> addresses = new ArrayList<>();
		addresses.add(residenceAddress);
		addresses.add(officeAddress);
		
		person.setId(1);
		person.setFirstName("Kameswara Pavan Kumar");
		person.setLastName("Mantha");
		Set<String> phoneNumbers = new HashSet<>();
		phoneNumbers.add("9949493991");
		phoneNumbers.add("9603434035");
		person.setPhoneNumbers(phoneNumbers);
		person.setAddress(addresses);
		
		PersonService personService = (PersonService) SpringDataUtil
				.getObject("personService");

		personService.deleteAll();
		
		if(personService.addPerson(person)){
			System.out.println("Person Added");
		}

	}
}

if every thing goes well and good then we should see some thing as below as output in mongo database.
mongodb-output

Happy Coding, Happy MongoDB πŸ™‚

Oracle Fusion Middleware – “Concepts of Oracle Coherence”

Hi all, if you are dealing with large applications with loads of write and read operations then each call to database will cost you so much in the performance prospective. Thinking of the above point now a days cache driven applications are given more and more importance. In this tutorial i will taking about the “Oracle Coherence”.

Note : This article assume that you already have the coherence downloaded and you know how to run a cache-server.

These days its very common to pre-populate the cache before the application starts using the data. In this example i am going to pre-popuate the cache.

Oracle Coherence revolves around the concept of named caches. The first thing you need to do in your code when working with Coherence is to obtain a reference to a named cache you want to work with. In order to do this, you
need to use the CacheFactory class, which exposes the getCache method as one of its public members.

below is the project structure.
coh-proj-struct

first of all let us write the configurations.
Step 1: applicationContext.xml – this file has the spring capability to instantiate the beans. In this i have written the DataSource object instantiation.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
		<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
		<property name="username" value="scott" />
		<property name="password" value="tiger" />
	</bean>
</beans>

let us start configuring our custom cache by creating coherence-cache-config.xml

<cache-config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.oracle.com/coherence/coherence-cache-config"
	xsi:schemaLocation="http://xmlns.oracle.com/coherence/coherence-cache-config http://xmlns.oracle.com/coherence/coherence-cache-config/1.0/coherence-cache-config.xsd">	<!-- The defaults element defines factory-wide default settings. -->

	<defaults>
		<serializer system-property="tangosol.coherence.serializer" />
		<socket-provider system-property="tangosol.coherence.socketprovider" />
	</defaults>

	<caching-scheme-mapping>
		<cache-mapping>
			<cache-name>dist-*</cache-name>
			<scheme-name>example-distributed</scheme-name>
			<init-params>
				<init-param>
					<param-name>back-size-limit</param-name>
					<param-value>8MB</param-value>
				</init-param>
			</init-params>
		</cache-mapping>

		<cache-mapping>
			<cache-name>*</cache-name>
			<scheme-name>example-distributed</scheme-name>
		</cache-mapping>
	</caching-scheme-mapping>

	<caching-schemes>
		<!-- Distributed caching scheme. -->
		<distributed-scheme>
			<scheme-name>example-distributed</scheme-name>
			<service-name>DistributedCache</service-name>
			<serializer>
				<instance>
					<class-name>com.tangosol.io.pof.ConfigurablePofContext</class-name>
					<init-params>
						<init-param>
							<param-type>String</param-type>
							<param-value>custom-pof-config.xml</param-value>
						</init-param>
					</init-params>
				</instance>
			</serializer>
			<backing-map-scheme>
				<read-write-backing-map-scheme>
					<internal-cache-scheme>
						<local-scheme>
						</local-scheme>
					</internal-cache-scheme>
				</read-write-backing-map-scheme>
			</backing-map-scheme>
			<autostart>true</autostart>
		</distributed-scheme>
	</caching-schemes>
</cache-config>

for every bean that we write we need to add an entry in the below file custom-pof-config.xml

<?xml version="1.0"?>
<pof-config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.oracle.com/coherence/coherence-pof-config"
	xsi:schemaLocation="http://xmlns.oracle.com/coherence/coherence-pof-config http://xmlns.oracle.com/coherence/coherence-pof-config/1.0/coherence-pof-config.xsd">
	<user-type-list>
		<!-- include all "standard" Coherence POF user types -->
		<include>coherence-pof-config.xml</include>
		<user-type>
			<type-id>1000</type-id>
			<class-name>com.spark.coherence.pof.beans.EmployeeBean</class-name>
		</user-type>
	</user-type-list>
</pof-config>

we need to override the tangosol-coherence-override.xml file with our config file entries as below.

<?xml version='1.0'?>
<coherence
	xmlns="http://xmlns.oracle.com/coherence/coherence-operational-config"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.oracle.com/coherence/coherence-operational-config http://xmlns.oracle.com/coherence/coherence-operational-config/1.2/coherence-operational-config.xsd">
	<cluster-config>
		<!-- <member-identity> <cluster-name>my-coherance-cluster</cluster-name> 
			</member-identity> -->

		<multicast-listener>
			<address>224.12.1.0</address>
			<port>12100</port>
			<time-to-live>60</time-to-live>
		</multicast-listener>
	</cluster-config>

	<configurable-cache-factory-config>
		<init-params>
			<init-param>
				<param-type>java.lang.String</param-type>
				<param-value system-property="tangosol.coherence.cacheconfig">
					coherence-cache-config.xml
				</param-value>
			</init-param>
		</init-params>
	</configurable-cache-factory-config>
</coherence>

Once done with our configuration file, let us start writing the jdbc connection factory class.

/**
 * 
 */
package com.spark.coherence.jdbc.connection.factory;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.sql.DataSource;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Sony
 *
 */
public class CoherenceJdbcConnectionFactory {

	private static Future<ApplicationContext> future;
	private static ExecutorService executorService = Executors.newFixedThreadPool(1);
	
	static{
		future = executorService.submit(new Callable<ApplicationContext>() {
			@Override
			public ApplicationContext call() throws Exception {
				return new ClassPathXmlApplicationContext("applicationContext.xml");
			}
		});
	}
	
	/**
	 * @return java.sql.Connection
	 * @throws InterruptedException
	 * @throws ExecutionException
	 * @throws BeansException
	 * @throws SQLException
	 */
	public static Connection getJdbcConnection() throws InterruptedException, ExecutionException, BeansException, SQLException{
		ApplicationContext applicationContext = future.get();
		return ((DataSource)applicationContext.getBean("dataSource")).getConnection();
	}
	
	/**
	 * @return javax.sql.DataSource
	 * @throws InterruptedException
	 * @throws ExecutionException
	 * @throws BeansException
	 * @throws SQLException
	 */
	public static DataSource getJdbcDataSource() throws InterruptedException, ExecutionException, BeansException, SQLException{
		ApplicationContext applicationContext = future.get();
		return ((DataSource)applicationContext.getBean("dataSource"));
	}
	
	private static ExecutorService getCurrentExecutorService(){
		return executorService;
	}
	
	public static void shutDownCurrentExecutorService(){
		getCurrentExecutorService().shutdown();
	}
}

Now let us create pojo classes, there are two classes explained here one is Entity.java and other is EmployeeBean.java. The Entity.java is used as Key for the EmployeeBean objects

/**
 * 
 */
package com.spark.coherence.pof.beans;

import java.io.IOException;

import com.tangosol.io.pof.PofReader;
import com.tangosol.io.pof.PofWriter;
import com.tangosol.io.pof.PortableObject;

/**
 * @author Sony
 * 
 */
public class Entity<T> implements PortableObject{

	public T key;

	/**
	 * @return the key
	 */
	public T getKey() {
		return key;
	}

	/**
	 * @param key
	 *            the key to set
	 */
	public void setKey(T key) {
		this.key = key;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void readExternal(PofReader pofReader) throws IOException {
		this.key = (T) pofReader.readObject(0);
	}

	@Override
	public void writeExternal(PofWriter pofWriter) throws IOException {
		pofWriter.writeObject(0, key);
	}

}
/**
 * 
 */
package com.spark.coherence.pof.beans;

import java.io.IOException;
import java.util.Date;

import com.tangosol.io.pof.PofReader;
import com.tangosol.io.pof.PofWriter;

/**
 * @author Sony
 * 
 */
public class EmployeeBean extends Entity<Integer> {

	private int employeeId;
	private String employeeName;
	private String job;
	private int managerId;
	private Date hireDate;
	private int salary;
	private int commission;
	private int deptNo;

	public EmployeeBean() {
		// TODO Auto-generated constructor stub
	}

	public EmployeeBean(int employeeId) {
		super.setKey(employeeId);
		this.employeeId = employeeId;
	}

	/**
	 * @return the employeeId
	 */
	public int getEmployeeId() {
		return employeeId;
	}

	/**
	 * @param employeeId
	 *            the employeeId to set
	 */
	public void setEmployeeId(int employeeId) {
		this.employeeId = employeeId;
	}

	/**
	 * @return the employeeName
	 */
	public String getEmployeeName() {
		return employeeName;
	}

	/**
	 * @param employeeName
	 *            the employeeName to set
	 */
	public void setEmployeeName(String employeeName) {
		this.employeeName = employeeName;
	}

	public String getJob() {
		return job;
	}

	public void setJob(String job) {
		this.job = job;
	}

	public int getManagerId() {
		return managerId;
	}

	public void setManagerId(int managerId) {
		this.managerId = managerId;
	}

	public Date getHireDate() {
		return hireDate;
	}

	public void setHireDate(Date hireDate) {
		this.hireDate = hireDate;
	}

	public int getSalary() {
		return salary;
	}

	public void setSalary(int salary) {
		this.salary = salary;
	}

	public int getCommission() {
		return commission;
	}

	public void setCommission(int commission) {
		this.commission = commission;
	}

	public int getDeptNo() {
		return deptNo;
	}

	public void setDeptNo(int deptNo) {
		this.deptNo = deptNo;
	}

	@Override
	public void readExternal(PofReader pofReader) throws IOException {
		this.employeeId = pofReader.readInt(0);
		this.employeeName = pofReader.readString(1);
		this.job = pofReader.readString(2);
		this.managerId = pofReader.readInt(3);
		this.hireDate = pofReader.readDate(4);
		this.salary = pofReader.readInt(5);
		this.commission = pofReader.readInt(6);
		this.deptNo = pofReader.readInt(7);
	}

	@Override
	public void writeExternal(PofWriter pofWriter) throws IOException {
		pofWriter.writeInt(0, employeeId);
		pofWriter.writeString(1, employeeName);
		pofWriter.writeString(2, job);
		pofWriter.writeInt(3, managerId);
		pofWriter.writeDate(4, hireDate);
		pofWriter.writeInt(5, salary);
		pofWriter.writeInt(6, commission);
		pofWriter.writeInt(7, deptNo);
	}

}

Let’s start with writing logic to fetch from Oracle database and put that into Map

/**
 * 
 */
package com.spark.coherence.jdbc.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;

import com.spark.coherence.pof.beans.EmployeeBean;

/**
 * @author Sony
 *
 */
public class EmployeeDao {

	private JdbcTemplate jdbcTemplate;

	public EmployeeDao(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	public Map<Integer, EmployeeBean> getAllEmployees() {
		String sql = "select * from emp";

		Map<Integer, EmployeeBean> map = this.jdbcTemplate.query(sql,
				new ResultSetExtractor<Map<Integer, EmployeeBean>>() {

					Map<Integer, EmployeeBean> map = new HashMap<>();

					public java.util.Map<Integer, EmployeeBean> extractData(
							ResultSet resultSet) throws SQLException,
							DataAccessException {
						
						while (resultSet.next()) {
							EmployeeBean employeeBean = new EmployeeBean(
									resultSet.getInt("empno"));
							employeeBean.setEmployeeName(resultSet
									.getString("ename"));
							employeeBean.setJob(resultSet.getString("job"));
							employeeBean.setCommission(resultSet.getInt("comm"));
							employeeBean.setDeptNo(resultSet.getInt("deptno"));
							employeeBean.setHireDate(resultSet
									.getDate("hiredate"));
							employeeBean.setManagerId(resultSet.getInt("mgr"));
							employeeBean.setSalary(resultSet.getInt("sal"));

							map.put(employeeBean.getKey(), employeeBean);
						}

						return map;

					};
				});

		return map;
	}
}

Let us create a CacheRepository class from which we get the NamedCache instance as shown below.

/**
 * 
 */
package com.spark.coherence.cache.repository;

import com.tangosol.net.CacheFactory;
import com.tangosol.net.NamedCache;

/**
 * @author Sony
 *
 */
public class CacheRepository {

	public static NamedCache getEmployeeCache(){
		return CacheFactory.getCache("dist-employee-cache");
	}
}

Now its time for to call the service layer and then put the data to cache.

/**
 * 
 */
package com.spark.coherence.cache.service.impl;

import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import org.springframework.beans.BeansException;

import com.spark.coherence.cache.repository.CacheRepository;
import com.spark.coherence.jdbc.connection.factory.CoherenceJdbcConnectionFactory;
import com.spark.coherence.jdbc.dao.impl.EmployeeDao;
import com.spark.coherence.pof.beans.EmployeeBean;
import com.tangosol.net.NamedCache;


/**
 * @author Sony
 *
 */
public class CacheService {

	public void preLoadCache(){
		try {
			Map<Integer, EmployeeBean> map = new EmployeeDao(CoherenceJdbcConnectionFactory.getJdbcDataSource()).getAllEmployees();
			NamedCache namedCache = CacheRepository.getEmployeeCache();
			namedCache.putAll(map);
		} catch (BeansException | InterruptedException | ExecutionException
				| SQLException e) {
			e.printStackTrace();
		}
	}
}

That is it we have done with coding part its now time for us to test the application by running the main method.

/**
 * 
 */
package com.spark.main;

import java.util.ArrayList;
import java.util.Collection;

import com.spark.coherence.cache.repository.CacheRepository;
import com.spark.coherence.cache.service.impl.CacheService;
import com.spark.coherence.jdbc.connection.factory.CoherenceJdbcConnectionFactory;
import com.spark.coherence.pof.beans.EmployeeBean;
import com.tangosol.net.NamedCache;


/**
 * @author Sony
 *
 */
public class CoherenceTest {

	/**
	 * @param args
	 */
	@SuppressWarnings({ "unused", "unchecked" })
	public static void main(String[] args) {
		NamedCache namedCache = CacheRepository.getEmployeeCache();
		System.out.println(namedCache.getCacheService().getInfo().getServiceName());
		
		new CacheService().preLoadCache();
		EmployeeBean employeeBean = (EmployeeBean)namedCache.get(7782);
		System.out.println(employeeBean.getEmployeeName());

		Collection<Integer> ids = new ArrayList<>();
		ids.add(7654);
		ids.add(7698);
		
		Collection<EmployeeBean> employeeBeans = namedCache.getAll(ids).values();
		for (EmployeeBean employeeBean2 : employeeBeans) {
			System.out.println(employeeBean2.getEmployeeName());
		}
		
		CoherenceJdbcConnectionFactory.shutDownCurrentExecutorService();
	}

}

Please observer the main class carefully i have demonstrated the two public methods get(Object) and getAll(Collection). In my next post i will be demonstrating to use the CacheListeners to know if cache is update,deleted or inserted.

Happy Coherence and Happy Coding πŸ™‚

Spring 4 – ContentNegotiatingViewResolver Sample

Hello every one, recently in one of my project i had a requirement that i need to generate multiple views based on the request type, this has lead me to write this post. In this article i will be explaining about “ContentNegotiatingViewResolver” class.

ContentNegotiatingViewResolver class is a implementation of ViewResolver. The ContentNegotiatingViewResolver does not resolve the view by itself unlike the ViewResolver based on the request type or the Header type in fact this delegates the request to other ViewResolvers that are configured explicitly.

This view resolver uses the requested media type to select a suitable View for a request. The requested media type is determined through the configured ContentNegotiationManager. Once the requested media type has been determined, this resolver queries each delegate view resolver for a View and determines if the requested media type is compatible with the view’s content type). The most compatible view is returned.

Below is the Project Structure.
ProjStruct-1

the project pom.xml is as follows

<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>com.spring.ContentNegotiatingViewResolver</groupId>
	<artifactId>ContentNegotiatingViewResolver</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>ContentNegotiatingViewResolver</name>
	<description>ContentNegotiatingViewResolver</description>

	<properties>
		<springframework.version>4.0.6.RELEASE</springframework.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${springframework.version}</version>
		</dependency>

		<!-- Needed for XML View (with JAXB2) -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-oxm</artifactId>
			<version>${springframework.version}</version>
		</dependency>

		<!-- Needed for JSON View -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.4.1.3</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>2.4.1</version>
		</dependency>

		<!-- Needed for PDF View -->
		<dependency>
			<groupId>com.lowagie</groupId>
			<artifactId>itext</artifactId>
			<version>4.2.1</version>
		</dependency>

		<!-- Needed for XLS View -->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.10-beta2</version>
		</dependency>

		<!-- Servlet dependencies -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.3.1</version>
		</dependency>

	</dependencies>


	<build>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-war-plugin</artifactId>
					<version>2.4</version>
					<configuration>
						<warSourceDirectory>src/main/webapp</warSourceDirectory>
						<warName>Spring4MVCContentNegotiatingViewResolverExample</warName>
						<failOnMissingWebXml>false</failOnMissingWebXml>
					</configuration>
				</plugin>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-compiler-plugin</artifactId>
					<configuration>
						<source>1.7</source>
						<target>1.7</target>
					</configuration>
				</plugin>
				<plugin>
					<groupId>org.codehaus.mojo</groupId>
					<artifactId>tomcat-maven-plugin</artifactId>
					<version>1.0-beta-1</version>
				</plugin>
			</plugins>
		</pluginManagement>

		<finalName>Spring4MVCContentNegotiatingViewResolverExample</finalName>
	</build>
</project>

Now let us create the configuration classes as this article is based on no-xml.
AppConfig.java

package com.spark.spring.config;

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

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import com.spark.spring.domain.objects.Pizza;
import com.spark.spring.view.resolvers.ExcelViewResolver;
import com.spark.spring.view.resolvers.Jaxb2MarshallingXmlViewResolver;
import com.spark.spring.view.resolvers.JsonViewResolver;
import com.spark.spring.view.resolvers.PdfViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.spark.spring")
public class AppConfig extends WebMvcConfigurerAdapter {

	public void configureContentNegotiation(
			ContentNegotiationConfigurer contentNegotiationConfigurer) {
		contentNegotiationConfigurer.ignoreAcceptHeader(true)
				.defaultContentType(MediaType.TEXT_HTML);
	}

	@Bean
	public ViewResolver contentNegotiationViewResolver(
			ContentNegotiationManager contentNegotiationManager) {
		ContentNegotiatingViewResolver contentNegotiatingViewResolver = new ContentNegotiatingViewResolver();
		contentNegotiatingViewResolver
				.setContentNegotiationManager(contentNegotiationManager);

		List<ViewResolver> resolvers = new ArrayList<ViewResolver>();
		resolvers.add(jaxb2MarshallingXmlViewResolver());
		resolvers.add(jsonViewResolver());
		resolvers.add(excelViewResolver());
		resolvers.add(pdfViewResolver());

		contentNegotiatingViewResolver.setViewResolvers(resolvers);
		return contentNegotiatingViewResolver;
	}

	/*
	 * Configure View resolver to provide XML output Uses JAXB2 marshaller to
	 * marshall/unmarshall POJO's (with JAXB annotations) to XML
	 */
	@Bean
	public ViewResolver jaxb2MarshallingXmlViewResolver() {
		Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
		marshaller.setClassesToBeBound(Pizza.class);
		return new Jaxb2MarshallingXmlViewResolver(marshaller);
	}

	/*
	 * Configure View resolver to provide JSON output using JACKSON library to
	 * convert object in JSON format.
	 */
	@Bean
	public ViewResolver jsonViewResolver() {
		return new JsonViewResolver();
	}
	
	/*
	 * Configure View resolver to provide PDF output using lowagie pdf library to
	 * generate PDF output for an object content
	 */
	@Bean
	public ViewResolver pdfViewResolver() {
		return new PdfViewResolver();
	}

	/*
	 * Configure View resolver to provide XLS output using Apache POI library to
	 * generate XLS output for an object content
	 */
	@Bean
	public ViewResolver excelViewResolver() {
		return new ExcelViewResolver();
	}
	
	/*
	 * Configure View resolver to provide HTML output This is the default format
	 * in absence of any type suffix.
	 */
	@Bean
	public ViewResolver jspViewResolver() {
		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		viewResolver.setViewClass(JstlView.class);
		viewResolver.setPrefix("/WEB-INF/views/");
		viewResolver.setSuffix(".jsp");
		return viewResolver;
	}
}

Let us look into the above class little deep, First we have created ContentNegotiationManager which is used to determine the requested media types of a request by delegating to a list of ContentNegotiationStrategy instances. By default PathExtensionContentNegotiationStrategy is consulted (which uses the URL extension e.g. .xls, .pdf,.json..) , followed by ParameterContentNegotiationStrategy (which uses the request parameter β€˜format=xls’ e.g.), followed by HeaderContentNegotiationStrategy (which uses HTTP Accept Headers) the ContentNegotiationManager instance is injected by Spring Container.
Snippet

@Bean
	public ViewResolver contentNegotiationViewResolver(
			ContentNegotiationManager contentNegotiationManager) {
		ContentNegotiatingViewResolver contentNegotiatingViewResolver = new ContentNegotiatingViewResolver();
		contentNegotiatingViewResolver
				.setContentNegotiationManager(contentNegotiationManager);

once the ContentNegotiationManager instance is ready then we need to pass different implementations of view resolvers in order to resolve dynamically in the runtime.
Snippet:

List<ViewResolver> resolvers = new ArrayList<ViewResolver>();
		resolvers.add(jaxb2MarshallingXmlViewResolver());
		resolvers.add(jsonViewResolver());
		resolvers.add(excelViewResolver());
		resolvers.add(pdfViewResolver());

		contentNegotiatingViewResolver.setViewResolvers(resolvers);
		return contentNegotiatingViewResolver;

There is one more configuration class required inorder to map the request using the front control called “DispatcherServlet”

/**
 * 
 */
package com.spark.spring.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * @author Sony
 * 
 */
public class AppInitializer implements WebApplicationInitializer {

	public void onStartup(ServletContext container) throws ServletException {

		AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
		ctx.register(AppConfig.class);
		ctx.setServletContext(container);

		ServletRegistration.Dynamic servlet = container.addServlet(
				"dispatcher", new DispatcherServlet(ctx));

		servlet.setLoadOnStartup(1);
		servlet.addMapping("/");
	}

}

Now let us create different ViewResolver Classes inorder to inject them into ContentNegotiatingViewResolver Object.
Jaxb2MarshallingXmlViewResolver.java

/**
 * 
 */
package com.spark.spring.view.resolvers;

import java.util.Locale;

import org.springframework.oxm.Marshaller;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.xml.MarshallingView;

/**
 * @author Sony
 * 
 */
public class Jaxb2MarshallingXmlViewResolver implements ViewResolver {

	private Marshaller marshaller;

	public Jaxb2MarshallingXmlViewResolver(Marshaller marshaller) {
		this.marshaller = marshaller;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.ViewResolver#resolveViewName(java.lang
	 * .String, java.util.Locale)
	 */
	public View resolveViewName(String viewName, Locale locale)
			throws Exception {
		MarshallingView view = new MarshallingView();
		view.setMarshaller(marshaller);
		return view;
	}

}

JsonViewResolver.java

/**
 * 
 */
package com.spark.spring.view.resolvers;

import java.util.Locale;

import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

/**
 * @author Sony
 * 
 */
public class JsonViewResolver implements ViewResolver {

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.ViewResolver#resolveViewName(java.lang
	 * .String, java.util.Locale)
	 */
	public View resolveViewName(String viewName, Locale locale)
			throws Exception {
		MappingJackson2JsonView view = new MappingJackson2JsonView();
		view.setPrettyPrint(true);
		return view;
	}

}

ExcelViewResolver.java

/**
 * 
 */
package com.spark.spring.view.resolvers;

import java.util.Locale;

import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;

import com.spark.spring.views.GenerateExcel;

/**
 * @author Sony
 *
 */
public class ExcelViewResolver implements ViewResolver {

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.ViewResolver#resolveViewName(java.lang.String, java.util.Locale)
	 */
	@Override
	public View resolveViewName(String viewname, Locale locale) throws Exception {
		GenerateExcel generateExcel = new GenerateExcel();
		return generateExcel;
	}

}

PdfViewResolver.java

/**
 * 
 */
package com.spark.spring.view.resolvers;

import java.util.Locale;

import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;

import com.spark.spring.views.GeneratePdf;

/**
 * @author Sony
 *
 */
public class PdfViewResolver implements ViewResolver{

	@Override
	public View resolveViewName(String viewName, Locale locale) throws Exception {
		GeneratePdf generatePdf = new GeneratePdf();
		return generatePdf;
	}

}

Below are utility classes for generating Excel content and PDF Content.

GenerateExcel.java

/**
 * 
 */
package com.spark.spring.views;

import java.util.Map;

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

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.web.servlet.view.document.AbstractExcelView;

import com.spark.spring.domain.objects.Pizza;

/**
 * @author Sony
 * 
 */
public class GenerateExcel extends AbstractExcelView {

	@Override
	protected void buildExcelDocument(Map<String, Object> model,
			HSSFWorkbook workbook, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		Pizza pizza = (Pizza) model.get("pizza");

		Sheet sheet = workbook.createSheet("sheet 1");
		CellStyle style = workbook.createCellStyle();
		style.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.index);
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
		style.setAlignment(CellStyle.ALIGN_CENTER);
		Row row = null;
		Cell cell = null;
		int rowCount = 0;
		int colCount = 0;

		// Create header cells
		row = sheet.createRow(rowCount++);

		cell = row.createCell(colCount++);
		cell.setCellStyle(style);
		cell.setCellValue("Name");

		cell = row.createCell(colCount++);
		cell.setCellStyle(style);
		cell.setCellValue("Flavor");

		cell = row.createCell(colCount++);
		cell.setCellStyle(style);
		cell.setCellValue("Toppings");

		// Create data cells
		row = sheet.createRow(rowCount++);
		colCount = 0;
		row.createCell(colCount++).setCellValue(pizza.getName());
		row.createCell(colCount++).setCellValue(pizza.getFlavor());

		StringBuffer toppings = new StringBuffer("");
		for (String topping : pizza.getToppings()) {
			toppings.append(topping);
			toppings.append(" ");
		}
		row.createCell(colCount++).setCellValue(toppings.toString());

		for (int i = 0; i < 3; i++)
			sheet.autoSizeColumn(i, true);
	}

}

GeneratePdf.java

/**
 * 
 */
package com.spark.spring.views;

import java.awt.Color;
import java.util.Map;

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

import org.springframework.web.servlet.view.document.AbstractPdfView;

import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import com.spark.spring.domain.objects.Pizza;

/**
 * @author Sony
 *
 */
public class GeneratePdf extends AbstractPdfView{

	@Override
	protected void buildPdfDocument(Map<String, Object> model,
			Document document, PdfWriter writer, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		Pizza pizza = (Pizza) model.get("pizza");

		PdfPTable table = new PdfPTable(3);
		table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
		table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
		table.getDefaultCell().setBackgroundColor(Color.lightGray);

		table.addCell("Name");
		table.addCell("Flavor");
		table.addCell("Toppings");

		table.addCell(pizza.getName());
		table.addCell(pizza.getFlavor());

		StringBuffer toppings = new StringBuffer("");
		for (String topping : pizza.getToppings()) {
			toppings.append(topping);
			toppings.append(" ");
		}
		table.addCell(toppings.toString());
		document.add(table);

	}
}

Now its time for us to write the .JSP file

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"  pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
	<title>Pizza order JSP View</title>
</head>
<body>
	<table border="1">
		<tr>
		<td>NAME</td>
		<td>Flavor</td>
		<td>Toppings</td>
		</tr>
		<tr>
			<td>${pizza.name}</td>
			<td>${pizza.flavor}</td>
			<td>
				<c:forEach var="item" items="${pizza.toppings}">
					<c:out value="${item}"/>&nbsp; 
				</c:forEach>
			</td>
		</tr>
	</table>
</body>
</html>

That is it we have done with our coding, now its time for us to deploy and test.

resp-json

resp-pdf

resp-xml

credits to : http://websystique.com/springmvc/spring-4-mvc-contentnegotiatingviewresolver-example/

Happy Coding With Spring πŸ™‚