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 πŸ™‚

Java Reflection Tutorial

Hi all, this is my second post in 2015. Here in this tutorial i am going to focus little bit on Java’s one of the powerful concept called “Reflection”.

What is reflection?


“Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine.” This concept is often mixed with introspection. Now let us see the definitions of “Reflection” & “Introspection”.

Introspection is the ability of a program to examine the type or properties of an object at runtime.
Reflection is the ability of a program to examine and modify the structure and behavior of an object at runtime.

Reflection

Let us see simple code snippets about the two concepts as below.
Introspection Example: The instanceof operator determines whether an object belongs to a particular class.

if(obj instanceof CoffeeBean){
   CoffeeBean cb = (CoffeeBean)obj;
   cb.startMakingCoffee();
}

Reflection Example: The Class.forName() method returns the Class object associated with the class/interface with the given name(a string and full qualified name). The forName method causes the class with the name to be initialized.

// with reflection
Class<?> c = Class.forName("com.spark.beverages.CoffeeBean");
Object cb = c.newInstance();
Method m = c.getDeclaredMethod("startMakingCoffee", new Class<?>[0]);
m.invoke(cb);

Most of the web frameworks make use of reflection to make changes to objects using “Reflection”, some of the practical examples are as follows.

For example, Spring makes use of bean configuration such as:

<bean id="beanID" class="com.spark.beverages.CoffeeBean>
    <property name="someField" value="someValue" />
</bean>

When the Spring context processes this element, it will use Class.forName(String) with the argument “com.spark.beverages.CoffeeBean” to instantiate that Class. It will then again use reflection to get the appropriate setter for the element and set its value to the specified value.

let us consider the Servlet web applications, the same explanation applies to servlet configuration files also

<servlet>
    <servlet-name>someServlet</servlet-name>
    <servlet-class>com.spark.beverages.CoffeeBeanServlet</servlet-class>
<servlet>

Now let us see some examples on how to make use of Reflection API in java. Please go through the code carefully and its very easy to understand. The below code explains how to call different methods with different parameters and different return types.

/**
 * 
 */
package com.spark.java8.reflection;

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

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

	public void startMakingCoffee() {
		System.out.println("Coffee Making Started ...");
	}

	public void startMakingCoffee(String coffeeName) {
		System.out.println("Making of " + coffeeName + " Started ...");
	}

	public List<String> getBevarages() {
		List<String> list = new ArrayList<>(); // Using Java 7 feature
		list.add("Moka");
		list.add("caffuccino");
		list.add("Espressino");
		list.add("Black eye");
		list.add("Iced coffee");
		return list;
	}

	public int getTimeToMakeCoffee(String coffeeName) {
		if ("caffuccino".equalsIgnoreCase(coffeeName)) {
			return 15;
		} else {
			return 5;
		}
	}

}
/**
 * 
 */
package com.spark.java8.reflection.test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

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

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			Class<?> clazz = Class
					.forName("com.spark.java8.reflection.CoffeeBean");
			Object object = clazz.newInstance();
			Method method = clazz.getDeclaredMethod("startMakingCoffee", null);
			method.setAccessible(true);
			method.invoke(object, null);
			
			System.out.println("-----------------------------------------------");
			Method method2 = clazz.getDeclaredMethod("startMakingCoffee",
					new Class[] { String.class });
			method2.setAccessible(true);
			method2.invoke(object, "caffuccino");
			
			System.out.println("-----------------------------------------------");
			Method method3 = clazz.getDeclaredMethod("getBevarages", null);
			method3.setAccessible(true);
			List<?> name = (List<?>) method3.invoke(object, null);
			for (Object object2 : name) {
				System.out.println(object2);
			}
			
			System.out.println("-----------------------------------------------");
			Method method4 = clazz.getDeclaredMethod("getTimeToMakeCoffee", new Class[]{String.class});
			method4.setAccessible(true);
			String beverageName = "Cold coffee";
			int time = (int) method4.invoke(object, beverageName);
			System.out.println("time to make "+beverageName+" is "+time+" mins");
			
		}
		//Using Java 7 feature of Multiple Catch.
		catch (ClassNotFoundException | NoSuchMethodException
				| SecurityException | IllegalAccessException
				| IllegalArgumentException | InvocationTargetException
				| InstantiationException e) {
			e.printStackTrace();
		}
	}

}

Happy Reflections πŸ™‚ Happy Coding πŸ™‚

Introduction to Arduino

