luni, 29 iunie 2015

Java: Making a Remote Service

Steps

Server

  • Make a remote interface
    • Extend java.rmi.Remote
    • Declare that all methods throw a RemoteException
      • arguments and return value should be Serializable or primitives


ITestRemoteService.java


import java.rmi.*;


public interface ITestRemoteService extends Remote {
   public String helloWorld() throws RemoteException;
}

  • Make a remote implementation
    • Implement the remote interface
    • Extend UnicastRemoteObject
    • write no argument constructor that declares a RemoteException
    • Register the service with the RMI registry


TestRemoteService.java


import java.rmi.*;
import java.rmi.server.*; // import for UnicastRemoteObject usage


public class TestRemoteService extends UnicastRemoteObject implements ITestRemoteService {
    
   public static void main(String[] args) {
       try{
           TestRemoteService myTestService = new TestRemoteService();
           Naming.rebind("TestRemoteService", myTestService); //bind to rmiregistry
       } catch(Exception ex) {
           ex.printStackTrace();
       }
   }
    
    
   public TestRemoteService() throws RemoteException {} //UnicastRemoteObject declares an exception
    
   public String helloWorld() {
       return "Hello, George!";
   }     
}

  • Generate the stubs and skeletons (this is deprecated for new java versions) using rmic
    • Split out the two new classes for the helper objects
    • NOTE: In Java 5, RMI and Dynamic Proxy got toghether and now stubs are generated dynamically using Dynamic Proxy. The remote objcet's stub is a java.lang.reflect.Proxy instance (with an invocation handler).
>javac -d class ITestRemoteService.java
>javac -d class TestRemoteService.java
>cd class
>rmic TestRemoteService

  • Start the RMI registry (rmiregistry)
>rmiregistry


  • Start the remote service
>java TestRemoteService


Client

  • Have a client class (in a client folder)
  • Copy interface and stubs to the client folder
  • Client does a lookup on the RMI registry
  • RMI registry returns the stub object
    • stub class should be on the client (also the interface class)
  • Client invokes a method on the stub


TestRemoteClient.java


import java.rmi.*;


public class TestRemoteClient {
   public static void main(String[] args) {
       try {
           ITestRemoteService service = (ITestRemoteService) Naming.lookup("rmi://127.0.0.1/TestRemoteService");
           String str = service.helloWorld();
           System.out.println(str);
            
       } catch(Exception ex) {
           ex.printStackTrace();
       }
   }
}


>javac -d class TestRemoteClient.java
>cd class
>java TestRemoteClient
Hello, George!

vineri, 19 iunie 2015

Java: Simple UI Application

import javax.swing.*;
import java.awt.*;

public class UITest {
    public static void main(String[] args) {
        UITest gui = new UITest();
        gui.go();
    }
    
    public void go() {
        //This has a BorderLayout manager's control
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        //A JPanel's layout manager is FJowLayout by default.
        JPanel panel = new JPanel();
        panel.setBackground(Color.darkGray);
        
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        frame.getContentPane().add(BorderLayout.EAST, panel);
        
        JButton button = new JButton("Button 1");
        panel.add(button);
        
        button = new JButton("Button button");
        panel.add(button);
        
        button = new JButton("Button??");
        panel.add(button);
        
        frame.setSize(200, 200);
        frame.setVisible(true);
    }
}

Java: Client - Server Application

ServerTest.java

import java.io.*;
import java.net.*;

public class ServerTest implements Serializable {
    String[] messageList = {
        "Mai bine sa ai bani decat sa nu ai.",
            "Din putul gandirii.",
            "Cosorul lui Moceanu a fost inventat de Moceanu",
            "Da' ce am facut sefu'?",
            "Elefantul si bursucul."
    };

    public static void main(String[] args) {
        ServerTest server = new ServerTest();
        server.setupServer();
    }

    public void setupServer() {
        try {
            ServerSocket serverSock = new ServerSocket(5000);
            //each time a client open a socket respond with one message from messageList
            while (true) {
                Socket sock = serverSock.accept();

                PrintWriter writer = new PrintWriter(sock.getOutputStream());
                String advice = getAdvice();
                writer.println(advice);
                writer.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

    private String getAdvice() {
        int random = (int)(Math.random() * messageList.length);
        return messageList[random];
    }

}

ClientTest.java


import java.io.*;
import java.net.*;

public class ClientTest implements Serializable {
    public static void main(String[] args) {
        ClientTest client = new ClientTest();
        client.ReadStreamFromNET();
    }
    
    public void ReadStreamFromNET() {
        try {
            Socket chatSocket = new Socket("127.0.0.1", 5000);
            InputStreamReader stream = new InputStreamReader(chatSocket.getInputStream());
            
            
            BufferedReader reader = new BufferedReader (stream);
            String message = reader.readLine();
            
            System.out.println("\t" + message);
        } catch(IOException ex) {
            ex.printStackTrace();
        }
    }
    
    public void WriteStreamToNET() {
        try {
            Socket chatSocket = new Socket("127.0.0.1", 5000);
            //Connection output stream
            PrintWriter writer = new PrintWriter(chatSocket.getOutputStream());
            
            writer.println("message to send"); 
            writer.print("another message");
        } catch(IOException ex) {
            ex.printStackTrace();
        }
    }
}

joi, 18 iunie 2015

Java: Sample of Serialization

//Serializable is in java.io package
import java.io.*;

//Serializable a way to say that this type is OK to be serialized
// Used to save the object state
public class SerializationTest implements Serializable {
    private int width; 
    private int height; 
    //transient says "don't save me"
    transient String name; 
    
    public void setWidth(int value) {
        width = value;
    }
    
    public void setHeight(int value) {
        height = value;
    }
    
    public int getWidth() {
        return width;
    }
    
    public static void main(String[] args) {
        SerializationTest test = new SerializationTest();
        test.setWidth(10);
        test.setHeight(20);
        
        try { // I/O can throw exceptions
            //Connect to a file (FileOutputStream is a connection stream. In this case to a file)
            FileOutputStream fs = new FileOutputStream("test.ser");
            //Make an ObjectOutputStream chained to the connection stream
            ObjectOutputStream os = new ObjectOutputStream(fs);
            //write the object
            os.writeObject(test);
            os.close();
            
        } catch(Exception ex) {
            ex.printStackTrace();
        }
        
        try {
            ObjectInputStream is = new ObjectInputStream(new FileInputStream("test.ser"));
            //You read objects In (using readObjeet()) in the order In which they were originally written.
            //return type is an Object
            //static variables are not serialized
            SerializationTest restored = (SerializationTest) is.readObject();
            
            System.out.println("Restored type: \t" + restored.getWidth());
            
        } catch(Exception ex) {
            ex.printStackTrace();
        }
        
        File myfile = new File("test.ser");
        System.out.println("File exists? : \t" + myfile.exists());
        System.out.println("\tAbsolute path:: \t" + myfile.getAbsolutePath());
    }
    
    
}