// bergmark - spring 1999 - ITX project

// This example looks up the extension of a given username and
// prints it out.  It illustrates stand-alone use of Directory Service.
// As such, it is hardly a telephony application. 

import java.io.*;
import cnrg.itx.ds.*;        // for directory service

public class GetMyEntry {
   private DirectoryService myDS = null;
   private DataOutputStream out = null;                        


   // Default constructor
   public GetMyEntry () {
      // Get a signaling object
      try {
	 myDS = new DirectoryService ( );
	 myDS.declareIdentity ( new UserID("adm"), new Password("itxds" ));
      } catch ( Exception e ) {
	 System.out.println ("Couldn't authenticate because" +
	    e.toString() );
	 System.exit(0);
      }
      System.out.println ("Got a Directory Server!");
   }

   // this method takes a user name and prints the extension
   private void PrintExtension (String who) {
      try {
	 System.out.println ("\n\nExtension for " + who + ": " +
	    myDS.getExtension(new UserID(who)).toString() + 
	    "\n\n" );
      } catch ( Exception e ) {
	   System.out.println ("\n\nUnable to look up the extension because " +
	    e.toString() );
      }
   }

   // This method prints the user whose extension is ext
   private void printUser ( String ext ) {
      try {
	 System.out.println ("\n\nUser at extension " + ext + ": " +
	 myDS.getID(new Digits(ext)).toString() +
	 "\n\n" );
      } catch ( Exception e ) {
	 System.out.println ("Could not find a user at extension " + ext +
	 " because " + e.toString() );
      }
   }

   // This method prints out the ITX directory
   private void printAllUsers() {
      for (int i = 0; i<10018; i++) {
	 printUser ( Integer.toString (i) );
      }
   }

   // This method writes the ITX directory to disk
   private void generateExtensions (int n) {
      String ext;
      FileOutputStream fs = null;                               
      try {
	 fs = new FileOutputStream("ExtensionList");
	 out = new DataOutputStream ( fs );
      } catch ( Exception e ) {
	 System.out.println ( "\n\nCould not open output file because " +
	    e.toString() );
      }
      for ( int i = 10000; i < 10000+n; i++ ) {
	 ext = Integer.toString(i);
	 try {
	    out.writeBytes (ext + ": " +
	       myDS.getID(new Digits(ext)).toString() + "\n" );
	    System.out.println ("\n\nUser at extension " + ext + ": " +
	       myDS.getID(new Digits(ext)).toString() +
	       "\n\n" );
	 } catch ( Exception e ) {}
      }
   }

   // This method finishes the run
   private void fini () {
      try {
	 out.flush();
	 out.close();
      } catch ( Exception e ) {}
      /* no need to log out if only using Directory Service
      myDS.logout();
      */
   }

   // Main program
   public static void main (String[] args) {
      GetMyEntry me = new GetMyEntry ();
      me.PrintExtension ("guest");
      /*me.printAllUsers();*/
      /*me.generateExtensions(20);*/
      me.fini();            
      }
}
