
package de.ivu.elect.jee.cdi;

import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class BeanManagerUtil {

  public static BeanManager getBeanManager() {
    try {
      InitialContext initialContext = new InitialContext();
      return (BeanManager) initialContext.lookup("java:comp/BeanManager");
    } catch (NamingException e) {
      throw new RuntimeException(e.getMessage(), e);
    }
  }

  public static <B> B getBeanByName(String name) {
    BeanManager bm = getBeanManager();
    Bean bean = bm.getBeans(name).iterator().next();
    return getBean(bm, bean);
  }

  public static <B> B getBeanByClass(Class<B> clazz) {
    BeanManager bm = getBeanManager();
    Bean bean = bm.getBeans(clazz).iterator().next();
    return getBean(bm, bean);
  }

  private static <B> B getBean(BeanManager bm, Bean bean) {
    CreationalContext ctx = bm.createCreationalContext(bean);
    return (B) bm.getReference(bean, bean.getBeanClass(), ctx); // ELECT-2433
  }
}
