January 2012 Posts

A Simple Java RMI Tutorial

Java Remote Method Invocation (Java RMI) enables the programmer to create distributed Java technology-based to Java technology-based applications, in which the methods of remote Java objects can be invoked from other Java virtual machines, possibly on different hosts. RMI uses object serialization to marshal and unmarshal parameters and does not truncate types, supporting true object-oriented polymorphism.

Let’s just say RMI is the “older version” of ejb remote. Because in EJB, enterprise beans are made available for remote clients using RMI.

In this example, im trying to create 2 different project, one is the RMI Server and another one is RMI Client.

First is a simple interface, i will use this interface to create invocation methods and implementations. This interface will be on both Server’s and Client’s side.

package com.edw.rmi;

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

public interface Message extends Remote {
    void sayHello(String name) throws RemoteException;
}

and next is the implementation for my interface, it is exist only on the server’s side. It has to implements my interface and extends to UnicastRemoteObject class.

package com.edw.rmi;

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

public class MessageImpl extends UnicastRemoteObject implements Message {

    public MessageImpl() throws RemoteException {        
    }
    
    @Override
    public void sayHello(String name) throws RemoteException {
        System.out.println("hello "+name);
    }
    
}

And next is creating my server side application. Im running on port 1099 for RMI port.

package com.edw.main;

import com.edw.rmi.MessageImpl;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Main {
    
    private void startServer(){
        try {
            // create on port 1099
            Registry registry = LocateRegistry.createRegistry(1099);
            
            // create a new service named myMessage
            registry.rebind("myMessage", new MessageImpl());
        } catch (Exception e) {
            e.printStackTrace();
        }      
        System.out.println("system is ready");
    }
    
    public static void main(String[] args) {
        Main main = new Main();
        main.startServer();
    }
}

And this is my client’s side application

package com.edw.main;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import com.edw.rmi.Message;

public class Main {
    
    private void doTest(){
        try {
			// fire to localhost port 1099
            Registry myRegistry = LocateRegistry.getRegistry("127.0.0.1", 1099);
			
			// search for myMessage service
            Message impl = (Message) myRegistry.lookup("myMessage");
			
			// call server's method			
            impl.sayHello("edwin");
			
            System.out.println("Message Sent");
        } catch (Exception e) {
            e.printStackTrace();
        }        
    }
    
    public static void main(String[] args) {
        Main main = new Main();
        main.doTest();
    }
}

This is the screenshot of what happen on my netbeans’ console, for my RMI client’s side

and RMI’s server side

and this is my netbeans’ project

While this is what RMI messages looks like

Have fun with RMI :)

Google+

Weird Blank Report When Using JasperReport

Yesterday, ive found a very weird error when im trying to print my report to pdf using jasper report. Somehow it show a blank report when i’m printing my report and my log file shows no error at all despite there is nothing on my pdf file. I’m using a simple servlet and jasper report classes to generate my pdf files and show it on browser.

This is what my report looks like

And this is part of my sourcecode

   protected void doPost(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
		// set header as pdf
        response.setContentType("application/pdf");

        // set input and output stream
        ServletOutputStream servletOutputStream = response.getOutputStream();   
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        
        FileInputStream fis;
        BufferedInputStream bufferedInputStream;
        
        String nama = "";
        String alamat = "";

        try {        	
        	if(request.getParameter("nama")!=null)
            	nama = request.getParameter("nama");
			
			if(request.getParameter("alamat")!=null)
				alamat = request.getParameter("alamat");
        	
        	// get report location
            ServletContext context = getServletContext();
            String reportLocation = context.getRealPath("WEB-INF");
            
            // get report
            fis = new FileInputStream(reportLocation + "/report/LaporanSatu.jasper");
            bufferedInputStream = new BufferedInputStream(fis);
            
            // fill parameters
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("nama", "%"+nama+"%");
            map.put("alamat", alamat);
                                               	
            // export to pdf            
            JasperReport jasperReport = (JasperReport) JRLoader.loadObject(bufferedInputStream);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map);
            JasperExportManager.exportReportToPdfStream(jasperPrint, baos);

            response.setContentLength(baos.size());
            baos.writeTo(servletOutputStream);

            // close it
            fis.close();
            bufferedInputStream.close();            
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			servletOutputStream.flush();
            servletOutputStream.close();
            baos.close();
		}        
	}

Well the workaround is actually very easy, i only need to add a new empty datasource (JREmptyDataSource) in JasperFillManager parameters

   protected void doPost(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
		// set header as pdf
        response.setContentType("application/pdf");

        // set input and output stream
        ServletOutputStream servletOutputStream = response.getOutputStream();   
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        
        FileInputStream fis;
        BufferedInputStream bufferedInputStream;
        
        String nama = "";
        String alamat = "";

        try {        	
        	if(request.getParameter("nama")!=null)
            	nama = request.getParameter("nama");
			
			if(request.getParameter("alamat")!=null)
				alamat = request.getParameter("alamat");
        	
        	// get report location
            ServletContext context = getServletContext();
            String reportLocation = context.getRealPath("WEB-INF");
            
            // get report
            fis = new FileInputStream(reportLocation + "/report/LaporanSatu.jasper");
            bufferedInputStream = new BufferedInputStream(fis);
            
            // fill parameters
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("nama", "%"+nama+"%");
            map.put("alamat", alamat);
                       
                        	
            // export to pdf            
            JasperReport jasperReport = (JasperReport) JRLoader.loadObject(bufferedInputStream);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, 
              map, new JREmptyDataSource());
            JasperExportManager.exportReportToPdfStream(jasperPrint, baos);

            response.setContentLength(baos.size());
            baos.writeTo(servletOutputStream);

            // close it
            fis.close();
            bufferedInputStream.close();
            
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			servletOutputStream.flush();
            servletOutputStream.close();
            baos.close();
		}        
	}

This is the screenshot for my successful report.

Google+