Hi All these days i got more fascinated towards IoT (Internet Of Things) the hot topic in market research, so i thought of doing research myself and started digging into it, then i came across may one of the hardware boards of which i was attracted to “Arduino”. When i told about Arduino to my friends the very first question i got from them is “What is Arduino ?” and “Why only Arduino ?” so i wanted to answer them infact Arduino corporation have answered the question in their site(Credits to arduino.cc)

What is Arduino?

Arduino is a tool for making computers that can sense and control more of the physical world than your desktop computer. It’s an open-source physical computing platform based on a simple microcontroller board, and a development environment for writing software for the board.

Arduino can be used to develop interactive objects, taking inputs from a variety of switches or sensors, and controlling a variety of lights, motors, and other physical outputs. Arduino projects can be stand-alone, or they can communicate with software running on your computer (e.g. Flash, Processing, MaxMSP.) The boards can be assembled by hand or purchased preassembled; the open-source IDE can be downloaded for free.

The Arduino programming language is an implementation of Wiring, a similar physical computing platform, which is based on the Processing multimedia programming environment.

Why Arduino?

There are many other microcontrollers and microcontroller platforms available for physical computing. Parallax Basic Stamp, Netmedia’s BX-24, Phidgets, MIT’s Handyboard, and many others offer similar functionality. All of these tools take the messy details of microcontroller programming and wrap it up in an easy-to-use package. Arduino also simplifies the process of working with microcontrollers, but it offers some advantage for teachers, students, and interested amateurs over other systems:

Inexpensive – Arduino boards are relatively inexpensive compared to other microcontroller platforms. The least expensive version of the Arduino module can be assembled by hand, and even the pre-assembled Arduino modules cost less than $50
Cross-platform – The Arduino software runs on Windows, Macintosh OSX, and Linux operating systems. Most microcontroller systems are limited to Windows.
Simple, clear programming environment – The Arduino programming environment is easy-to-use for beginners, yet flexible enough for advanced users to take advantage of as well. For teachers, it’s conveniently based on the Processing programming environment, so students learning to program in that environment will be familiar with the look and feel of Arduino
Open source and extensible software- The Arduino software is published as open source tools, available for extension by experienced programmers. The language can be expanded through C++ libraries, and people wanting to understand the technical details can make the leap from Arduino to the AVR C programming language on which it’s based. Similarly, you can add AVR-C code directly into your Arduino programs if you want to.
Open source and extensible hardware – The Arduino is based on Atmel’s ATMEGA8 and ATMEGA168 microcontrollers. The plans for the modules are published under a Creative Commons license, so experienced circuit designers can make their own version of the module, extending it and improving it. Even relatively inexperienced users can build the breadboard version of the module in order to understand how it works and save money.

Happy IoT, Happy Arduino πŸ™‚

2014 in review..Thanks to every one for making my blog successful.

The WordPress.com stats helper monkeys prepared a 2014 annual report for this blog.

Here’s an excerpt:

The concert hall at the Sydney Opera House holds 2,700 people. This blog was viewed about 28,000 times in 2014. If it were a concert at Sydney Opera House, it would take about 10 sold-out performances for that many people to see it.

Click here to see the complete report.

Primefaces 5 example

Here is an example on how to use jsf framework to develop a fully blown JavaEE application. when it comes to jsf all should know its a specification from sun and has been implemented by lot many vendors, some of them are “PrimeFaces”, “RichFaces”, “IceFaces”. The advantage of using JSF is the UI components are directly binded to Managed bean properties(value injection). In this example i want to show how to push data to database and retrieve from database to front end. This example is implemented in “Primefaces5.1”, “Maven”, “MySql”.

<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.jsf.primefaces</groupId>
	<artifactId>PrimeFacesTutorial</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>PrimeFacesTutorial</name>
	<description>PrimeFacesTutorial</description>

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

	<properties>
		<java.version>1.6</java.version>
		<servlet.version>3.0.1</servlet.version>
		<jsf.version>2.2.4</jsf.version>
		<primefaces.version>5.1</primefaces.version>
	</properties>

	<dependencies>
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${servlet.version}</version>
		</dependency>
		<!-- Faces Implementation -->
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-impl</artifactId>
			<version>${jsf.version}</version>
		</dependency>
		<!-- Faces Library -->
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-api</artifactId>
			<version>${jsf.version}</version>
		</dependency>
		<!-- Primefaces Version 5 -->
		<dependency>
			<groupId>org.primefaces</groupId>
			<artifactId>primefaces</artifactId>
			<version>${primefaces.version}</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>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.9</version>
		</dependency>
	</dependencies>

	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<warSourceDirectory>webapp</warSourceDirectory>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
		<finalName>primefaces-tutorial</finalName>
	</build>
