package demo.ssl;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;

import org.omg.CORBA.ORB;
import org.omg.PortableServer.POA;

/**
 * This is the server part of the ssl demo.
 *
 * @author Nicolas Noffke
 */

public class Server
    extends SSLDemoPOA
{
    /**
     * This method is from the IDL--interface. It prints out the
     * received client cert (if available).
     */
    public void printCert()
    {
        System.out.println("[Server] invoked printCert()");
    }


    public static void main( String[] args ) throws Exception
    {
        if( args.length != 1 && args.length != 2)
        {
            System.out.println( "Usage: java demo.ssl.Server <ior_file> <killfile>" );
            System.exit( -1 );
        }
		
		System.setProperty("OASSLPort","7777"); // WE WANT ALL SERVERS TO TAKE THE SAME PORT

        ORB orb = ORB.init( args, null );

		POA poa = null;
		try {
		System.out.println("\n\nFirst try...\n\n");
        poa = (POA)
        orb.resolve_initial_references( "RootPOA" );
		} catch (Throwable t) {
			System.out.println("\n\nfailed... try again\n\n");
			// FORGET THE EXCEPTION AND TRY AGAIN
			poa = (POA)
			orb.resolve_initial_references( "RootPOA" );
			// NOW WE DON'T GET AN EXCEPTION! THERE WAS NO TRY TO GET THE PORT!
			// NOW WE HAVE A POA BUT IT IS NOT USABLE
		}
		System.out.println("\n\nsucceeded...\n\n");
		
        poa.the_POAManager().activate();

        org.omg.CORBA.Object demo = poa.servant_to_reference( new Server());

		System.out.println("\n\nNow waiting...\n\n");
		Thread.sleep(10000); // JUST TO LET THE SYSTEM WAIT FOR US TO START THE SECOND SERVER
		
        PrintWriter pw = new PrintWriter( new FileWriter( args[ 0 ] ));

        // print stringified object reference to file
        pw.println( orb.object_to_string( demo ));

        pw.flush();
        pw.close();

        if (args.length == 2)
        {
            File killFile = new File(args[1]);
            while(!killFile.exists())
            {
                Thread.sleep(1000);
            }
            orb.shutdown(true);
        }
        else
        {
            orb.run();
        }
    }
} // Server
