d65968a21e5e22e00aad4e5999fb06522d97ac88
[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 bind objects in the JNDI tree simply use the standard JNDI api: <code>
31  *   InitialContext context = new InitialContext();
32  *   MyClass myObj = ...; 
33  *   context.bind("a/b", myObj); 
34  * </code>
35  */
36 public class StubInitialContextFactory implements InitialContextFactory {
37
38     private static Context CONTEXT;
39
40     private static void initialize() {
41         try {
42             CONTEXT = new StubInitialContext();
43         } catch (NamingException e) { // can't happen.
44             throw new RuntimeException(e);
45         }
46     }
47
48     /**
49      * This method must be called to register this initial context factory as
50      * the default implementation for JNDI.
51      * 
52      * @throws Exception
53      */
54     public static void register() {
55         // sets up the InitialContextFactoryForTest as default factory.
56         System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
57             StubInitialContextFactory.class.getName());
58         if (CONTEXT == null) {
59             initialize();
60         }
61     }
62
63     /**
64      * Unregisters the initial context factory
65      */
66     public static void unregister() {
67         System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "");
68         CONTEXT = null;
69     }
70
71     public Context getInitialContext(Hashtable<?, ?> aEnvironment)
72         throws NamingException {
73         return CONTEXT;
74     }
75 }