1:package is346;
   2:
   3:import javax.naming.InitialContext;
   4:import javax.rmi.PortableRemoteObject;
   5:import javax.naming.NamingException;
   6:import javax.naming.Context;
   7:import javax.ejb.EJBHome;
   8:import javax.ejb.EJBLocalHome;
   9:import java.util.Hashtable;
  10:
  11:public class ServiceLocator {
  12:  private static ServiceLocator serviceLocator;
  13:  private static Context context;
  14:  protected ServiceLocator() throws ServiceLocatorException {
  15:    try {
  16:      context = getInitialContext();
  17:    }
  18:    catch (Exception e) {
  19:      throw new ServiceLocatorException(e.getMessage());
  20:    }
  21:  }
  22:
  23:  public static EJBHome getEjbHome(String ejbName, Class ejbClass) throws
  24:      ServiceLocatorException {
  25:    try {
  26:      Object object = context.lookup(ejbName);
  27:      EJBHome ejbHome = null;
  28:      ejbHome = (EJBHome) PortableRemoteObject.narrow(object, ejbClass);
  29:      if (ejbHome == null) {
  30:        throw new ServiceLocatorException("Could not get home for " + ejbName);
  31:      }
  32:      return ejbHome;
  33:    }
  34:    catch (NamingException ne) {
  35:      throw new ServiceLocatorException(ne.getMessage());
  36:    }
  37:  }
  38:
  39:  public static EJBLocalHome getEjbLocalHome(String ejbName) throws
  40:      ServiceLocatorException {
  41:    try {
  42:      Context localContext = new InitialContext();
  43:      Object object = localContext.lookup(ejbName);
  44:      EJBLocalHome ejbLocalHome = null;
  45:      ejbLocalHome = (EJBLocalHome) object;
  46:      if (ejbLocalHome == null) {
  47:        throw new ServiceLocatorException("Could not get local home for " +
  48:                                          ejbName);
  49:      }
  50:      return ejbLocalHome;
  51:    }
  52:    catch (NamingException ne) {
  53:      throw new ServiceLocatorException(ne.getMessage());
  54:    }
  55:  }
  56:
  57:  public static synchronized ServiceLocator getInstance() throws
  58:      ServiceLocatorException {
  59:    if (serviceLocator == null) {
  60:      serviceLocator = new ServiceLocator();
  61:    }
  62:    return serviceLocator;
  63:  }
  64:
  65:  private Context getInitialContext() throws NamingException {
  66:    Hashtable environment = new Hashtable();
  67:
  68:    environment.put(Context.INITIAL_CONTEXT_FACTORY,
  69:                    "org.jnp.interfaces.NamingContextFactory");
  70:    environment.put(Context.URL_PKG_PREFIXES,
  71:                    "org.jboss.naming:org.jnp.interfaces");
  72:    environment.put(Context.PROVIDER_URL, "jnp://localhost:1099");
  73:
  74:    return new InitialContext(environment);
  75:  }
  76:}