package WEB-INF.classes.wenrgise.common.utility;

import java.util.HashMap;
import javax.ejb.EJBLocalHome;
import javax.naming.Context;
import javax.naming.NamingException;
import wenrgise.common.exception.EnrgiseSystemException;
import wenrgise.common.utility.ContextProvider;

public class ServiceLocator {
  private HashMap homeCache;
  
  private final HashMap cacheMap = new HashMap();
  
  private static wenrgise.common.utility.ServiceLocator serviceLocator = new wenrgise.common.utility.ServiceLocator();
  
  private ServiceLocator() {
    try {
      this.homeCache = new HashMap();
    } catch (Throwable e) {
      e.printStackTrace();
    } 
  }
  
  public static wenrgise.common.utility.ServiceLocator getLocator() {
    return serviceLocator;
  }
  
  public Object getService(String jndiName) throws EnrgiseSystemException {
    try {
      if (!this.homeCache.containsKey(jndiName.trim())) {
        Context context = ContextProvider.getContext();
        this.homeCache.put(jndiName.trim(), context.lookup(jndiName.trim()));
      } 
    } catch (NamingException oNa) {
      oNa.printStackTrace();
      System.out.println(oNa.getExplanation());
      throw new EnrgiseSystemException(oNa);
    } catch (Exception oEx) {
      oEx.printStackTrace();
      throw new EnrgiseSystemException(oEx);
    } 
    return this.homeCache.get(jndiName.trim());
  }
  
  public Object getLocalService(String jndiHomeName) throws EnrgiseSystemException {
    Object obj = null;
    try {
      Context context = ContextProvider.getLocalContext();
      if (this.cacheMap.containsKey(jndiHomeName)) {
        obj = this.cacheMap.get(jndiHomeName);
      } else {
        obj = context.lookup(jndiHomeName);
        this.cacheMap.put(jndiHomeName, obj);
      } 
    } catch (NamingException ne) {
      ne.printStackTrace();
      throw new EnrgiseSystemException(ne);
    } 
    return obj;
  }
  
  public EJBLocalHome getLocalHome(String jndiHomeName) throws EnrgiseSystemException {
    System.out.println(String.valueOf("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").concat(String.valueOf(jndiHomeName)));
    EJBLocalHome home = null;
    try {
      Context context = ContextProvider.getLocalContext();
      if (this.cacheMap.containsKey(jndiHomeName)) {
        home = (EJBLocalHome)this.cacheMap.get(jndiHomeName);
      } else {
        home = (EJBLocalHome)context.lookup(String.valueOf("java:comp/env/").concat(String.valueOf(jndiHomeName)));
        this.cacheMap.put(jndiHomeName, home);
      } 
    } catch (NamingException ne) {
      System.out.println(ne);
      ne.printStackTrace();
      throw new EnrgiseSystemException(ne);
    } catch (Exception oEx) {
      oEx.printStackTrace();
      throw new EnrgiseSystemException(oEx);
    } 
    return home;
  }
}
