RSS

RMI vs JMS Clarification


Most of the developers and system designers may know what is RMI and what is JMS but when they come to develop or design the real world application then they are in trouble with which one to choose. So I thought its better to publish some thoughts on this.

Lets start with the regular descriptions.

RMI – Remote Method Invocation

rmi-5

  1. Synchronous communication – Request initiator wait for the response. In order to archive this RMI service need to be up at the time of communication.
  2. Tightly coupled – Requesting system is couple to the declared interface in RMI service.
  3. Unreliable communication – If something happen in-between the communication you will loose the request and you have to handle those in application level.

Advantages :
Easy to start by writing the simple interface and the implementation.

Disadvantages :
Can use only the java supported platforms.
Cannot use the code out of the scope of java.
Security issues need to be monitored more closely.

Using RMI :
If you have process with heavy computation and need more computation power to improve the performance then you can go with RMI because it will give you the computation power on simple method call.

JMS – Java Message Service

Topic – Publish and subscribe model

publish_subscribe
Queue – Load balancing model

qs-multiple-consumers

  1.  Asynchronous communication – Request initiator is not going to wait for the response and it just send the message out then close the connection. No need to have backing service up at the time of communication.
  2. Loosely coupled – It is not tight to the service as RMI. You can use any kind of data format to communicate via message QUEUEs and TOPICs. ex/ XML, JSON
  3. Reliable communication – This is not like RMI because this communication has message broker in-between the systems and message broker has capability of error handling and the persistent of the messages and handover them to the responsible party.

Advantages :
Due to asynchronous messaging, All the modules don’t need to be up for the application to function as a whole.

Disadvantages :
Extra overhead on setup and maintain the message broker

Using JMS :
If you have any process which will be getting heavy request load and that can be run asynchronously then go for JMS Queue implementation and run them separately and communicate via the queue. The next point is if you have a process that need to send the data to many downstream applications then go for JMS Topic implementation.

By the way remember this, There is no such a thing as bad technology only bad choice.

 
Leave a comment

Posted by on April 19, 2016 in java, jms, RMI

 

Tags: , , , , ,

Apache-Camel with Java (Integration)

Apache-Camel with Java (Integration)

Apache camel is very useful routing implementation. If you involve with some integration then you will realize how it is solving your problems. When technology evolves Integration will come to the picture as follows.

A company has a software, which runs in old technology. The company wants to go for another tool, which is going to work on latest platforms and technology. But still the company need to get integrated with the old system because new tool depends on the company data, which is in old system. In this case we need to come up with good solution that can be bridge to the communication. In the industry we used Message Queues to make realtime communication so if it is realtime we can use the message queue in between the two systems.

Above sample is really simple scenario but think about if you have number of systems in downstream to communicate, then you will need proper routing mechanism otherwise you will end up with multiple endpoints, which is doing the same thing (duplicate work). Apache Camel is open source tool for routing data with JAVA application.

Apache Camel

I have created simple adapter with apache camel routes. It explains how to use camel routes in implementation level. This is a maven project produce the war file, which you can deploy on apache tomcat and subscribe to the queue. ( I hope you have understanding of use Spring Boot and Spring Profile) This sample doesn’t contain JMS client to publish messages so I’m going to use the ActiveMQ console.

You can clone the whole project in following location. https://github.com/malalanayake/camel-sample

In code level you need to create the camel route and camel message processor as you wish. See the following rout configuration and sample message processor implementation.

Follow the instruction to deploy and run the adapter.

Start Apache ActiveMQ and create the queue as “sample_queue” then change the application-dev.properties in resource folder. I used spring profile for switch the context so you need to update the default profile as follows in application.properties

Now build the WAR file and deploy the WAR on Apache Tomcat. Then you will see the WAR adapter is going to subscribe to the sample_queue

activemq

Now go to operation and do “Send To“. Now your adapter is going to consume the given message. See the logs in tomcat console.

send

 

 

after_sent

 

console

 

after_consume

The routing mechanism and routing patterns might vary with the problem domain. However the implementation perspective is similar. For example subscribe to message queue and then route the message to endpoints. I hope you got some idea how to use the camel routes.

Enjoy the integration.

 
1 Comment

Posted by on October 11, 2015 in integration, java, spring

 

Tags: , , , ,

