checkstyle
[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.HashMap;
19 import java.util.Hashtable;
20 import java.util.Map;
21
22 import javax.naming.Context;
23 import javax.naming.InitialContext;
24 import javax.naming.NamingException;
25 import javax.naming.spi.InitialContextFactory;
26
27 /**
28  * Test initial context factory used for testing software in a Java SE
29  * environnment that uses JNDI to retrieve objects.
30  * 
31  * See {@link #bind(String, Object)} to resp. register the initial context.
32  * 
33  * To bind objects in the JNDI tree simply use the standard JNDI api: <code>
34  *   InitialContext context = new InitialContext();
35  *   MyClass myObj = ...; 
36  *   context.bind("a/b", myObj); 
37  * </code>
38  */
39 public class StubInitialContextFactory implements InitialContextFactory {
40
41     private static Context CONTEXT;
42
43     private static void initialize() {
44         try {
45             CONTEXT = new StubInitialContext();
46         } catch (NamingException e) { // can't happen.
47             throw new RuntimeException(e);
48         }
49     }
50
51     /**
52      * This method must be called to register this initial context factory as
53      * the default implementation for JNDI.
54      * 
55      * @throws Exception
56      */
57     public static void register() {
58         // sets up the InitialContextFactoryForTest as default factory.
59         System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
60             StubInitialContextFactory.class.getName());
61         if (CONTEXT == null) {
62             initialize();
63         }
64     }
65
66     /**
67      * Unregisters the initial context factory
68      */
69     public static void unregister() {
70         System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "");
71         CONTEXT = null;
72     }
73
74     public Context getInitialContext(Hashtable<?, ?> aEnvironment)
75         throws NamingException {
76         return CONTEXT;
77     }
78 }