package labworks.ntservice;

import javax.naming.*;
import org.objectweb.jonas.server.Server;
import org.objectweb.jonas.adm.*;
import net.sourceforge.jsrvany.*;

// jeremie packages
import org.objectweb.jeremie.libs.services.registry.JRMIRegistry;

// rmi packages
//  import java.rmi.registry.*;
//  import java.rmi.RemoteException;

public class JonasWrapper extends SimpleListener {

  final static String JONAS_NAME = "jonas";  // default value, hope its not changed...

  private static ServiceControlManager manager = null;

  public static void main(String[] args) {

    // jsrvany dosen't set the main threads class loader so do so here
    Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());

    // get the ServiceConrolManager
    manager = ServiceControlManager.getInstance();

    // register this class as a listener
    manager.addServiceControlListener(new JonasWrapper());

    // start Jeremie
    JRMIRegistry.main(args);

    // start RMI registry
//      try {
//        LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
//      } catch(RemoteException e) { 
//        System.err.println("Unable to create RMI Registry"); 
//        System.exit(-1);
//      } 

    // start JOnAS
    Server.main(args);

    // main thread ends killing the naming service
  }

  public void handleServiceControlEvent(StopServiceControlEvent e)
    throws ServiceControlException {
    stopJonas();
  }

  public void handleServiceControlEvent(TerminateServiceControlEvent e)
    throws ServiceControlException {
    stopJonas();
  }

  public static void stopJonas() {

    // stop jonas from a new thread giving this method a chance
    // to complete before the main thread.
    Thread stoper = new Thread(){
	public void run() {
	  String admName = JONAS_NAME + Adm.ADMNAME_SUFFIX;
	  try {
	    InitialContext initialContext = new InitialContext();
	    AdmInterface admI = (AdmInterface) initialContext.lookup(admName);
	    admI.stopServer();
	  } catch (Exception e) {
	    System.err.println ("JonasWrapper.stopJonas : " + e);
	  }
  	}
      };
    stoper.start();
  }

}