</project>

web.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"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>PrimeFaces Web Application</display-name>

	<!-- Change to "Production" when you are ready to deploy -->
	<context-param>
		<param-name>javax.faces.PROJECT_STAGE</param-name>
		<param-value>Development</param-value>
	</context-param>

	<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>client</param-value>
	</context-param>

	<context-param>
		<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
		<param-value>resources.application</param-value>
	</context-param>

	<!-- Welcome page -->
	<welcome-file-list>
		<welcome-file>login.xhtml</welcome-file>
	</welcome-file-list>

	<!-- JSF mapping -->
	<servlet>
		<servlet-name>Faces Servlet</servlet-name>
		<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- Map these files with JSF -->
	<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>*.jsf</url-pattern>
	</servlet-mapping>
	<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>

</web-app>

faces-config.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">
	

</faces-config>

Once done with our configuration files let us write the page from which the operations are done.
login.xhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:p="http://primefaces.org/ui">

<h:head>
	<h:outputStylesheet name="css/custom-styles.css" />
</h:head>
<body>
	<h:form>
		<p:panelGrid columns="2">
			<p:outputLabel value="FirstName"></p:outputLabel>
			<p:inputText value="#{loginBean.firstName}"></p:inputText>

			<p:outputLabel value="LastName"></p:outputLabel>
			<p:inputText value="#{loginBean.lastName}"></p:inputText>

			<p:outputLabel value="Email"></p:outputLabel>
			<p:inputText value="#{loginBean.emailText}"></p:inputText>

			<p:outputLabel value="Password"></p:outputLabel>
			<p:password value="#{loginBean.password}"></p:password>

			<p:commandButton action="#{loginBean.saveValues()}" value="Submit"></p:commandButton>
		</p:panelGrid>

		<p:dataTable var="loginBean" value="#{loginBean.loginBeans}">
			<p:column headerText="First Name">
				<h:outputText value="#{loginBean.firstName}" />
			</p:column>

			<p:column headerText="Last Name">
				<h:outputText value="#{loginBean.lastName}" />
			</p:column>

			<p:column headerText="Email Id">
				<h:outputText value="#{loginBean.emailText}" />
			</p:column>

			<p:column headerText="Password">
				<h:outputText value="#{loginBean.password}" />
			</p:column>
		</p:dataTable>
	</h:form>

</body>
</html>

let us write a DTO in which we hold the data.

/**
 * 
 */
package com.spark.jsf.vo;

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

/**
 * @author Sony
 *
 */
@ManagedBean(name="loginVO")
@SessionScoped
public class LoginBeanVO {

	private String firstName;
	private String lastName;
	private String emailText;
	private String password;
	/**
	 * @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 emailText
	 */
	public String getEmailText() {
		return emailText;
	}
	/**
	 * @param emailText the emailText to set
	 */
	public void setEmailText(String emailText) {
		this.emailText = emailText;
	}
	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}
	/**
	 * @param password the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((emailText == null) ? 0 : emailText.hashCode());
		result = prime * result
				+ ((firstName == null) ? 0 : firstName.hashCode());
		result = prime * result
				+ ((lastName == null) ? 0 : lastName.hashCode());
		result = prime * result
				+ ((password == null) ? 0 : password.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;
		LoginBeanVO other = (LoginBeanVO) obj;
		if (emailText == null) {
			if (other.emailText != null)
				return false;
		} else if (!emailText.equals(other.emailText))
			return false;
		if (firstName == null) {
			if (other.firstName != null)
				return false;
		} else if (!firstName.equals(other.firstName))
			return false;
		if (lastName == null) {
			if (other.lastName != null)
				return false;
		} else if (!lastName.equals(other.lastName))
			return false;
		if (password == null) {
			if (other.password != null)
				return false;
		} else if (!password.equals(other.password))
			return false;
		return true;
	}
	
	
}

Here comes the major part of our code, its our backing bean which controls our jsf page. There are lot many concepts involved in the below code, we achieve dependency injection using @ManagedProperty annotation in the below code we have injected the dao and dto objects to backing bean using @ManagedProperty annotation , also we used ExternalContext object to redirect to the jsf page from managed bean.

/**
 * 
 */
package com.spark.jsf.managed.beans;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import org.primefaces.context.RequestContext;

import com.spark.jsf.dao.impl.LoginSaveDAOImpl;
import com.spark.jsf.vo.LoginBeanVO;
import com.spark.security.EncryptPassword;

/**
 * @author Sony
 *
 */
