package mit.rmi ;

public class Client
implements java.io.Serializable
{
	private String host = null ;
	public String getHost() { return this.host ; }
	protected void setHost( String host ) { this.host = host ; }

	private Integer port = new Integer( 0 ) ;
	public Integer getPort() { return this.port ; }
	protected void setPort( Integer port ) { this.port = port ; }

	private String server = "mit.rmi.Server" ;
	protected String getServer() { return this.server ; }
	protected void setServer( String server ) { this.server = server ; }

	private Object response = null ;
	public Object getResponse() { return this.response ; }
	protected void setResponse( Object response ) { this.response = response ; }

	private mit.rmi.Interface iface = null ;
	protected mit.rmi.Interface getIface() { return this.iface ; }
	protected void setIface( mit.rmi.Interface iface ) { this.iface = iface ; }

	public static void main( String[] args) {
		
		try {
			mit.rmi.Client c = mit.rmi.Client.create( "localhost", new Integer( 0 ));
			System.out.println( c.test() );
			Boolean b = c.authenticate( null );
			System.out.println( "c.authenticate( null ) = " + b );
			Object o = c.invoke( new mit.rmi.TestObject() , "getMessage" , new Class[ 0 ] , new Object[ 0 ] ) ;
			System.out.println( "Object " + o + " returned from invoke!" );
		} catch ( Exception ex ) {
				ex.printStackTrace();
		}
	}


	public static mit.rmi.Client create( String host , Integer port )
	throws Exception
	{
		mit.rmi.Client client = new mit.rmi.Client() ;
		client.setHost( host ) ;
		client.setPort( port ) ;
		return client ;
	}

	public Boolean authenticate( byte[] ticket )
	throws Exception
	{
		setup() ;
		if( null != getIface() )
		{
			return getIface().authenticate( ticket ) ;
		}
		return new Boolean( false ) ;
	}

	public Object invoke( java.io.Serializable object , String methodName , Class[] argTypes , Object[] args )
	throws Exception
	{
		try
		{
			setup() ;
			if( null != getIface() )
			{
				Object resp = getIface().invoke( object , methodName , argTypes , args ) ;
				setResponse( resp ) ;
			}
		}
		catch( Exception ex )
		{
			ex.printStackTrace() ;
		}
		if( getResponse() instanceof Exception )
		{
			throw ( Exception ) getResponse() ;
		}
		return getResponse() ;
	}

	public String test()
	throws Exception
	{
		setup() ;
		if( null != getIface() )
		{
			return getIface().test() ;
		}
		return "Test failed." ;
	}

	private void setup()
	throws Exception
	{
		setResponse( null ) ;
		if( null == System.getSecurityManager() )
		{
			System.setSecurityManager( new java.rmi.RMISecurityManager() ) ;
		}
		if( null == getIface() )
		{
			mit.rmi.Interface iface
				= ( mit.rmi.Interface ) java.rmi.Naming.lookup
					( "//" +  getHost()
					+ ":" + getPort().toString()
					+ "/" + getServer()
					) ;
			setIface( iface ) ;
		}
	}

}