Understanding Java pass by value


I think most of the people they are confused with this concept because it is appearing in different angles. First thing I have to say that Java is pass by Value not pass by reference. I’ll show the example to clear the concept.

First of all I’ll show the sample code, then you can see the confused point that you will drive to think that java is pass by reference. you can checkout the full source here.

package sample.passby.value;

/**
 * Point class
 * 
 * @author malalanayake
 *
 */
public class Point {
	private int x;
	private int y;

	public Point(int x, int y) {
		this.x = x;
		this.y = y;
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

}
package sample.passby.value;

/**
 * Demonstration of Java pass by value
 * 
 */
public class App {
	public static void main(String[] args) {
		int xOrginal = 0, yOriginal = 0;
		System.out.println("Original Coordinates:" + xOrginal + "," + yOriginal);
		App.getNextCoordinates(xOrginal, yOriginal);
		System.out.println("After modification of Coordinates:" + xOrginal
				+ "," + yOriginal);

		Point pOriginal = new Point(0, 0);
		System.out.println("Original Point:" + pOriginal.getX() + ","
				+ pOriginal.getY());
		App.getNextCoordinates(pOriginal);
		System.out.println("After modification of Point:" + pOriginal.getX()
				+ "," + pOriginal.getY());

	}

	public static void getNextCoordinates(int x, int y) {
		x = 12;
		y = 15;
	}

	public static void getNextCoordinates(Point point) {
		point.setX(12);
		point.setY(15);
	}
}

Output:
Original Coordinates:0,0
After modification of Coordinates:0,0
Original Point:0,0
After modification of Point:12,15

So you can see in the above example if I pass the primitives then it is not going to change the values. But if I pass the object type then if i change something on that it will reflect. The understanding point is Java every time pass by value and if it is primitive then it is just pass the value to the given argument and nothing will reflect. See the following image for understanding.
PassByValue (1)

But if we pass the Object type then java pass the “reference by value”. This is the tricky point that we need to understand.
PassByValue (2)

So you can see if we pass some Object type to some function actually its going to pass the pointer to that Object. That means if we change some thing on that it will be reflect on that. But be aware about this, You cannot change the pointer which is not in the scope. As an example if you do following coding in getNextCoordinates(Point point) method it will not reflecting anything on the original object because it is going to change the pointer of the object which is under that scope not the original object that passed to the function.

public static void getNextCoordinates(Point point) {
                point = new Point(12,15);
}
 
Leave a comment

Posted by on December 8, 2014 in java

 

Tags: , ,

Comparator and Comparable interfaces in Java


c4c3

Comparator and Comparable interfaces are heavily used in the Java development to manage the sorting of the collections. This approach will achieve the software engineering goals such as extensibility, reusability, modularity etc. In this post I like to explain this mechanism of how to use comparator and comparable interfaces. First thing is we are going to use the Collections API for sorting which is provided by Java. So we have to expose sorting comparison logic without exposing the internal structure of our custom implementation.Here you can download the source.

Lets look at how to use Comparable interface.

As an example I have Employee class which is created by me and need to sort the collection of employees according to the employee age.

  • First we need to implement the Comparable interface in Employee class and override the compareTo method
  • Then we can pass the employee collection to the Collections.sort() API to do the sorting.
  • Underneath what will happen Collections.sort() method will access the compareTo implementation and get the decision according to the return value.

See the code sample below to get clear understanding.

package sample.common;

/**
 * Employee Class
 *
 * @author malalanayake
 *
 */
public class Employee implements Comparable<Employee> {
	private int id;
	private String name;
	private int age;
	private int salary;

	public Employee(int id, String name, int age, int salary) {
		this.id = id;
		this.name = name;
		this.age = age;
		this.salary = salary;
	}

	public int getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public int getSalary() {
		return salary;
	}

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

	public int compareTo(Employee o) {
		if (o.getAge() == this.age) {
			return 0;
		} else if (o.getAge() > this.age) {
			return -1;
		} else {
			return 1;
		}
	}

