package system.util;

import java.io.*;
import java.net.*;
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * Hibrid betwin RMI and Servlet
 * @author: nik and tin
 */
public abstract class RemoteHttpServlet extends javax.servlet.http.HttpServlet implements java.rmi.Remote {
	protected java.rmi.registry.Registry registry;
/**
 * RemoteHttpServlet constructor comment.
 */
public RemoteHttpServlet() {
	super();
}
/**
 * Try to find the appropriate registry already running.
 * Creation date: (17.3.00 18:35:30)
 */
protected boolean bind() {
	try{
		registry = LocateRegistry.getRegistry(getRegistryPort());
		registry.list();
	}catch( Exception e){
		registry = null;
	}

	if ( registry == null ){
		try{
			registry = LocateRegistry.createRegistry(getRegistryPort());
		}catch( Exception e){
			log("Could not get or create RMI registry on port "+ getRegistryPort()+": "+
				e.getMessage());
			return false;
		}		
	}

	try{
		registry.rebind(getRegistryName(), this );
	}catch( Exception e){
		log("Could not bind to RMI registry : " + e.getMessage());		
//		System.out.println("Could not bind to RMI registry : " + e.getMessage());
		return false;
	}		
	return true;
}
/**
 * Unregistry ourself.
 * Creation date: (17.3.00 18:21:16)
 */
public void destroy() {
	unbind();
}
/**
 * Return the name under which we are to be registered.
 * Creation date: (17.3.00 18:23:22)
 * @return java.lang.String
 */
protected String getRegistryName() {
	String name = getInitParameter("registryName");
	log("Name to RMI registry : " +name);

	if ( null!=name ) return name;

 	return this.getClass().getName();
}
	/**
 * Return the port on which the registry server is listening.
 * Creation date: (17.3.00 18:23:22)
 * @return java.lang.String
 */
protected int getRegistryPort() {
	String port = getInitParameter("registryPort");
	log("Port to RMI registry : " +port);
	
	if ( null!=port ) try{
		return Integer.parseInt(port);
	}catch( Exception e ){}	

 	return Registry.REGISTRY_PORT;
}
/**
 * Init Servlet.
 * Creation date: (17.3.00 18:14:38)
 * @param config javax.servlet.ServletConfig
 */
public void init(javax.servlet.ServletConfig config) throws ServletException {
	super.init(config);
}
/**
 * Insert the method's description here.
 * Creation date: (01.4.2000 a. 17:05:10)
 * @return boolean
 */
public boolean initRMI() {
	try {
		//Export ourself
		UnicastRemoteObject.exportObject(this);
		//Register ourself
		if(!bind()) return false;
	} catch (RemoteException e) {
		return false;
	}
	return true;
}
/**
 * Unbind Server.
 * Creation date: (17.3.00 18:51:11)
 */
protected void unbind() {
	try{
		if (registry != null ) registry.unbind(getRegistryName());
	}catch( Exception e){
//		getServletContext().log("Could not unbinding to RMI registry : " + e.getMessage());
		System.out.println("Could not unbinding to RMI registry : " + e.getMessage());
		return;
	}		

}
}