@ManagedBean(name = "loginBean")
@SessionScoped
public class LoginBean {

	private String firstName;
	private String lastName;
	private String emailText;
	private String password;
	private List<LoginBeanVO> loginBeans = new ArrayList<LoginBeanVO>();

	@ManagedProperty(value = "#{loginVO}")
	private LoginBeanVO loginBeanVO;

	@ManagedProperty(value = "#{loginSaveDao}")
	private LoginSaveDAOImpl loginSaveDAOImpl;

	/**
	 * @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 emailText
	 */
	public String getEmailText() {
		return emailText;
	}

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

	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

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

	/**
	 * @return the loginSaveDAOImpl
	 */
	public LoginSaveDAOImpl getLoginSaveDAOImpl() {
		return loginSaveDAOImpl;
	}

	/**
	 * @param loginSaveDAOImpl
	 *            the loginSaveDAOImpl to set
	 */
	public void setLoginSaveDAOImpl(LoginSaveDAOImpl loginSaveDAOImpl) {
		this.loginSaveDAOImpl = loginSaveDAOImpl;
	}

	/**
	 * @return the loginBeanVO
	 */
	public LoginBeanVO getLoginBeanVO() {
		return loginBeanVO;
	}

	/**
	 * @param loginBeanVO
	 *            the loginBeanVO to set
	 */
	public void setLoginBeanVO(LoginBeanVO loginBeanVO) {
		this.loginBeanVO = loginBeanVO;
	}

	/**
	 * @return the loginBeans
	 */
	public List<LoginBeanVO> getLoginBeans() {
		return loginBeans;
	}

	/**
	 * @param loginBeans the loginBeans to set
	 */
	public void setLoginBeans(List<LoginBeanVO> loginBeans) {
		this.loginBeans = loginBeans;
	}
	
	@PostConstruct
	public void getLoginDetails(){
		
		loginBeans = loginSaveDAOImpl.getLoginBeans();
	}

	public void saveValues() {

		loginBeanVO.setFirstName(firstName);
		loginBeanVO.setLastName(lastName);
		loginBeanVO.setEmailText(emailText);
		EncryptPassword encryptPassword = new EncryptPassword("");
		String encryptedPassword = encryptPassword.encrypt(password);

		loginBeanVO.setPassword(encryptedPassword);
		boolean status = loginSaveDAOImpl.saveCredentialsToDatabase(loginBeanVO);
		
		if(status){
			FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_INFO, "Info", "User details saved successfully !");
			RequestContext.getCurrentInstance().showMessageInDialog(facesMessage);
			populateLoginBeanList();
			ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
		    try {
				ec.redirect(((HttpServletRequest) ec.getRequest()).getRequestURI());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "Failed to Save user, might be user with same email id already exist !");
			RequestContext.getCurrentInstance().showMessageInDialog(facesMessage);
		}
		
	}
	
	public void populateLoginBeanList(){
		loginBeans = loginSaveDAOImpl.getLoginBeans();
	}

}

here our dao layer logic.

/**
 * 
 */
package com.spark.jsf.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

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

import com.spark.jsf.db.DBUtil;
import com.spark.jsf.vo.LoginBeanVO;

/**
 * @author Sony
 *
 */
@ManagedBean(name= "loginSaveDao")
@SessionScoped
public class LoginSaveDAOImpl {

	List<LoginBeanVO> loginBeanVOs;
	
