Thursday, 31 December 2015

Java Remote Method invocation

Java RMI:

The Java Remote Method Invocation (RMI) system allows an object running in one Java virtual machine to invoke methods on an object running in another Java
virtual machine. RMI provides for remote communication between programs written in the Java programming language.

only supports making calls from one JVM to another. The protocol underlying this Java-only implementation is known as Java Remote Method Protocol (JRMP).

In order to support code running in a non-JVM context, a CORBA version was later developed.

RMI provides the mechanism by which the server and the client communicate and pass information back and forth

Client -->Stub-->RRL(remote reference Layer)-->Transport Layer
Server<--Skeleton<--RRL <--Transport Layer

Stub is the proxy of the Remote object at client side.
Sending objects from client to server and from server to client happens with marshaling mechanism
which actually serializes the objects and adds header to that and sends, at the receiving end Unmarshaling happens which actually re-creates the object(de-serialization) .

When a client communicates with the Server object it opens a socket for the communication

Once the server creates the Remote Object, it places the Remote object into RMI registry with the unique bind name.
//Exports the remote object to make it available to receive incoming calls, using the particular supplied port
Hello stub = (Hello) UnicastRemoteObject.exportObject(server, 0);
Registry registry = LocateRegistry.getRegistry();
//Binds a remote reference to the specified name in this registry.
registry.bind("Hello", stub);
at this point Server becomes client and Registry becomes Server and again Remote call happens between Server to Registry to store remote Object into Registry.

Client uses this bind name to look up for, to get the respective remote object and calls the Remote methods on that.

Registry registry = LocateRegistry.getRegistry();
// Returns the remote reference bound to the specified name in this registry
Hello response = (Hello) registry.lookup("Hello");


RMI Implementation

Write an Interface:

It contains all Business methods invoked by the client
The interface must extend Remote interface of RMI
all the methods must throw RemoteException


Write an Implementation Class :

Implement the above interface and extend the UnicastRemoteObject class
if not possible(i.e., if the class already extending some other class) need to export object

Server program :

Create the instance of the implementation class
place remote object into RMI Registry
ie., Naming.bind("bindName", object); (or)
Naming.rebind("bindName", object);[it is for localhost]

Naming.rebind("machineName:port:bindName",);
Client program:
Fetch the Remote object
Naming.lookup("rmi://machineNme:port/bindName");
Downcast it and invoke the method


Finally, the client invokes the sayHello method on the remote object's stub, which causes the following actions to happen:



  • The client-side runtime opens a connection to the server using the host and port information in the remote object's stub and then serializes the call data.
  • The server-side runtime accepts the incoming call, dispatches the call to the remote object, and serializes the result (the reply string ) to the client.
  • The client-side runtime receives, deserializes, and returns the result to the caller.

Code:

Interface :

package com.awf.org;

import java.rmi.Remote;
import java.rmi.RemoteException;

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

Implementing Class and Server Program:

package com.awf.org;

import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
/**
*
*this class has Interface implementation and Server program i.e., bind related stuff
*/
public class Server implements Hello {

public Server() {

}

@Override
public String sayHello(String clientName) throws RemoteException {
return "Hello " + clientName + "...!!!";
}

public static void main(String args[]) {
Server server = new Server();
try {
// Exports the remote object to make it available to receive
// incoming calls, using the particular supplied port
Hello stub = (Hello) UnicastRemoteObject.exportObject(server, 0);
Registry registry = LocateRegistry.getRegistry();
// Binds a remote reference to the specified name in this registry.
registry.bind("Hello", stub);
System.out.println("Server started...!");
} catch (RemoteException e) {
e.printStackTrace();
} catch (AlreadyBoundException e) {
// this exception occurs if we try to bind the object with the same
// bindName using registry.bind() method
// it can be avoided using Naming.rebind("bindName", object);it
// actually replaces the object
e.printStackTrace();
}
}
}

// We can also write a server class as below
public class Server extends UnicastRemoteObject implements Hello {
}
in another class
Server rmiDemoObj = new Server();//throws RemoteException
Naming.rebind("RMIDemo", rmiDemoObj);// throws MalformedURLException

Client Class:

package com.awf.org;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Client {

public static void main(String[] args) {

try {
Registry registry = LocateRegistry.getRegistry();
// Returns the remote reference bound to the specified name in this
// registry
Hello response = (Hello) registry.lookup("Hello");
System.out.println("Server response ::"
+ response.sayHello("Supreme"));
} catch (RemoteException | NotBoundException e) {
e.printStackTrace();
}
}
}



Running RMI application:

a)Compile interface, Implementation class, server, client classes using javac
    b)start RMI Registry using command (start rmiregistry)
    c)Run server program using below command
    the below command sets the code base which downloads the stub dinamically and client uses this stub to call remote methods.
    It opens new command prompt to display execution result of Server
start java -classpath C:\MyJavaWorld\MyExperiments\RMIApp\bin\ -Djava.rmi.server.codebase=C:\MyJavaWorld\MyExperiments\RMIApp\bin\ com.awf.org.Server
    d)open another command prompt to run the client program.
Example:
In eclipse create project RMIApp
under source create package com.awf.org
create Above classes[Hello interface, Server,Client Classes]

a)if java files are created using eclise, class files will be there under bin folder of the project bin/com/awf/org/<classfiles>

b)open a command prompt
C:\Users\IBM_ADMIN>cd C:\MyJavaWorld\MyExperiments\RMIApp\bin
C:\MyJavaWorld\MyExperiments\RMIApp\bin>start rmiregistry
[Result :This opens a new CMD to run RMI Registry]

c)C:\MyJavaWorld\MyExperiments\RMIApp\bin>start java -classpath C:\MyJavaWorld\MyE
xperiments\RMIApp\bin\ -Djava.rmi.server.codebase=C:\MyJavaWorld\MyExperiments\R
MIApp\bin\ com.awf.org.Server

[Result: opens a new command prompt and prints Server output below]
Server started...!


    d)in new CMD to run Client program
C:\MyJavaWorld\MyExperiments\RMIApp\bin>java com.awf.org.Client
Server response ::Hello Supreme...!!!




Note: Prior to J2SE 5.0 release Step c) needs to be replaced with the below
The below rmic commad is used for compiling Remote Implementation class[here its Server. We can write Implementation class and Server class separately also]
C:\MyJavaWorld\MyExperiments\RMIApp\bin>rmic com.awf.org.Server
[Result: Generates the Stub class Server_stub.class]

C:\MyJavaWorld\MyExperiments\RMIApp\bin> java com.awf.org.Server
Server started...!

Friday, 25 December 2015

Dude Vs Super Dude: Episode 1 


Dude: I wanted  to buy a PencilBox and CompassBox and put some stationery in it. I took two ArrayList and put the items into it. But am confused how I am going to place corresponding stationery into each box.

               List box =new ArrayList();
                       box.add("PencilBox");
                       box.add("CompassBox");
              List stationery =new ArrayList();
                      stationery.add("Pencil");
                      stationery.add("Eraser");
                      stationery.add("Sharpener");
                      stationery.add("Protector");
                      stationery.add("Compass");
                      System.out.println(box);
                      System.out.println(stationery);

Super Dude: Hey Buddy, with ArrayList you can only place group of different objects in an order and  you can sort them if required. But to map two different items, you are in a very wrong place. Don’t Worry! HashMap is available in the market under java.util package, come lets buy some.

Dude: Why buy a HashMap?

Super Dude: Because it implemented the legendary Map<K,V> interface. So Cool huh??

Dude: What’s so cool in it?

Super Dude: Map is the feature of Collection framework which will help us map one item to another which is termed as a Key(K) and Value(V) pair.

Dude: Does it help me to map my PencilBox and stationery?

Super Dude: Sure it does more than that. A map cannot contain duplicate keys so that you can uniquely identify the value using the key.Each key can map to at most one value.  The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys(Only Keys), collection of values(Only Value), or set of key-value mappings(K-V pair), served to you in whatever manner you want. 

Dude: Wow! Awwesome!!

Super Dude: Let me show you how you can do that with a small example,

package com.awf;

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

public class HashMapDemo {

    public static void main(String[] args) {
        List<String> box = new ArrayList();    //Here is your box list
        box.add("PencilBox");
        box.add("CompassBox");
        List pencilBoxStationery = new ArrayList(); //Here is your pencil-box stationery 
        pencilBoxStationery.add("Pencil");
        pencilBoxStationery.add("Eraser");
        pencilBoxStationery.add("Sharpener");
        List compassBoxStationery = new ArrayList(); //Here is your compass-box stationery
        compassBoxStationery.add("Protector");
        compassBoxStationery.add("Compass");

// HashMap implementation
        Map<String, List> objHashMap = new HashMap<String, List>(); 

//This is where we are mapping box list with the corresponding stationery list
        for (String boxes : box) {
            if ("PencilBox".equals(boxes)) {
                objHashMap.put(boxes, pencilBoxStationery);// Maps PencilBox with stationery
            } else {
                objHashMap.put(boxes, compassBoxStationery);// Maps CompassBox with stationery
            }
        }
        System.out.println(objHashMap);
    }

}

Output will be :
{PencilBox=[Pencil, Eraser, Sharpener], CompassBox=[Protector, Compass]}

You can see that the pencil box stationery are mapped within PencilBox and compass box stationery are mapped with the CompassBox within a HashMap object.

Dude: This is the coolest stuff I have ever seen..!! Now i will map all cities with district and all district with states and all states with country and all countries with the world.. Hahaha!!!

Super Dude [Did he really learned map of maps already..??? ]
                                                                     
                                                                                -Will be Continued...

#jAvaLoVEr                                                                                                               AWF

Thursday, 10 December 2015

How to sort the contents in Map based on values?


If you want to sort the map based on Values .

Below is the sample code

Example : In the below example  key is student name , Value is Student marks

Map<String, Integer> studentToTotal = new TreeMap<String, Integer>();

If you want to sort the studentname(key) based on mark(value) . First you have to convert the mapbject


List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(
                studentToTotal.entrySet());


then use Collections sort method

Collections.sort( list, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> o1,
                    Map.Entry<String, Integer> o2) {
                return (o2.getValue()).compareTo(o1.getValue());
            }
        }       );

The above method will sort the student name based on highest total to lowest total.
 
If you want to sort the student name based on lowest totatl to highest total below is the code snippet

 
Collections.sort( list, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> o1,
                    Map.Entry<String, Integer> o2) {
                return (o1.getValue()).compareTo(o2.getValue());
            }
        }       );


Example program to sort the student name based on highest total to lowest total

package com.awf.org;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.List;

public class SortingBasedOnMapValues {

    public static void main(String[] args) {
       
       // studentToTotal map key is student name ,value is student total

        Map<String, Integer> studentToTotal = new TreeMap<String, Integer>();

        List<Entry<String, Integer>> sortedlistdsc = new ArrayList<Entry<String, Integer>>();
       
        studentToTotal.put("awf-Tamil", 1000);
        studentToTotal.put("awf-Tirumala", 986);
        studentToTotal.put("awf-Joel", 999);
        studentToTotal.put("awf-Rahul", 984);
        studentToTotal.put("awf-Arun", 987);

       
           
        sortedlistdsc=sortStudentsBasedOnTotal(studentToTotal);
       
        System.out.println("Student details based on highest to lowest Total ");

        for (Entry<String, Integer> entry : sortedlistdsc{
            System.out.println("Name ::" + entry.getKey()
                    + "\tTotal ::" + entry.getValue() + "\n");
        }
   
 }

  
   
    public static List<Entry<String, Integer>> sortStudentsBasedOnTotal(
            Map<String, Integer>
studentToTotalref)
{

        // Sort the cells based on Student marks
       // put the studenttotal map entry set in list using the below command for sorting

        List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(
                studentToTotalref.entrySet());


        Collections.sort( list, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> o1,
                    Map.Entry<String, Integer> o2) {
                return (o2.getValue()).compareTo(o1.getValue());
            }
        }       );

        return list;

    }
   

}
=======================================================================

Output :

Student details based on highest to lowest Total

Name ::awf-Tamil         Total ::1000
Name ::awf-Joel            Total ::999
Name ::awf-Arun           Total ::987
Name ::awf-Tirumala    Total ::986
Name ::awf-Rahul          Total ::984




Regards,
R Tamilanban M.E(CSE)
AWF Community

Wednesday, 9 December 2015

Design Patterns :: Observer Pattern

Design Patterns :: Observer Pattern

In this post, we will see about the Observer Design Pattern. To know more about design patterns, visit Software Design Pattern.

Observer Design Pattern is useful in scenarios where changes to an Object is of interest to multiple parties.

Mostly used in all the GUI tool kits(e.g. Swings) and event dispatch mechanisms.

Java Code 

  1. Observable 
    1. The Object which is to be observed
    2. Holds the reference to the list of Observers that are interested in changes happening in this object
  2. Observer (Interface or Abstract class
  3. Concrete Observer 1, Concrete Observer 2 ...

Observable.java

class Observable {

private List<Observer> observers = new ArrayList<Observer>();

public void addObserver(Observer o) {

}

public void removeObserver(Observer o) {

}

public void notifyObservers() {


 
}

Wednesday, 2 December 2015

Why Singleton Design Pattern is required?

Scenario :
If you have 3 classes consider ClassA,ClassB and ClassC.

ClassA has contain one method called displayMsg() method .

If you want to access the displayMsg() in ClassA from ClassB and ClassC.

you need to create ClassA object in ClassB and ClassC using the below command

ClassA objA=new ClassA();       

Once object of ClassA is created displayMsg()can be accessible from ClassB and ClassC


Example :

File 1: ClassA.java
 

package com.awf.org;

public class ClassA{
public void displayMsg(){


System.out.println("Class A method is called");
 

}
}


File 2: ClassB.java

package com.awf.org;

public class ClassB{
public static void main(String args[]){


ClassA objA=new ClassA();
objA.displayMsg();
 

}
}

File 3 :ClassC.java
package com.awf.org;

public class ClassC{


public static void main(String args[]){


ClassA objA=new ClassA();
objA.displayMsg();
 

}
}



Output :

If you ClassB  or ClassC you will get the below output

Class A method is called

Problem with the above code :

 If you have n number of Classes let us consider ClassB,ClassC........ClassN . Each Class need to access ClassA method displayMsg().

You used to create object in all Classes by using 

 

 ClassA objA=new ClassA();

 If you do this your heap memory will get full sometimes you will get java.lang.OutOfMemoryError

The java.lang.OutOfMemoryError: Java heap space error will be triggered when the application attempts to add more data(Object) into the heap space area, but there is not enough space for it.
Note :
There might be plenty of physical memory available, but the Java heap space error is thrown whenever the JVM reaches the heap size limit java.lang.OutOfMemoryError 

 
 To avoid the above problem use Singleton design pattern it will create only one object for particular class. That object can be useb by any class.


Example to create Singleton Class:


package com.awf.org;

public class MySingleton
{
    private volatile static MySingleton instance;
     
    private MySingleton()
    {
      
    }
   
     public static MySingleton getInstance()
    {
        if (instance == null) {
            synchronized (MySingleton.class) {
                if (instance == null) {              //
Doublecheck to avoid race condition
                    instance = new MySingleton();
                }
            }
        }
        return instance;

    }
   
    
}



The above class first check whether the instance for particular Class is already there or not . If it is there it will return existing object else it will create new object and it will return. Its used to avoid java.lang.OutOfMemoryError 


Now I will include Singleton Concept for our example . Just add our ClassA in singleton class this is the first way ,Second way you can make ClassA as Singleton class.


First Way : 

 Include ClassA in above Singleton Object .
If you to get ClassA object from ClassB Just use the below code

ClassA objA=MySingleton.getClassAInstance();

Insted of 

 ClassA objA=new ClassA();



package com.awf.org;

public class MySingleton
{
    private volatile static MySingleton instance;
    private volatile static ClassA classAinstance;
  
    private MySingleton()
    {
        // Suppressing creating a new instances
    }
   
     public static MySingleton getInstance()
    {
        if (instance == null) {
            synchronized (MySingleton.class) {
                if (instance == null) {
                    instance = new MySingleton();
                }
            }
        }
        return instance;
    }
   
   
   
public static ClassA getClassAInstance()
    {
      
  if (classAinstance == null) {
            synchronized (ClassA.class) {
                if (classAinstance == null) {
                     classAinstance = new ClassA();
                }
            }
        }
        return classAinstance;

    }

 
}



File 1: ClassA.java
 

package com.awf.org;

public class ClassA{
public void displayMsg(){


System.out.println("Class A method is called");
 

}
}


File 2: ClassB.java

package com.awf.org;

public class ClassB{
public static void main(String args[]){


ClassA objA=
MySingleton.getClassAInstance();
objA.displayMsg();
 

}
}

File 3 :ClassC.java
package com.awf.org;

public class ClassC{


public static void main(String args[]){


ClassA objA=MySingleton.getClassAInstance();
objA.displayMsg();
 

}
}


Output :
If you ClassB  or ClassC you will get the below output

Class A method is called

Note : Without Singleton 2 Objects created for ClassA but now single object is created for ClassA and Usedby ClassB and ClassC

============================================================

Second Way : 

 Make ClassA as Singleton Object .
If you to get ClassA object from ClassB Just use the below code

ClassA objA=ClassA.getClassAInstance();

Insted of 

 ClassA objA=new ClassA();


 File 1: ClassA.java
package com.awf.org;

public class
ClassA
{
   private volatile static ClassA classAinstance;
  
    private
ClassA()
    {
        // Suppressing creating a new instances
    }
   
       
   
public static ClassA getClassAInstance()
    {
      
  if (classAinstance == null) {
            synchronized (ClassA.class) {
                if (classAinstance == null) {
                     classAinstance = new ClassA();
                }
            }
        }
        return classAinstance;

    }

 
public void displayMsg(){

  System.out.println("Class A method is called");
 

}

}




 

File 2: ClassB.java

package com.awf.org;

public class ClassB{
public static void main(String args[]){


ClassA objA=
ClassA.getClassAInstance();
objA.displayMsg();
 

}
}

File 3 :ClassC.java
package com.awf.org;

public class ClassC{


public static void main(String args[]){


ClassA objA=ClassA.getClassAInstance();
objA.displayMsg();
 

}
}


Output :
If you ClassB  or ClassC you will get the below output

Class A method is called

Note : Without Singleton 2 Objects created for ClassA but now single object is created for ClassA and Usedby ClassB and ClassC



Regards,
R Tamilanban M.E(CSE)
AWF Community