cdi project in initial revision
[utils] / support / cdi / src / main / java / org / wamblee / cdi / BeanManagerLookup.java
diff --git a/support/cdi/src/main/java/org/wamblee/cdi/BeanManagerLookup.java b/support/cdi/src/main/java/org/wamblee/cdi/BeanManagerLookup.java
new file mode 100644 (file)
index 0000000..2952653
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * Copyright 2005-2010 the original author or authors.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wamblee.cdi;
+
+import java.util.logging.Logger;
+
+import javax.enterprise.inject.spi.BeanManager;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+
+/**
+ * Class that encapsulates beanmanager lookup in a way so that the lookup can be
+ * explicitly overriden (e.g. for unit test).
+ * 
+ * In case no bean manager is found the beanmanager is set to null and the
+ * problem is logged.
+ * 
+ * @author Erik Brakkee
+ */
+public class BeanManagerLookup {
+
+    private static final Logger LOGGER = Logger
+        .getLogger(BeanManagerLookup.class.getName());
+
+    private static final String BEAN_MANAGER_JNDI = "java:comp/BeanManager";
+    private static BeanManager mgr = null;
+
+    /**
+     * Sets the bean manager (mainly for testability).
+     * 
+     * @param aMgr
+     *            Bean manager.
+     */
+    public static void setBeanManager(BeanManager aMgr) {
+        mgr = aMgr;
+    }
+
+    /**
+     * Looks up the bean manager if not already cached and returns it.
+     * 
+     * @return Bean manager.
+     */
+    public static BeanManager lookup() {
+        if (mgr == null) {
+            try {
+                InitialContext ctx = new InitialContext();
+                mgr = (BeanManager) ctx.lookup(BEAN_MANAGER_JNDI);
+                LOGGER.info("Beanmanager successfully located");
+            } catch (NamingException e) {
+                LOGGER.warning("No beanmanager was found, using null");
+                mgr = null;
+            }
+        }
+        return mgr;
+    }
+}