001 package org.granite.cdi;
002
003 import javax.enterprise.inject.spi.BeanManager;
004 import javax.naming.InitialContext;
005 import javax.naming.NameNotFoundException;
006 import javax.servlet.ServletContext;
007
008
009 public class CDIUtils {
010
011 public static BeanManager lookupBeanManager(ServletContext servletContext) {
012 BeanManager manager = (BeanManager)servletContext.getAttribute(BeanManager.class.getName());
013 if (manager != null)
014 return manager;
015 manager = (BeanManager)servletContext.getAttribute("org.jboss.weld.environment.servlet.javax.enterprise.inject.spi.BeanManager");
016 if (manager != null)
017 return manager;
018
019 InitialContext ic = null;
020 try {
021 ic = new InitialContext();
022 // Standard JNDI binding
023 return (BeanManager)ic.lookup("java:comp/BeanManager");
024 }
025 catch (NameNotFoundException e) {
026 if (ic == null)
027 throw new RuntimeException("No InitialContext");
028
029 // Weld/Tomcat
030 try {
031 return (BeanManager)ic.lookup("java:comp/env/BeanManager");
032 }
033 catch (Exception e1) {
034 // JBoss 5/6 (maybe obsolete in Weld 1.0+)
035 try {
036 return (BeanManager)ic.lookup("java:app/BeanManager");
037 }
038 catch (Exception e2) {
039 throw new RuntimeException("Could not find Bean Manager", e2);
040 }
041 }
042 }
043 catch (Exception e) {
044 throw new RuntimeException("Could not find Bean Manager", e);
045 }
046 }
047 }