	@Override
	public String toString() {
		return "[Employee ID:" + this.getId() + " Name:" + this.getName()
				+ " Age:" + this.getAge() + " Salary:" + this.getSalary() + "]";
	}

}
package sample.app;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import comparator.sample.app.SalaryComparator;
import sample.common.Employee;

/**
 * Application Class
 *
 * @author malalanayake
 *
 */
public class App {
	public static void main(String[] args) {
		List<Employee> employees = new ArrayList<Employee>();

		Employee emp_dinuka = new Employee(101, "Dinuka", 27, 95000);
		employees.add(emp_dinuka);

		Employee emp_malalanayake = new Employee(100, "Malalanayake", 27, 85000);
		employees.add(emp_malalanayake);

		Employee emp_Thanuja = new Employee(305, "Thanuja", 23, 150000);
		employees.add(emp_Thanuja);

		Employee emp_Damith = new Employee(204, "Damith", 20, 75000);
		employees.add(emp_Damith);

		System.out.println("=======Before Sorting=====");
		for (Employee emp : employees) {
			System.out.println(emp.toString());
		}

		Collections.sort(employees);
		System.out.println("=======After Sorting=====");
		for (Employee emp : employees) {
			System.out.println(emp.toString());
		}
	}
}

You can see in the above case we can have only one sorting logic over the employee class. Lets think about sometimes if I need to sort the Employee by their salaries and sometimes I need to sort by their age. Then you can see we don’t have space to put that logic in my Employee class because already I have method implementation according to the age. In this kind of situation Comparator comes to the picture to solve the problem.

Lets look at how to use Comparator

  • So first you have to have comparator implementation class. In above case I have created SalaryComparator class which is provide the salary comparison.
  • Then you can pass the employee collection to overloaded method in collections api to sort the given collection according to the given comparator.
package comparator.sample.app;

import java.util.Comparator;

import sample.common.Employee;

/**
 * Salary Comparator
 *
 * @author malalanayake
 *
 */
public class SalaryComparator implements Comparator<Employee> {

