package demo.interceptors.proprietary;

import org.omg.CosNaming.*;

/** 
 * An example for using interceptors. Because of the specific
 * nature of this example, we cannot use the name service here
 * and must rely on exchanging object references in string form.
 *
 * NOTE: You must enable all client-side interceptors in the 
 * jacorb properties file or on the command line for this example 
 * to work!
 */ 

public class Client 
{
    public static void main( String[] args )
    {
	try
	{
	    jacorb.orb.ORB orb = (jacorb.orb.ORB)org.omg.CORBA.ORB.init(args,null);

	    if( args.length == 0 )
	    {
		System.out.println("Usage: jaco demo.interceptors.proprietary.Client <ior>");
		System.exit(0);
	    }

	    MyServer s = MyServerHelper.narrow(orb.string_to_object(args[0]));

	    /* Let's register an interceptor. It will be called for all outgoing requests */

	    TraceClientRequestInterceptor t = new TraceClientRequestInterceptor();
	    orb.addInterceptor( t );

	    /* the following interceptor is per-object, i.e. it will only be called
	       for requests to object s */

	    if (s == null){
	      System.err.println("s is null!");
	      System.exit(-1);
	    }

	    orb.addInterceptor( s, new ClientMessageInterceptor() );

	    /* to have a request pass through a request-level interceptor, 
	       we have to use the DII! */

	    org.omg.CORBA.Request r = s._request("_notify");
	    r.add_in_arg().insert_string("hallo");
	    r.invoke();

	    /* redirecting calls: */

	    try
	    {
		NamingContextExt nc = 
		    NamingContextExtHelper.narrow(orb.resolve_initial_references("NameService"));

		MyServer other = MyServerHelper.narrow(nc.resolve(nc.to_name("Redirection.example")));
		RedirectClientRequestInterceptor ri = new RedirectClientRequestInterceptor(other);
		orb.addInterceptor( ri );

		r = s._request("_notify");
		r.add_in_arg().insert_string("hi, Server 2");
		r.invoke();
		orb.removeInterceptor( ri );
	    }
	    catch( org.omg.CosNaming.NamingContextPackage.NotFound nf )
	    {
		System.out.println("The server we wanted to redirect this call could not be found.");
	    }


	    /* The trace interceptor can be removed here (as it would not be called  
	       for the following request anyway (see below) */
	    orb.removeInterceptor(t);

	    /* This request will not go through the trace interceptor as we don't use 
	       the DII.  */

	    System.out.println("The following exception is intentional: ");
	    System.out.println("1: " +  s.writeNumberWithEx(5) );  
			
	} 
	catch ( Exception e )
	{
	    e.printStackTrace();
	}
    }
}


