Monday, June 3, 2013

How to use and advantages of Spring RMI

My current project is java RMI (remote method invocation) project and we are using spring as main framework. There are lots of advantages when you use spring framework for RMI. Before I go father I will show you RMI example without using spring framework.

Create an interface name Hello.java and declare sayHello method without body as per the requirement of a simple Hello RMI application.


import java.rmi.Remote;

public interface Hello extends Remote{
    public String sayHello();
}

The next step is to implement the interface so define a class.

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class HelloImpl extends UnicastRemoteObject implements Hello {

    protected HelloImpl() throws RemoteException {
        super();
    }

    @Override
    public String sayHello() {
        System.out.println("Hello");
        return "Hello";
    }
}

Define the Server side class.

import java.rmi.Naming;
public class HelloServer {

    public HelloServer() {
        try {
            Hello h = new HelloImpl();
            Naming.rebind("rmi://localhost:1099/HelloService", h);
        } catch (Exception e) {
            System.out.println("Exception is : " + e);
        }
    }
    
    public static void main(String[] args) {
        new HelloServer();
    }
}

Now server side code is over. Define the Client side class to access sayHello method.
import java.rmi.Naming;

public class HelloClient {
    public static void main(String[] args) {
        try {
            Hello h = (Hello) Naming.lookup("//127.0.0.1:1099/HelloService");
            System.out.println("Say : " + h.sayHello());
        } catch (Exception ex) {
            System.out.println("Error " + ex);
        } 
            
    }
}

These are the steps of RMI example without spring. Now check how Spring framework can implement same example.

package com.sasika.hello;

public interface Hello{
    public String sayHello();
}

You don’t need to extend Hello java interface from Remote Interface. You don’t need to extend UnicastRemoteObject as well.

package com.sasika.hello;
public class HelloImpl implements Hello {

    @Override
    public String sayHello() {
        System.out.println("Hello");
        return "Hello";
    }
}
We can export the interface of our HelloImpl object as RMI object. To do that we can use spring RmiServiceExporter. Next code sample shows how to export our business logic(HelloImpl) to RMI service using spring.
For more detail visit: http://static.springsource.org/spring/docs/2.0.8/reference/remoting.html



   
        
   

   
   

   
   


That’s all for server side. Now look at the client side code. We need to write SpringConfiguration.xml for access Rmi service.





        
        




public class HelloClient {
    public void callHello() {
        try {
            ApplicationContext ctx =  new ClassPathXmlApplicationContext("classpath:com/sasika/hello/SpringConfiguration.xml");
            Hello h = (UserRolePermissionBo) ctx.getBean("helloBean");
            System.out.println("Say : " + h.sayHello());
        } catch (Exception ex) {
            System.out.println("Error " + ex);
        } 
            
    }
}


This is how we develop RMI project with spring. So what are the advantages of using spring RMI.

There are few advantages. One is you don’t need to extend any RMI related Interfaces. So you can concentrate your application business logic rather than RMI specific codes. When you don’t extend RMI related Interfaces your application can export any other services without changing your existing code.

For example if you need to write Hello web service, you can write another class (HelloWs) and call existing Hello java class method. You don’t need to QA for existing code.Same as you can write web client or any other service without changing existing code.

This will improve your system Flexibility, Maintainability, and Extensibility.

In here with spring, RMI specific codes move into xml file. This reduces complexity of codes. Hiding complexity is another advantage.

Wednesday, May 8, 2013

Design patterns can save your day


Last month I was working on inventory control system with my team members. We were developing it using “weighted average” inventory method on SRS prepared BA’s. After few week of development requirements change as no surprise. The management want to develop it’s using both “weighted average” and “first in first out(FIFO)” methods.

So we discussed how to change our design for these new requirements. We were using spring as MVC framework and JPA for ORM. It is client (Java Swing) server application using RMI. After few hours of discussion we decided to write InventoryManagerDao interface and two implementation class called InventoryManagerFifoDaoImpl and InventoryManagerWavgDaoImpl.(Initially we decided to write abstract class but these two inventory methods(FIFO and weighted average) does not have any common methods) 

