X-Git-Url: http://wamblee.org/gitweb/?a=blobdiff_plain;f=support%2Fcdi%2Fsrc%2Fmain%2Fjava%2Forg%2Fwamblee%2Fcdi%2FBeanManagerLookup.java;fp=support%2Fcdi%2Fsrc%2Fmain%2Fjava%2Forg%2Fwamblee%2Fcdi%2FBeanManagerLookup.java;h=2952653870e18ebcfbf974232bedafb10be522e5;hb=cbb032a4e384ae54d9c7f5f42758622f53a17bb7;hp=0000000000000000000000000000000000000000;hpb=2a90c02cde9e8e31ecd4cf01baf91f798b262eb3;p=utils 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 index 00000000..29526538 --- /dev/null +++ b/support/cdi/src/main/java/org/wamblee/cdi/BeanManagerLookup.java @@ -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; + } +}