01: package com.mockrunner.ejb;
02:
03: import javax.naming.Context;
04: import javax.naming.InitialContext;
05: import javax.naming.NamingException;
06: import javax.transaction.UserTransaction;
07:
08: import org.mockejb.jndi.MockContextFactory;
09:
10: import com.mockrunner.base.NestedApplicationException;
11:
12: /**
13: * Util class for creating and managing the JNDI context
14: */
15: public class JNDIUtil {
16: /**
17: * Calls <code>MockContextFactory.setAsInitial()</code>, if the
18: * <code>MockContextFactory</code> is not already the current
19: * context factory.
20: */
21: public static void initMockContextFactory() throws NamingException {
22: String factory = System
23: .getProperty(Context.INITIAL_CONTEXT_FACTORY);
24: if (null == factory
25: || !factory.equals(MockContextFactory.class.getName())) {
26: MockContextFactory.setAsInitial();
27: }
28: }
29:
30: /**
31: * Calls <code>MockContextFactory.revertSetAsInitial()</code>, if the
32: * <code>MockContextFactory</code> is the current context factory.
33: */
34: public static void resetMockContextFactory() {
35: String factory = System
36: .getProperty(Context.INITIAL_CONTEXT_FACTORY);
37: if (null != factory
38: && factory.equals(MockContextFactory.class.getName())) {
39: MockContextFactory.revertSetAsInitial();
40: }
41: }
42:
43: /**
44: * Tries to get the JNDI context from the specified configuration.
45: * If the configuration returns <code>null</code> for the context,
46: * this method initializes the MockEJB JNDI implementation.
47: * @param configuration the configuration
48: * @return the JNDI context
49: */
50: public static Context getContext(Configuration configuration) {
51: Context context = configuration.getContext();
52: if (null == context) {
53: try {
54: JNDIUtil.initMockContextFactory();
55: context = new InitialContext();
56: } catch (NamingException exc) {
57: throw new NestedApplicationException(exc);
58: }
59: configuration.setContext(context);
60: }
61: return context;
62: }
63:
64: /**
65: * Binds the specified <code>UserTransaction</code> to the specified
66: * JNDI context.
67: * @param configuration the configuration
68: * @param context the JNDI context
69: * @param transaction the <code>UserTransaction</code>
70: */
71: public static void bindUserTransaction(Configuration configuration,
72: Context context, UserTransaction transaction)
73: throws NamingException {
74: if (configuration.getBindMockUserTransactionToJNDI()) {
75: context.rebind(configuration.getUserTransactionJNDIName(),
76: transaction);
77: context.rebind("javax.transaction.UserTransaction",
78: transaction);
79: context.rebind("java:comp/UserTransaction", transaction);
80: }
81: }
82: }
|