// eg3_clt.java -- Echo client that uses the COSS naming service

package UK.co.orl.omniorb;

import org.omg.CORBA.*;
import org.omg.CORBA.ORBPackage.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;

class eg3_clt {
  public static void main(String[] args) {
    ORB orb = ORB.init(args, null);
    
    try {
      java.util.Random r = new java.util.Random();
      Echo obj = EchoHelper.narrow(getObjectReference(orb));
      for (;;) {
	hello(obj);
	Thread.sleep(Math.abs(r.nextLong() % 20000));
      }
    } catch (COMM_FAILURE x) {
      System.err.println("Caught system exception COMM_FAILURE, unable to " +
			 "contact the object.");
    } catch (Throwable x) {
      System.err.println("Caught a system exception:");
      System.err.println(x);
    }
  }

  static org.omg.CORBA.Object getObjectReference(ORB orb) {
    NamingContext rootContext;
    try {
      org.omg.CORBA.Object initServ;
      try {
	initServ = orb.resolve_initial_references("NameService");
      } catch (COMM_FAILURE x) {
	if (x.minor == 6)
	  // We probably haven't got a bootstrap server running.  Try
	  // doing what omniORB would do...
	  initServ =
	    OmniOrbConfig.resolve_omniorb_initial_references("NameService",
							     orb);
	else
	  throw x.fillInStackTrace();
      }
      rootContext = NamingContextHelper.narrow(initServ);
    } catch (org.omg.CORBA.ORBPackage.InvalidName x) {
      System.err.println("Service required is invalid [does not exist].");
      return null;
    } catch (Throwable x) {
      System.err.println("Caught a system exception finding the name " +
			 "service:");
      System.err.println(x);
      return null;
    }

    NameComponent[] name = {
      new NameComponent("test", "my_context"),
      new NameComponent("Echo", "Object")};
    
    org.omg.CORBA.Object obj;
    try {
      obj = rootContext.resolve(name);
    } catch (NotFound x) {
      System.err.println("Context not found.");
      return null;
    } catch (COMM_FAILURE x) {
      System.err.println("Caught system exception COMM_FAILURE, unable to " +
			 "contact the naming service.");
      return null;
    } catch (Throwable x) {
      System.err.println("Caught a system exception while using the naming " +
			 "service:");
      System.err.println(x);
      return null;
    }
    return obj;
  }
  static void hello (Echo obj) {
    String src = "Hello!";
    String dest;
    
    long time_pre = System.currentTimeMillis();
    dest = obj.echoString(src);
    long time_elapsed = System.currentTimeMillis() - time_pre;
    System.err.println("I said, \"" + src + "\".  " +
		       "The Object said, \"" + dest + "\" " +
		       "(" + time_elapsed + " ms)");
  }
}
