package iiop.rmi;
import java.rmi.Remote;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
/** <tt>java iiop.rmi.Server service</tt><br>
    creates service(), binds it for service.id.
    Set <tt>rmi.log</tt> to display threads.
  */
public class Server {
  /** locates a service using JNDI.
      @param id service's registry name.
    */
  public static Object lookup (String id, Class to) throws NamingException {
    return PortableRemoteObject.narrow(new InitialContext().lookup(id), to);
  }
  /** starts and registers a service using JNDI.
      Set <tt>rmi.log</tt> to show threads.
      @param args [0] classname of service; class must contain static String id.
   */
  public static void main (String args []) throws Exception {
    Class serviceClass = null;
    try {
      if (args != null && args.length > 0) {
        serviceClass = Class.forName(args[0]);
        Remote service = (Remote)serviceClass.newInstance();
        PortableRemoteObject.exportObject(service);
        new InitialContext().rebind((String)serviceClass.getField("id").get(null),
                                                                          service);
        if (Boolean.getBoolean("rmi.log"))
          dumpThreads(true);
      }
   }  finally {
      if (serviceClass == null)
        System.err.println("usage: java iiop.rmi.Server service");
    }
  }
  /** dump active threads [needs ModifyThreadGroup permission].
      @param user true to see only user threads.
    */
  public static void dumpThreads (boolean user) {
    ThreadGroup tg = Thread.currentThread().getThreadGroup();
    for (ThreadGroup p = tg.getParent(); p != null; p = tg.getParent())
      tg = p;
    Thread thread [] = new Thread[tg.activeCount()];
    int nThreads = tg.enumerate(thread);
    for (int n = 0; n < nThreads; ++ n)
      if (!user || !thread[n].isDaemon())
        System.err.println(thread[n]+" daemon: "+thread[n].isDaemon());
  }
}