	public int compare(Employee o1, Employee o2) {
		if (o1.getSalary() > o2.getSalary()) {
			return 1;
		}

		if (o1.getSalary() < o2.getSalary()) {
			return -1;
		}
		return 0;
	}

}
package sample.app;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import comparator.sample.app.SalaryComparator;
import sample.common.Employee;

/**
 * Application Class
 *
 * @author malalanayake
 *
 */
public class App {
	public static void main(String[] args) {
		List<Employee> employees = new ArrayList<Employee>();

		Employee emp_dinuka = new Employee(101, "Dinuka", 27, 95000);
		employees.add(emp_dinuka);

		Employee emp_malalanayake = new Employee(100, "Malalanayake", 27, 85000);
		employees.add(emp_malalanayake);

		Employee emp_Thanuja = new Employee(305, "Thanuja", 23, 150000);
		employees.add(emp_Thanuja);

		Employee emp_Damith = new Employee(204, "Damith", 20, 75000);
		employees.add(emp_Damith);

		SalaryComparator comparator = new SalaryComparator();
		Collections.sort(employees, comparator);
		System.out.println("=======After Sorting By Salary=====");
		for (Employee emp : employees) {
			System.out.println(emp.toString());
		}
	}
}

So If you have multiple sorting logics then you have to go for the Comparator because then only you can have multiple logics. Otherwise you can encapsulate the logic inside your custom implementation class by using the Comparable interface. I hope you got the idea of how to use the comparator and comparable interfaces.

 
Leave a comment

Posted by on December 5, 2014 in java, Other

 

Tags: , , , ,

JSP, Servlet, Scope variables and Init Parameters


If you are getting involved in Java EE development you have to have good knowledge about the JSP and Servlets. Servlets are server side components that provide a powerful mechanism for developing server side programs. JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pages based on HTML, XML, or other document types.

First look at how request and response handle in servlet container. Servlet container create one instance from each servlet but its going to serve for multiple threads. See the following diagram. You can see HTTP Request comes to the container and it will create the HTTPServletRequest, HTTPServletResponse objects. Finally put those two objects in new thread and let the thread to access the instance of specified servlet.

Servlet Conatiner

According to the above process you can see we have to be careful of the thread safety of instance variable in servlet. Because each and every thread is gong to access the single Servlet instance. If you have some instance variable in the servlet which is going to modify with in the thread you have to make it thread safe.

Look at the Servlet life cycle

init() – this method is going to run only one time
service() – this method is going to run each time the request comes to the servlet. And it will identify either doGet or doPost to execute according to the request.

Servlet Life Cycle

JSP life cycle is same as Servlet, only additional thing is its going to translate to the servlet. Ultimately its acts as Servlet. JSP you can override two methods which is jspInit() and jspDestroy(). But you cannot override the jspService() method.

Lets talk about Scope variables.

1. Application Context  – In other words we can say this is servletContext. You can use servletContext to store the global data which is going to share through out the application. This is not thread safe. You can easily access this context as follows.

request.getServletContext();
request.getServletContext().setAttribute("attribute_name","value");

2. Session Context – Session management is handling by the servlet container and you can store the user specific data on session. This object is not thread safe.

request.getSession(); //going to create the session if session is not exist.
request.getSession(false); // Not going to create the session.

3. Request Attributes – You can use this scope to carry the data in server side from one resource to another. As an example while you are doing the request forwarding. This is thread safe because one request is handle by one thread.

request.setAttribute("attribute_name","value");
request.getAttribute("attribute_name"); // return the Object you have to cast it

Config Parameters

We have two different types of init parameters. One is available for the whole application and the other one is only for specific servlet. These parameters are deployment time constants. That means once the application is deployed you cannot change it. These parameters are going to declare in web.xml

<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" version="3.0">
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/config/springmvc-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <context-param>
  	<param-name>ApplicationName</param-name>
  	<param-value>ApplicationName</param-value>
  </context-param>
</web-app>

1. Global init parameter 

getServletContext().getInitParameter("ApplicationName");

2. Specified int parameter

getServletConfig().getInitParameter("contextConfigLocation");
 
Leave a comment

Posted by on October 10, 2014 in java, web

 

Tags: , , , ,

Selecting proper data structures for the realtime problems


As a software engineer you have to have a proper understanding about data structures and the corresponding implementations. In real world application development you need to think about the efficiency of the operations and it should fit for the entire domain that the solution is addressing. So in this blog post Im going to explain some of the data structures implemented in java.

Look at the following class hierarchy.

collections

1. LinkedList –  Use the linked list If you need to maintain the list which is no need random access to the values and needed frequent insertions and deletions.
Insertion and deletion is O(1) and access the (k)th element is O(n).
But remember LinkedList is not thread safe.

2. ArrayList –  Use the array list if you need the random access to the values frequently and same as you don’t need frequent insertion and remove operations.
Access the (k)th element is O(1) and insertion and deletion is O(n).
Same as LinkedList remember ArrayList is not thread safe.

3. Vector –  When you need to maintain thread safety over the ArrayList use the Vector. If you don’t need any synchronization on each and every operations you have to go for ArrayList otherwise it will give bad performance impact on each operation.

4. PriorityQueue –  We know that queue is a first come first serve basis but some times we need to get the things according to the priority. So if you have that kind of problem use the priority queue. But remember PriorityQueue is not thread safe.

5. HashSet –  It is not maintaining the duplicates. When you need to maintain the unique list of objects you can use the HashSet. HashSet allows the NULL Objects but it is not maintain the insertion sequence. If you need to maintain the insertion sequence you have to use the LinkedHashSet.

6. TreeSet –  Same as HashSet this data structure maintain the duplicate free collection and additionally its provide the sorted order of the elements.TreeSet is not allow the NULL objects. Guarantees log(n) time cost for the basic operations add, remove and contains.

7. HashTable –  This data structure is useful when you need to do the insertion, deletion and the quick access to the given element in constant time. All operations are in O(1).Hash tables are not maintain the insertion sequence. I would like to explain the HashTable little bit in depth because this is commonly using in the industry. As an example a router table. When a packet has to be routed to a specific IP address, the router has to determine the best route by querying the router table in an efficient manner.

To use the Hash tables you have to implement the equals(), hashCode() functions the Object type that you are going to store in the HashTable.
hashCode() – as a best practice you have to consider all attributes in the object to generate the hash code. See the following example.

public class Employee {
    int        employeeId;
    String     name;
    Department dept;
 
    // other methods would be in here 
 
    @Override
    public int hashCode() {
        int hash = 1;
        hash = hash * 17 + employeeId;
        hash = hash * 31 + name.hashCode();
        hash = hash * 13 + (dept == null ? 0 : dept.hashCode());
        return hash;
    }
}

Once you call the insert method in the hash table it will calculate the hash value and then store the the data according to the hash value.