	public boolean saveCredentialsToDatabase(LoginBeanVO loginBeanVO) {
		boolean status = false;
		System.out.println(loginBeanVO.getFirstName() + "  "
				+ loginBeanVO.getLastName() + "  " + loginBeanVO.getPassword());
		Connection connection = DBUtil.getDBConnection();
		System.out.println("Got the connection object: " + connection);
		String sql = "insert into login(first_name,last_name,email_id,password) values(?,?,?,?)";
		if (!checkUserWithEmailExist(connection, loginBeanVO.getEmailText())) {
			try {
				PreparedStatement preparedStatement = connection
						.prepareStatement(sql);
				preparedStatement.setString(1, loginBeanVO.getFirstName());
				preparedStatement.setString(2, loginBeanVO.getLastName());
				preparedStatement.setString(3, loginBeanVO.getEmailText());
				preparedStatement.setString(4, loginBeanVO.getPassword());
				preparedStatement.execute();
				System.out.println("--------------- Values Saved to Database ---------------");
				status = true;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} else {
			System.out
					.println("------------ user already exist with the same email id ---------------");
			status = false;
		}
		return status;
	}

	private boolean checkUserWithEmailExist(Connection connection,
			String emailText) {
		String sql = "select * from login where email_id = ?";
		boolean userExist = false;
		try {
			PreparedStatement preparedStatement = connection
					.prepareStatement(sql);
			preparedStatement.setString(1, emailText);
			ResultSet resultSet = preparedStatement.executeQuery();
			while (resultSet.next()) {
				userExist = true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return userExist;
	}
	
	public List<LoginBeanVO> getLoginBeans(){
		loginBeanVOs = new ArrayList<LoginBeanVO>();
		String sql = "select * from login";
		Connection connection = DBUtil.getDBConnection();
		try {
			PreparedStatement preparedStatement = connection
					.prepareStatement(sql);
			ResultSet resultSet = preparedStatement.executeQuery();
			while (resultSet.next()) {
				LoginBeanVO beanVO = new LoginBeanVO();
				beanVO.setFirstName(resultSet.getString("first_name"));
				beanVO.setLastName((resultSet.getString("last_name")));
				beanVO.setEmailText((resultSet.getString("email_id")));
				beanVO.setPassword((resultSet.getString("password")));
				loginBeanVOs.add(beanVO);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return loginBeanVOs;
	}
}

The speciality of this example is that i have implemented the PBEWithMD5AndDES algorith for encrypting and decrypting the passwords for security purpose.
SecurityUtils.java

/**
 * 
 */
package com.spark.security;

import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

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

	public static Cipher dCipher, eCipher;
	public SecurityUtils(String helperString) {
		//b-bit salt
		byte[] salt = {(byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32,
                (byte) 0x56, (byte) 0x34, (byte) 0xE3, (byte) 0x03};
		
		// iteration count
		int iterationCount = 19;
		try {
			// generating a temporary key, Encryptinng with DES using a pass key
			
			KeySpec keySpec = new PBEKeySpec(helperString.toCharArray(), salt, iterationCount);
			SecretKey secretKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
			
			eCipher = Cipher.getInstance(secretKey.getAlgorithm());
			dCipher = Cipher.getInstance(secretKey.getAlgorithm());
			
			AlgorithmParameterSpec algorithmParameterSpec = new PBEParameterSpec(salt, iterationCount);
			
			eCipher.init(Cipher.ENCRYPT_MODE, secretKey, algorithmParameterSpec);
			dCipher.init(Cipher.DECRYPT_MODE, secretKey, algorithmParameterSpec);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

EncryptPassword.java

/**
 * 
 */
package com.spark.security;

import java.io.UnsupportedEncodingException;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;

/**
 * @author Sony
 *
 */
public class EncryptPassword extends SecurityUtils{

	public EncryptPassword(String helperString) {
		super(helperString);
	}
	
	public String encrypt(String password){
		 try {
             // Encode the string into bytes using utf-8
             byte[] utf8 = password.getBytes("UTF8");
             // Encrypt
             byte[] enc = eCipher.doFinal(utf8);
             // Encode bytes to base64 to get a string
             return new sun.misc.BASE64Encoder().encode(enc);

      } catch (BadPaddingException e) {
    	  e.printStackTrace();
      } catch (IllegalBlockSizeException e) {
    	  e.printStackTrace();
      } catch (UnsupportedEncodingException e) {
    	  e.printStackTrace();
      }
      return null;
	}
}

DecryptPassword.java

/**
 * 
 */
package com.spark.security;

/**
 * @author Sony
 *
 */
public class DecryptPassword extends SecurityUtils {

	public DecryptPassword(String helperString) {
		super(helperString);
	}

	public String decrypt(String encryptedPassword) {
		try {
			// Decode base64 to get bytes
			byte[] dec = new sun.misc.BASE64Decoder()
					.decodeBuffer(encryptedPassword);
			// Decrypt
			byte[] utf8 = dCipher.doFinal(dec);
			// Decode using utf-8
			return new String(utf8, "UTF8");
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

}

Let us have a helper class which will create a connection object and return DAO layer.

/**
 * 
 */
package com.spark.jsf.db;

import java.sql.Connection;
import java.sql.DriverManager;

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

	private static Connection connection = null;
	
	private DBUtil(){
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Connection getDBConnection(){
		if(connection == null){
			return new DBUtil().getConnection();
		}else{
			return connection;
		}
	}

	/**
	 * @return the connection
	 */
	public Connection getConnection() {
		return connection;
	}

	/**
	 * @param connection the connection to set
	 */
	public  void setConnection(Connection connection) {
		this.connection = connection;
	}
	
}

finally the output is as below.

ui