/* * 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()); public static final String BEAN_MANAGER_JNDI = "java:comp/BeanManager"; private static BeanManager BEAN_MANAGER = null; /** * Sets the bean manager (mainly for testability). * * @param aMgr * Bean manager. */ public static void setBeanManager(BeanManager aMgr) { BEAN_MANAGER = aMgr; } /** * Looks up the bean manager if not already cached and returns it. * * @return Bean manager. */ public static BeanManager lookup() { if (BEAN_MANAGER == null) { try { InitialContext ctx = new InitialContext(); BEAN_MANAGER = (BeanManager) ctx.lookup(BEAN_MANAGER_JNDI); LOGGER.info("Beanmanager successfully located"); } catch (NamingException e) { LOGGER.warning("No beanmanager was found, using null"); BEAN_MANAGER = null; } } return BEAN_MANAGER; } }