 int hashValue = hashCode % hash_table_size;

There are several ways to handle the collisions in hash table.
1. Separate Chaining – Maintain the list in each slot. If there are two objects with same hash value it is going to store in that list. This implementation has extra overhead to maintain the list. Total Performance is depend on the number of elements in the list.

2. Open Addressing – In this approach it is find the next available slot according to the probing function.
Linear prob – h(x), h(x)+1, h(x)+2, h(x)+3,..
Quadratic prob – h(x), h(x)+1^2, h(x)+2^2, h(x)+3^2,..
Double hashing – h(x), h(x)+1*h'(x), h(x)+2*h'(x), h(x)+3*h'(x),..

Delete elements in hash table – If hash table is use open addressing then it is logically delete the value from the table by setting a flag.

Performance of the hash table is denoted by alpha load factor.

 alpha = number_of_elements/table_size;

If hash table is filled we need to do the rehashing. Rehashing is done according to the load factor. If load factor reaches to some level we need to do the rehashing. This is the only disadvantage of the HashTable.

8. HashMap –  Hash map is used when you need to store the elements as key, value pairs.In hash map you cannot duplicate the key but you can duplicate the value with different key. This is not maintain the insertion sequence. If you need to maintain the insertion sequence you have to use the LinkedHashMap. Remember HasMap is not thread safe if you need thread safety over HashMap you have to use the ConcurrentHashMap

8. TreeMap –  If you need to maintain the key, value pairs in sorted order this is the data structure suits for that operation. Its guarantees that the given key value pairs arrange in sorted order according to the compareTo() method in Object type which is stored in TreeMap.

 
Leave a comment

Posted by on September 26, 2014 in data-structures, java, Other

 

Tags: , ,

Spring MVC with Hibernate


These days spring is most popular framework in the industry because it has lots of capabilities. Most probably large scale projects are using Spring as DI(Dependency Injection) framework with supporting of AOP(Aspect oriented programming) and Hibernate as ORM(Object relational mapping) framework in their backend. There is another cool feature came along with spring which is provide the MVC(Model View Control) architectural pattern.

In this post I’m going to focus on the spring MVC, DI, AOP. I’m not going to explain the hibernate mappings because it is in another context.

Lets look at the spring MVC request handling architecture.
Spring MVC

In the above diagram you can see there is controller class which is responsible for the request mediation. As a good practice we are not writing any business logic on this controller. Spring MVC is front end architecture and we have to have the layered architecture to separate the logic by concern. So thats why we use the backend service which is provide the business logic.

Lets go for the implementation of simple sample project with SpringMVC and Hibernate. I’m using maven project with the eclipse. You can download the full source of the project from here
Screen Shot 2014-07-26 at 1.03.03 PM

I have created layers by separating the concerns.
1. Controller layer (com.app.spring.contoller)
2. Service layer (com.app.spring.service)
3. Data Access layer (com.app.spring.dao)
4. Persistance layer (com.app.spring.model)

First look at the Model class Customer. This class is the one going to map with the DB table.

package com.app.spring.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * 
 * @author malalanayake
 *
 */
@Entity
@Table(name = "CUSTOMER")
public class Customer {

	@Id
	@Column(name = "id")
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int id;
	private String name;
	private String address;

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public int getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	@Override
	public String toString() {
		return "id=" + id + ", name=" + name + ", address=" + address;
	}
}

Data Access Object class – CustomerDAOImpl.java
In each layer we need to have interfaces which is provided the functionality and the concert implementation classes. So we have CustomerDAO Interface and CustomerDAOImpl class as follows.

package com.app.spring.dao;

import java.util.List;

import com.app.spring.model.Customer;

/**
 * 
 * @author malalanayake
 *
 */
public interface CustomerDAO {

	public void addCustomer(Customer p);

	public void updateCustomer(Customer p);

	public List<Customer> listCustomers();

	public Customer getCustomerById(int id);

	public void removeCustomer(int id);
}

package com.app.spring.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.app.spring.dao.CustomerDAO;
import com.app.spring.model.Customer;

/**
 * 
 * @author malalanayake
 *
 */
@Repository
public class CustomerDAOImpl implements CustomerDAO {

