FileDocCategorySizeDatePackage
ServiceLocator.javaAPI DocExample2083Mon Nov 24 10:31:40 GMT 2003com.oreilly.patterns.chapter9

ServiceLocator

public class ServiceLocator extends Object

Fields Summary
private static ServiceLocator
instance
private HashMap
cache
private Context
context
Constructors Summary
private ServiceLocator()

  cache = new HashMap();
  
  // initialize the shared context object      
  try {
   context = new InitialContext();
  } catch(NamingException ne) {
   throw new ServiceLocatorException("Unable to create " + 
    "initial context", ne);
  }
 
Methods Summary
public static com.oreilly.patterns.chapter9.ServiceLocatorgetInstance()

  if (instance == null)
   instance = new ServiceLocator();
  
  return instance;
 
public javax.ejb.EJBHomegetRemoteEJB(java.lang.String name, java.lang.Class type)

  // see if it's in the cache
  if (cache.containsKey(name)) {
   // cache HomeHandle objects since they are maintained
   // by the container
   HomeHandle hh = (HomeHandle)cache.get(name);
            
   try {
    return hh.getEJBHome();
   } catch(RemoteException re) {
    // some kind of problem -- fall through to
    // relookup below
   }
  }
  
  // access to the shared context as well as modifications
  // to the HashMap must be synchronized.  Hopefully the
  // majority of cases are handled above     
  synchronized(this) {
   try {
    Object rRef = context.lookup(name);
    EJBHome eh = 
     (EJBHome)PortableRemoteObject.narrow(rRef, type);
    
    cache.put(name, eh.getHomeHandle());
    return eh;
   } catch(Exception ex) {
    throw new ServiceLocatorException("Unable to find EJB",
     ex);
   }
  }