DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
JEE Service Locator
Locates JEE Resources thorugh their JNDI Name and caches them in a hashMap
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.ejb.EJBLocalHome;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class ServiceLocator {
private InitialContext initialContext;
private Map cache;
private static ServiceLocator _instance;
static {
try {
_instance = new ServiceLocator();
} catch (ServiceLocaterException se) {
System.err.println(se);
se.printStackTrace(System.err);
}
}
private ServiceLocator() throws ServiceLocaterException {
try {
initialContext = new InitialContext();
cache = Collections.synchronizedMap(new HashMap());
} catch (NamingException ne) {
throw new ServiceLocaterException(ne);
} catch (Exception e) {
throw new ServiceLocaterException(e);
}
}
static public ServiceLocator getInstance() {
return _instance;
}
public Object getLocalHome(String jndiHomeName) throws ServiceLocaterException {
Object localHome = null;
try {
if (cache.containsKey(jndiHomeName)) {
localHome = cache.get(jndiHomeName);
} else {
localHome = initialContext.lookup(jndiHomeName);
cache.put(jndiHomeName, localHome);
}
} catch (NamingException ne) {
throw new ServiceLocaterException(ne);
} catch (Exception e) {
throw new ServiceLocaterException(e);
}
return localHome;
}
}