	private static final Logger logger = LoggerFactory.getLogger(CustomerDAOImpl.class);

	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sf) {
		this.sessionFactory = sf;
	}

	@Override
	public void addCustomer(Customer p) {
		Session session = this.sessionFactory.getCurrentSession();
		session.persist(p);
		logger.info("Customer saved successfully, Customer Details=" + p);
	}

	@Override
	public void updateCustomer(Customer p) {
		Session session = this.sessionFactory.getCurrentSession();
		session.update(p);
		logger.info("Customer updated successfully, Person Details=" + p);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Customer> listCustomers() {
		Session session = this.sessionFactory.getCurrentSession();
		List<Customer> customersList = session.createQuery("from Customer").list();
		for (Customer c : customersList) {
			logger.info("Customer List::" + c);
		}
		return customersList;
	}

	@Override
	public Customer getCustomerById(int id) {
		Session session = this.sessionFactory.getCurrentSession();
		Customer c = (Customer) session.load(Customer.class, new Integer(id));
		logger.info("Customer loaded successfully, Customer details=" + c);
		return c;
	}

	@Override
	public void removeCustomer(int id) {
		Session session = this.sessionFactory.getCurrentSession();
		Customer c = (Customer) session.load(Customer.class, new Integer(id));
		if (null != c) {
			session.delete(c);
		}
		logger.info("Customer deleted successfully, Customer details=" + c);
	}

}

If we are using the hibernate we have to have start the transaction before each operation and commit the transaction after the work done. If we are not doing these things our data is not going to persist in DB. But you can see I have not started transaction in explicitly. This is the point that AOP come to the picture. Lets look at the service layer you can see I have declare the @Transactional annotation. That means I wanted to start the transaction before going to execute the operations. This transaction handling mechanism is going to handle by the Spring frame work. We don’t want to worry about that. Only we need to concern about the spring configurations.

package com.app.spring.service;

import java.util.List;

import com.app.spring.model.Customer;

/**
 * 
 * @author malalanayake
 *
 */
public interface CustomerService {

	public void addCustomer(Customer p);

	public void updateCustomer(Customer p);

	public List<Customer> listCustomers();

	public Customer getCustomerById(int id);

	public void removeCustomer(int id);

}
package com.app.spring.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.app.spring.dao.CustomerDAO;
import com.app.spring.model.Customer;
import com.app.spring.service.CustomerService;

/**
 * 
 * @author malalanayake
 *
 */
@Service
public class CustomerServiceImpl implements CustomerService {

	private CustomerDAO customerDAO;

	public void setCustomerDAO(CustomerDAO customerDAO) {
		this.customerDAO = customerDAO;
	}

	@Override
	@Transactional
	public void addCustomer(Customer c) {
		this.customerDAO.addCustomer(c);
	}

	@Override
	@Transactional
	public void updateCustomer(Customer c) {
		this.customerDAO.updateCustomer(c);
	}

	@Override
	@Transactional
	public List<Customer> listCustomers() {
		return this.customerDAO.listCustomers();
	}

	@Override
	@Transactional
	public Customer getCustomerById(int id) {
		return this.customerDAO.getCustomerById(id);
	}

	@Override
	@Transactional
	public void removeCustomer(int id) {
		this.customerDAO.removeCustomer(id);
	}

}

Now lock at the servlet-context.xml this file is the most important part in the spring framework.

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

	<!-- Enables the Spring MVC annotations ex/ @Controller -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving 
		up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources 
		in the /WEB-INF/views directory -->
	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>

	<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<beans:property name="url"
			value="jdbc:mysql://localhost:3306/TestDB" />
		<beans:property name="username" value="root" />
		<beans:property name="password" value="root123" />
	</beans:bean>

	<!-- Hibernate 4 SessionFactory Bean definition -->
	<beans:bean id="hibernate4AnnotatedSessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<beans:property name="dataSource" ref="dataSource" />
		<beans:property name="annotatedClasses">
            <beans:list>
                <beans:value>com.app.spring.model.Customer</beans:value>
            </beans:list>
        </beans:property>
		<beans:property name="hibernateProperties">
			<beans:props>
				<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
				</beans:prop>
				<beans:prop key="hibernate.show_sql">true</beans:prop>
				<beans:prop key="hibernate.hbm2ddl.auto">update</beans:prop>
			</beans:props>
		</beans:property>
	</beans:bean>
	
