c7e4e2fde323bd3c390cebcf8b59dde3adf24b73
[utils] / test / enterprise / src / main / java / org / wamblee / support / jndi / StubInitialContextFactory.java
1 package org.wamblee.support.jndi;
2
3 import java.util.HashMap;
4 import java.util.Hashtable;
5 import java.util.Map;
6
7 import javax.naming.Context;
8 import javax.naming.InitialContext;
9 import javax.naming.NamingException;
10 import javax.naming.spi.InitialContextFactory;
11
12 /**
13  * Test initial context factory used for testing software in a Java SE
14  * environnment that uses JNDI to retrieve objects.
15  * 
16  * See {@link #bind(String, Object)} to resp. register the initial context.
17  * 
18  * To bind objects in the JNDI tree simply use the standard JNDI api: <code>
19  *   InitialContext context = new InitialContext();
20  *   MyClass myObj = ...; 
21  *   context.bind("a/b", myObj); 
22  * </code>
23  */
24 public class StubInitialContextFactory implements InitialContextFactory {
25
26         private static Context context;
27
28         private static void initialize() {
29                 try {
30                         context = new StubInitialContext();
31                 } catch (NamingException e) { // can't happen.
32                         throw new RuntimeException(e);
33                 }
34         }
35
36         /**
37          * This method must be called to register this initial context factory as
38          * the default implementation for JNDI.
39          * 
40          * @throws Exception
41          */
42         public static void register() {
43                 // sets up the InitialContextFactoryForTest as default factory.
44                 System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
45                                 StubInitialContextFactory.class.getName());
46                 if (context == null) {
47                         initialize();
48                 }
49         }
50         
51         /**
52          * Unregisters the initial context factory 
53          */
54         public static void unregister() { 
55                 System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "");
56                 context = null; 
57         }
58
59         public Context getInitialContext(Hashtable<?, ?> environment)
60                         throws NamingException {
61                 return context;
62         }
63 }