//#
//# Corba Time Server
//# $Revision: 1.1 $
//# Copyright 2004 by Eric Y. Theriault
//# All Rights Reserved.
//# http://www.eyt.ca/CORBA
//#
package ca.eyt.corba;

/**
 * Implements a CORBA server to provide the local time.
 *
 * @author Eric Y. Theriault <eric@eyt.ca>
 */
public class TimeServer {
   /**
    * main
    *
    * @param args Currently forwarded directly to ORB.init.
    */
   public static void main( String args[] ) {
      try {
         String iorFile = "time.ior";

         // Create and Initialize the ORB
         org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init( args, null );

         // Get a reference to the root POA and activate the POAManager
         org.omg.PortableServer.POA rootPOA =
                         org.omg.PortableServer.POAHelper.narrow(
                              orb.resolve_initial_references( "RootPOA" )
                                                                );
         rootPOA.the_POAManager().activate();

         // Create the time Servant and register it.
         ca.eyt.corba.TimeImpl timeImpl = new ca.eyt.corba.TimeImpl();
         timeImpl.setORB( orb );

         // Create the object reference.
         org.omg.CORBA.Object ref = rootPOA.servant_to_reference( timeImpl );
         String ior = orb.object_to_string( ref );

         // Create the file.
         java.io.FileWriter fileWriter = null;
         java.io.BufferedWriter writer = null;
         try {
            fileWriter = new java.io.FileWriter( iorFile );
            writer = new java.io.BufferedWriter( fileWriter );
         } catch ( java.io.IOException ioe ) {
            System.err.println( iorFile + ": Failure to create:" );
            ioe.printStackTrace();
            System.exit( 1 );
         }

         // Write in the IOR from the file...
         try {
            writer.write( ior );
            writer.newLine();
         } catch ( java.io.IOException ioe ) {
            System.err.println( iorFile + ": exception raised: " );
            ioe.printStackTrace();
            System.exit( 1 );
         } finally {
            writer.flush();
            try {
               fileWriter.close();
            } catch ( java.io.IOException ioe ) {
               System.err.println( iorFile + ": exception raised " +
                                   "closing the file: " );
               ioe.printStackTrace();
            }
            writer = null;
            fileWriter = null;
         }

         // Server is now up and running
         System.out.println( "TimeServer is ready and waiting..." );
         orb.run();
      } catch ( Throwable t ) {
         System.err.println( "Exception raised: " );
         t.printStackTrace();
      }
   }
};