	<!-- Inject the transaction manager  -->
	<tx:annotation-driven transaction-manager="transactionManager"/>
	<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
	</beans:bean>
	
	<!-- Inject the instance to customerDAO reference with adding sessionFactory -->
	<beans:bean id="customerDAO" class="com.app.spring.dao.impl.CustomerDAOImpl">
		<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
	</beans:bean>
	<!-- Inject the instance to service reference with adding customerDao instance -->
	<beans:bean id="customerService" class="com.app.spring.service.impl.CustomerServiceImpl">
		<beans:property name="customerDAO" ref="customerDAO"></beans:property>
	</beans:bean>
	<!-- Set the package where the annotated classes located at ex @Controller -->
	<context:component-scan base-package="com.app.spring" />


</beans:beans>

Look at the following two three lines. We are going to discuss about the dependency injection.

<beans:bean id="customerDAO" class="com.app.spring.dao.impl.CustomerDAOImpl">
		<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
	</beans:bean>
	<!-- Inject the instance to service reference with adding customerDao instance -->
	<beans:bean id="customerService" class="com.app.spring.service.impl.CustomerServiceImpl">
		<beans:property name="customerDAO" ref="customerDAO"></beans:property>
	</beans:bean>

In our CustomerDAOImpl class we have the reference of sessionFactory but we are not creating any instance of session factory rather having setter method for that. So that means some how we need to pass the reference to initiate the session factory. To archive that task we need to say that spring framework to create the instance of sessionFactory. If you follow the configuration above you can see how I declared that.

Another thing is if you declare something as property that means it is going to inject the instance by using setter method and you have to have setter method for that particular reference (Go and see the CustomerDAOImpl class).

Lets look at CustomerServiceImpl class, I have declare the CustomerDAO reference with the setter method. So that means we can inject the CuatomerDAOImpl reference same procedure as we did for the CustomerDAOImpl class.

It is really easy but you have to set the configuration properly.

Deployment descriptor web.xml
You have to set the context configuration as follows.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>
	
	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
		
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

</web-app>

Controller class

package com.app.spring.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.app.spring.model.Customer;
import com.app.spring.service.CustomerService;

/**
 * 
 * @author malalanayake
 *
 */
@Controller
public class CustomerController {

	private CustomerService customerService;

	@Autowired(required = true)
	@Qualifier(value = "customerService")
	public void setPersonService(CustomerService cs) {
		this.customerService = cs;
	}

	@RequestMapping(value = "/customers", method = RequestMethod.GET)
	public String listCustomers(Model model) {
		model.addAttribute("customer", new Customer());
		model.addAttribute("listCustomers", this.customerService.listCustomers());
		return "customer";
	}

	// For add and update person both
	@RequestMapping(value = "/customer/add", method = RequestMethod.POST)
	public String addCustomer(@ModelAttribute("customer") Customer c) {

		if (c.getId() == 0) {
			// new person, add it
			this.customerService.addCustomer(c);
		} else {
			// existing person, call update
			this.customerService.updateCustomer(c);
		}

		return "redirect:/customers";

	}

	@RequestMapping("/customer/remove/{id}")
	public String removeCustomer(@PathVariable("id") int id) {

		this.customerService.removeCustomer(id);
		return "redirect:/customers";
	}