Our design looks like this


This design looks fine for us. But we had another problem with this design.When we were using this design we have to check which inventory method initially configured. We have to check it using if condition and get the appropriate inventory manager object from few areas (Sales Invoice, GRN, Returns…). It is code duplication. So we decided to give this object creation responsibility to some other class called InventoryHandle.

Now design looks like this.


This design looks maintainable and extensible. Few days later we found that this is almost a design pattern. It is a Factory method pattern.

 

I have read Head First Design Patterns ebook once and I knew few design patterns. But I did not memorize it. We need to know how to apply design pattern with real scenarios. So I decide to follow these design patterns seriously and try to understand and memorize (of course how to apply). Because design patterns can save our day.

Friday, April 19, 2013

Why do we need java frameworks?


What is core java and advanced java?
Before we start talking about java framework, we should know about core and advance java.
Core java comes with java 'Standard Edition' and it has to do with the basic package of Java objects that are typically used for general desktop applications.
Where as advance java is specialisation in some domain, such as networking, web, DCOM or database handling.


What is Frameworks?
Framework is set of reusable software program that forms the basis for an application. Frameworks helps the programmers to build the application quickly. Earlier it was very hard to develop complex web applications. Now it’s very easy to develop such application using different kinds of frameworks such as Struts, Struts 2, Hibernate,  JSF, Tapestry, JUnit, Log4j, Spring etc.
http://www.roseindia.net/frameworks/

Example of Java frameworks
MVC frameworks : Spring
ORM frameworks : Hibernate, Oracle TopLink, iBATIS
Presentation layer frameworks : Struts, JSF, Apache Wicket

Example of Framework usage
I will show how JDBC that inserts data into the database and how simply do it using java frameworks(Spring & Hibernate).

Consider there is a Customer table in your database.

CREATE TABLE `customer` (                              
             `CUSTOMER_ID` BIGINT(20) NOT NULL AUTO_INCREMENT,    
             `NAME` VARCHAR(45) NOT NULL,                          
              PRIMARY KEY (`CUSTOMER_ID`),                          
              UNIQUE KEY `CUSTOMER_ID` (`CUSTOMER_ID`)              
              )

JDBC Insert customer method using PreparedStatement

private void insertCustomerIntoTable(Customer customer) throws SQLException {
  Connection dbConnection = null;
  PreparedStatement preparedStatement = null;
  String insertTableSQL = "INSERT INTO CUSTOMER ( CUSTOMER_ID, NAME) VALUES (?,?)";
  try {
   dbConnection = getDBConnection();
   preparedStatement = dbConnection.prepareStatement(insertTableSQL);
   preparedStatement.setInt(1, customer.getCustomerId());
   preparedStatement.setString(2, customer.getName());
   preparedStatement.executeUpdate();

   } catch (SQLException e) {
    System.out.println(e.getMessage());
   } finally {
    if (preparedStatement != null) {
    preparedStatement.close();
   }
    if (dbConnection != null) {
    dbConnection.close();
   }
  }
  }

We have to code this much no of line to achieve our goal.(I do not show the database connection method and Customer class with getters and setters )

Now when we configure this project with spring mvc and hibernate frameworks code is simplify like this

@Transactional
private void insertCustomerIntoTable(Customer customer){
      session.save(customer);
}

That’s it. That’s what all we need to do. @Transactional annotation will handle the transactional part in database access and hibernate session’s save method will insert customer data into table.If anything goes  wrong and Exception throws,this method will rollback transaction.
(to achieve this we need to do some configurations like Datasource, HibernateSessionFactory, TransactionManager spring beans)

There are so many example like this,when you develop application using java frameworks.Main advantage is we can concentrate our application business logic rather than handling data access common boilerplate code.
Other than this some of advantage of frameworks are
  • Hiding complexity
  • Increase performance
  • Modularity
  • Flexibility, Maintainability, and Extensibility