code style improvements.
[utils] / test / enterprise / src / main / java / org / wamblee / support / jndi / StubInitialContextFactory.java
1 /*
2  * Copyright 2005-2010 the original author or authors.
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * 
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  * 
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */ 
16 package org.wamblee.support.jndi;
17
18 import java.util.Hashtable;
19
20 import javax.naming.Context;
21 import javax.naming.NamingException;
22 import javax.naming.spi.InitialContextFactory;
23
24 /**
25  * Test initial context factory used for testing software in a Java SE
26  * environnment that uses JNDI to retrieve objects.
27  * 
28  * See {@link #bind(String, Object)} to resp. register the initial context.
29  * 
30  * To start mocking the JNDI tree, call {@link #register()}. 
31  * 
32  * To bind objects in the JNDI tree simply use the standard JNDI api: 
33  * <pre>
34  *   InitialContext context = new InitialContext();
35  *   MyClass myObj = ...; 
36  *   context.bind("a/b", myObj); 
37  * </pre>
38  * 
39  * When finished with a test case, call {@link #unregister()} to unregister the 
40  * JNDI tree again. 
41  */
42 public class StubInitialContextFactory implements InitialContextFactory {
43
44     private static Context CONTEXT;
45
46     private static void initialize() {
47         try {
48             CONTEXT = new StubInitialContext();
49         } catch (NamingException e) { // can't happen.
50             throw new RuntimeException(e);
51         }
52     }
53
54     /**
55      * This method must be called to register this initial context factory as
56      * the default implementation for JNDI.
57      * 
58      * @throws Exception
59      */
60     public static void register() {
61         // sets up the InitialContextFactoryForTest as default factory.
62         System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
63             StubInitialContextFactory.class.getName());
64         if (CONTEXT == null) {
65             initialize();
66         }
67     }
68
69     /**
70      * Unregisters the initial context factory
71      */
72     public static void unregister() {
73         System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "");
74         CONTEXT = null;
75     }
76
77     public Context getInitialContext(Hashtable<?, ?> aEnvironment)
78         throws NamingException {
79         return CONTEXT;
80     }
81 }