	@RequestMapping("/customer/edit/{id}")
	public String editCustomer(@PathVariable("id") int id, Model model) {
		model.addAttribute("customer", this.customerService.getCustomerById(id));
		model.addAttribute("listCustomers", this.customerService.listCustomers());
		return "customer";
	}

}

Now I’m going to talk about MVC configuration. Look at controller class. I have declare the request mappings by using the annotation @RequestMapping. This is how we redirect the request to the particular service which is backing on service layer. Then we need to inject the data to the model and send that model to the view.

You can see in our project structure we have customer.jsp on /WEB-INF/views folder. We need to let the view resolver to know that our views are located at this folder. That is why we are doing the following configuration.

<!-- Resolves views selected for rendering by @Controllers to .jsp resources 
		in the /WEB-INF/views directory -->
	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>

See the CustomerController class that I have return the string like “customer”.

@RequestMapping(value = "/customers", method = RequestMethod.GET)
	public String listCustomers(Model model) {
		model.addAttribute("customer", new Customer());
		model.addAttribute("listCustomers", this.customerService.listCustomers());
		return "customer";
	}

Once I return the string “customer” spring frame work knows it is a view name. Then it will pic the view as follows according to the configuration.
/WEB-INF/views/customer.jsp

Finally I have used the JSTL tags, spring core and spring form tags in customer.jsp to represent the data came from model class.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ page session="false"%>
<html>
<head>
<title>Manage Customer</title>
<style type="text/css">
.tg {
	border-collapse: collapse;
	border-spacing: 0;
	border-color: #ccc;
}

.tg td {
	font-family: Arial, sans-serif;
	font-size: 14px;
	padding: 10px 5px;
	border-style: solid;
	border-width: 1px;
	overflow: hidden;
	word-break: normal;
	border-color: #ccc;
	color: #333;
	background-color: #fff;
}

.tg th {
	font-family: Arial, sans-serif;
	font-size: 14px;
	font-weight: normal;
	padding: 10px 5px;
	border-style: solid;
	border-width: 1px;
	overflow: hidden;
	word-break: normal;
	border-color: #ccc;
	color: #333;
	background-color: #8FBC8F;
}

.tg .tg-4eph {
	background-color: #f9f9f9
}
</style>
</head>
<body>
	<h1>Manage Customers</h1>

	<c:url var="addAction" value="/customer/add"></c:url>

	<form:form action="${addAction}" commandName="customer">
		<table>
			<c:if test="${!empty customer.name}">
				<tr>
					<td><form:label path="id">
							<spring:message text="ID" />
						</form:label></td>
					<td><form:input path="id" readonly="true" size="8"
							disabled="true" /> <form:hidden path="id" /></td>
				</tr>
			</c:if>
			<tr>
				<td><form:label path="name">
						<spring:message text="Name" />
					</form:label></td>
				<td><form:input path="name" /></td>
			</tr>
			<tr>
				<td><form:label path="address">
						<spring:message text="Address" />
					</form:label></td>
				<td><form:input path="address" /></td>
			</tr>
			<tr>
				<td colspan="2"><c:if test="${!empty customer.name}">
						<input type="submit"
							value="<spring:message text="Edit Customer"/>" />
					</c:if> <c:if test="${empty customer.name}">
						<input type="submit" value="<spring:message text="Add Customer"/>" />
					</c:if></td>
			</tr>
		</table>
	</form:form>
	<br>
	<h3>Customer List</h3>
	<table class="tg">
		<tr>
			<th width="80">Customer ID</th>
			<th width="120">Customer Name</th>
			<th width="120">Customer Address</th>
			<th width="60">Edit</th>
			<th width="60">Delete</th>
		</tr>
		<c:if test="${!empty listCustomers}">
			<c:forEach items="${listCustomers}" var="customer">
				<tr>
					<td>${customer.id}</td>
					<td>${customer.name}</td>
					<td>${customer.address}</td>
					<td><a href="<c:url value='/customer/edit/${customer.id}' />">Edit</a></td>
					<td><a
						href="<c:url value='/customer/remove/${customer.id}' />">Delete</a></td>
				</tr>
			</c:forEach>
		</c:if>
	</table>

</body>
</html>

Now build and deploy the war on tomcat and go to the following url http://localhost:8080/SampleSpringMVCHibernate/customers

Screen Shot 2014-07-26 at 6.29.42 PM
Screen Shot 2014-07-26 at 6.31.10 PM
Screen Shot 2014-07-26 at 6.31.24 PM

Advantages of Dependency injection
1. Loosely couple architecture.
2. Separation of responsibility.
3. Configuration and code is separate.
4. Using configuration, a different implementation can be supplied without changing the dependent code.
5. Testing can be performed using mock objects.

Advantages of using Object relational mapping framework
1. Business code access objects rather than DB tables.
2. Hides details of SQL queries from OO logic.
3. Baking by JDBC
4. No need to play with database implementation.
5. Transaction management and automatic key generation.
6. Fast development of application.

I hope you got the idea about how spring framework is working.

 
2 Comments

Posted by on July 27, 2014 in java, spring

 

Tags: , , ,

 
Follow

Get every new post delivered to your Inbox.

Join 41 other followers

%d bloggers like this: