Dears,

This blog is moved to a new blog at:

The new update will be found at that new blog, please follow it!
This blog is no more updated.
Thanks for your visit!

Monday, September 16, 2013

Combination programming of RMI and TCP/IP

Objective
This topic will help you to program an application which is combined from RMI (Remote Method Invocation) technology and TCP/IP protocol. The case study is always a login example described as follow:
- A remote server RMI which provides a method enabling to check login (verify whether an username/password logged in is correct in a database)
- The RMI server also manages a database which contains a table of users including at least two columns of username and password.
- The client (RMI) side is also viewed as the server side of TCP/IP. This receives the User entity from TCP/IP client, via TCP/IP procotol, to verify login.
- The client RMI (also TCP/IP server) will call the remote method from server RMI to verify whether an username/password logged in is correct
- At the client (of TCP/IP) side, a GUI is provided which enables user to enter username/password lo login, and, once logged in, this interface will display the login results (success or fail).
- This TCP/IP client sends an User entity to TCP/IP server to verify and then, receives the login results to display to user.


Application design
The classes for the server RMI side are:
- User (entity class): represents the username/password that a client entered and then, need to be verified
- RMILoginServerView (view class): is a simple view class with console interface. Its mission is to display the server RMI status and show errors if they occur
- RMILoginInterface: an interface of RMI method. This includes an interface of the method checkLogin(User): String
- RMILoginServerControl (control class): a control class for defining the whole method of checkLogin(User): String, and then register this method to the RMI Registry





The classes for RMI client side (also the TCP/IP server side):
- using the same class of User as that of the server side
- ServerView (view class): is a simple view class with console interface. Its mission is to display the server TCP/IP status and show errors if they occur
- ServerControl (control class):  this receives User entity from TCP/IP client side, calls the remote method from server RMI to verify this login and return the results to the TCP/IP client side.

 

 The classes for TCP/IP client side:
- using the same class of User as that of the server side
- ClientView (view class): this class plays the role of GUI interface enabling user to enter username/password and see the login results
- ClientControl (control class): this gets login information entered by user, sends it to the TCP/IP server, receives the login results from TCP/IP server and return the results to the view class to display.



 And the sequence of activities between two sides of application are (assume that the server already registed its method):
1. At the client side, an user enters his username and password to login
2. The ClientView receives these information and then sends to User class to pack them in to an User entity
3. The User class packs them in to an User entity end return it to the view class
4. The view class will forward this entity to control to send to TCP/IP server
5. The server TCP/IP control searches the remote method of checkUser(User) from remote server RMI
6. The remote RMI server (control) return a stub of the called method
7. The server TCP/IP control calls the method to verify the login
8. The server TCP/IP control returns the login results to the client TCP/IP control
9. The client TCP/IP control sends these results to the view class
10. The view class displays the login results (success or fail) to the user.






User.java
package rmi_tcp.rmiServer;
import java.io.Serializable;

public class User implements Serializable{
    private String userName;
    private String password;
   
    public User(){       
    }
   
    public User(String username, String password){
        this.userName = username;
        this.password = password;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}


RMILoginServerView.java
package rmi_tcp.rmiServer;

public class RMILoginServerView {
    public RMILoginServerView(){       
    }
   
    public void showMessage(String msg){
        System.out.println(msg);
    }   
}


RMILoginInterface.java
package rmi_tcp.rmiServer;
import java.rmi.Remote;
import java.rmi.RemoteException;
import rmi_tcp.rmiServert.User;

public interface RMILoginInterface extends Remote{
    public String checkLogin(User user) throws RemoteException;
}


RMILoginServerControl.java
package rmi_tcp.rmiServer;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import rmi_tcp.rmiServer.User;

public class RMILoginServerControl extends UnicastRemoteObject implements RMILoginInterface{
    private int serverPort = 3535;
    private Registry registry;
    private Connection con;
    private RMILoginServerView view;
    private String rmiService = "rmitcpLoginServer";
   
    public RMILoginServerControl(RMILoginServerView view) throws RemoteException{
        this.view = view;
        view.showMessage("RMI server is running...");
        try{
            registry = LocateRegistry.createRegistry(serverPort);
            registry.rebind(rmiService, this);
        }catch(RemoteException e){
            throw e;
        }
    }
   
    public String checkLogin(User user) throws RemoteException{
        String result = "";
        getDBConnection("hotelmanagement", "root","12345678");
        if(checkUser(user))
            result = "ok";
        return result;
    }
   
    private void getDBConnection(String dbName, String username, String password){
        String dbUrl = "jdbc:mysql://your.database.domain/" + dbName;
        String dbClass = "com.mysql.jdbc.Driver";

        try {
            Class.forName(dbClass);
            con = DriverManager.getConnection (dbUrl, username, password);
        }catch(Exception e) {
            view.showMessage(e.getStackTrace().toString());
        }
    }
   
    private boolean checkUser(User user) {
        String query = "Select * FROM users WHERE username ='" + user.getUserName()
                + "' AND password ='" + user.getPassword() + "'";

        try {
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(query);

            if (rs.next()) {
              return true;
            }
        }catch(Exception e) {
            view.showMessage(e.getStackTrace().toString());
        } 
        return false;
      }

    public static void main(String[] args) {
        RMILoginServerView view       = new RMILoginServerView();
        try{
            RMILoginServerControl control = new RMILoginServerControl(view); 
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}




ServerView.java
package rmi_tcp.tcpServer;

public class ServerView {
    public ServerView(){       
    }
   
    public void showMessage(String msg){
        System.out.println(msg);
    }   
}



ServerControl.java
package rmi_tcp.tcpServer;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import rmi_tcp.rmiServer.RMILoginInterface;
import rmi_tcp.rmiServer.User;

public class ServerControl {
    private ServerView view;
    private ServerSocket myServer;
    private Socket clientSocket;
    private String serverRMIHost = "localhost";
    private int serverRMIPort = 3535;
    private int serverTCPPort = 8000;
    private RMILoginInterface rmiServer;
    private Registry registry;
    private String rmiService = "rmitcpLoginServer";
   
    public ServerControl(ServerView view){
        this.view = view;
        openServer(serverTCPPort);
        bindingRMI();
        view.showMessage("TCP server is running...");
       
        while(true){
            listenning();
        }
    }
   
   
    private void openServer(int portNumber){
        try {
            myServer = new ServerSocket(portNumber);
        }catch(IOException e) {
            view.showMessage(e.toString());
            e.printStackTrace();
        }
    }
   
    private void bindingRMI(){
        try{
            registry = LocateRegistry.getRegistry(serverRMIHost, serverRMIPort);
            rmiServer =    (RMILoginInterface)(registry.lookup(rmiService));
        }catch(RemoteException e){
            view.showMessage(e.getStackTrace().toString());
            e.printStackTrace();
        }catch(NotBoundException e){
            view.showMessage(e.getStackTrace().toString());
            e.printStackTrace();
        }
    }
   
    private void listenning(){
        try {
            clientSocket = myServer.accept();
            ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
       
            Object o = ois.readObject();
            if(o instanceof User){
                User user = (User)o;
                String result = rmiServer.checkLogin(user);
                ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());
                oos.writeObject(result);                   
            }
        }catch (Exception e) {
            view.showMessage(e.toString());
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ServerView view       = new ServerView();
        ServerControl control = new ServerControl(view);
    }
}




ClientView.java
package rmi_tcp.tcpClient;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class ClientView extends JFrame implements ActionListener{
    private JTextField txtUsername;
    private JPasswordField txtPassword;
    private JButton btnLogin;
   
    public ClientView(){
        super("RMI - TCP Login MVC");
       
        txtUsername = new JTextField(15);
        txtPassword = new JPasswordField(15);
        txtPassword.setEchoChar('*');
        btnLogin = new JButton("Login");
       
        JPanel content = new JPanel();
        content.setLayout(new FlowLayout());
        content.add(new JLabel("Username:"));
        content.add(txtUsername);
        content.add(new JLabel("Password:"));
        content.add(txtPassword);
        content.add(btnLogin);
                 
        this.setContentPane(content);
        this.pack();
       
        this.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                System.exit(0);
            }
        });
    }

    public void actionPerformed(ActionEvent e) {
    }
   
    public User getUser(){
        User model = new User(txtUsername.getText(), txtPassword.getText());
        return model;       
    }
   
    public void showMessage(String msg){
        JOptionPane.showMessageDialog(this, msg);
    }
   
    public void addLoginListener(ActionListener log) {
          btnLogin.addActionListener(log);
        }
}


ClientControl.java
package rmi_tcp.tcpClient;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class ClientControl {
    private ClientView view;
    private String serverTCPHost = "localhost";
    private int serverTCPPort = 8000;
   
    public ClientControl(ClientView view){
        this.view = view;
        this.view.addLoginListener(new LoginListener());
    }
   
    class LoginListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {
                User user = view.getUser();
                Socket mySocket = new Socket(serverTCPHost, serverTCPPort);
                ObjectOutputStream oos = new ObjectOutputStream(mySocket.getOutputStream());
                oos.writeObject(user);
               
                ObjectInputStream ois = new ObjectInputStream(mySocket.getInputStream());
                Object o = ois.readObject();
                if(o instanceof String){
                    String result = (String)o;
                    if(result.equals("ok")) view.showMessage("Login succesfully!");
                    else view.showMessage("Invalid username and/or password!");
                }
                mySocket.close();
            } catch (Exception ex) {
                view.showMessage(ex.getStackTrace().toString());
            }
        }
    }

    public static void main(String[] args) {
        ClientView view = new ClientView();
        ClientControl control = new ClientControl(view);
        view.setVisible(true);
    }
}





No comments:

Post a Comment