001 package com.mockrunner.ejb; 002 003 import javax.naming.Context; 004 import javax.naming.InitialContext; 005 import javax.naming.NamingException; 006 import javax.transaction.UserTransaction; 007 008 import org.mockejb.jndi.MockContextFactory; 009 010 import com.mockrunner.base.NestedApplicationException; 011 012 /** 013 * Util class for creating and managing the JNDI context 014 */ 015 public class JNDIUtil 016 { 017 /** 018 * Calls <code>MockContextFactory.setAsInitial()</code>, if the 019 * <code>MockContextFactory</code> is not already the current 020 * context factory. 021 */ 022 public static void initMockContextFactory() throws NamingException 023 { 024 String factory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY); 025 if(null == factory || !factory.equals(MockContextFactory.class.getName())) 026 { 027 MockContextFactory.setAsInitial(); 028 } 029 } 030 031 /** 032 * Calls <code>MockContextFactory.revertSetAsInitial()</code>, if the 033 * <code>MockContextFactory</code> is the current context factory. 034 */ 035 public static void resetMockContextFactory() 036 { 037 String factory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY); 038 if(null != factory && factory.equals(MockContextFactory.class.getName())) 039 { 040 MockContextFactory.revertSetAsInitial(); 041 } 042 } 043 044 /** 045 * Tries to get the JNDI context from the specified configuration. 046 * If the configuration returns <code>null</code> for the context, 047 * this method initializes the MockEJB JNDI implementation. 048 * @param configuration the configuration 049 * @return the JNDI context 050 */ 051 public static Context getContext(Configuration configuration) 052 { 053 Context context = configuration.getContext(); 054 if(null == context) 055 { 056 try 057 { 058 JNDIUtil.initMockContextFactory(); 059 context = new InitialContext(); 060 } 061 catch(NamingException exc) 062 { 063 throw new NestedApplicationException(exc); 064 } 065 configuration.setContext(context); 066 } 067 return context; 068 } 069 070 /** 071 * Binds the specified <code>UserTransaction</code> to the specified 072 * JNDI context. 073 * @param configuration the configuration 074 * @param context the JNDI context 075 * @param transaction the <code>UserTransaction</code> 076 */ 077 public static void bindUserTransaction(Configuration configuration, Context context, UserTransaction transaction) throws NamingException 078 { 079 if(configuration.getBindMockUserTransactionToJNDI()) 080 { 081 context.rebind(configuration.getUserTransactionJNDIName(), transaction); 082 context.rebind("javax.transaction.UserTransaction", transaction); 083 context.rebind("java:comp/UserTransaction", transaction); 084 } 085 } 086 }