1 16 17 package org.springframework.mock.jndi; 18 19 import java.util.Hashtable ; 20 21 import javax.naming.Context ; 22 import javax.naming.NamingException ; 23 import javax.naming.spi.InitialContextFactory ; 24 import javax.naming.spi.InitialContextFactoryBuilder ; 25 import javax.naming.spi.NamingManager ; 26 27 import org.apache.commons.logging.Log; 28 import org.apache.commons.logging.LogFactory; 29 30 80 public class SimpleNamingContextBuilder implements InitialContextFactoryBuilder { 81 82 83 private static SimpleNamingContextBuilder activated; 84 85 86 91 public static SimpleNamingContextBuilder getCurrentContextBuilder() { 92 return activated; 93 } 94 95 104 public static SimpleNamingContextBuilder emptyActivatedContextBuilder() throws NamingException { 105 if (activated != null) { 106 activated.clear(); 108 } 109 else { 110 SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder(); 112 builder.activate(); 114 } 115 return activated; 116 } 117 118 119 private final Log logger = LogFactory.getLog(getClass()); 120 121 private final Hashtable boundObjects = new Hashtable (); 122 123 124 132 public void activate() throws IllegalStateException , NamingException { 133 logger.info("Activating simple JNDI environment"); 134 if (NamingManager.hasInitialContextFactoryBuilder()) { 135 throw new IllegalStateException ( 136 "Cannot activate SimpleNamingContextBuilder: there is already a JNDI provider registered. " + 137 "Note that JNDI is a JVM-wide service, shared at the JVM system class loader level, " + 138 "with no reset option. As a consequence, a JNDI provider must only be registered once per JVM."); 139 } 140 NamingManager.setInitialContextFactoryBuilder(this); 141 activated = this; 142 } 143 144 147 public void clear() { 148 this.boundObjects.clear(); 149 } 150 151 157 public void bind(String name, Object obj) { 158 if (logger.isInfoEnabled()) { 159 logger.info("Static JNDI binding: [" + name + "] = [" + obj + "]"); 160 } 161 this.boundObjects.put(name, obj); 162 } 163 164 169 public InitialContextFactory createInitialContextFactory(Hashtable environment) { 170 return new InitialContextFactory () { 171 public Context getInitialContext(Hashtable environment) { 172 return new SimpleNamingContext("", boundObjects, environment); 173 } 174 }; 175 } 176 177 } 178 | Popular Tags |