1 30 31 package de.susebox.java.lang; 32 33 import java.util.Hashtable ; 37 import de.susebox.java.lang.ExtNullPointerException; 38 39 40 44 58 public final class EnvironmentProvider { 59 60 79 public static Environment getEnvironment(Object obj) { 80 Environment env = null; 81 82 if (obj != null && _environmentMap != null) { 84 synchronized(_syncMonitor) { 85 Object iterObj = obj; 86 87 do { 88 if (iterObj instanceof Class ) { 89 env = (Environment)_environmentMap.get(new EnvironmentKey((Class )iterObj)); 90 iterObj = ((Class )iterObj).getSuperclass(); 91 } else { 92 env = (Environment)_environmentMap.get(iterObj); 93 iterObj = iterObj.getClass(); 94 } 95 if (env != null) { 96 break; 97 } 98 } while (iterObj instanceof Class ); 99 } 100 } 101 102 if (env == null) { 104 synchronized(_syncMonitor) { 105 if (_defaultEnvironment == null) { 106 _defaultEnvironment = new DefaultEnvironment(); 107 } 108 env = _defaultEnvironment; 109 } 110 } 111 return env; 112 } 113 114 123 public static void setEnvironment(Object obj, Environment env) throws NullPointerException { 124 if (obj == null) { 126 throw new ExtNullPointerException("No object given."); 127 } else if (env == null) { 128 throw new ExtNullPointerException("No environment given."); 129 } 130 131 synchronized(_syncMonitor) { 133 if (_environmentMap == null) { 134 _environmentMap = new Hashtable (); 135 } 136 137 if (obj instanceof Class ) { 139 _environmentMap.put(new EnvironmentKey((Class )obj), env); 140 } else { 141 _environmentMap.put(obj, env); 142 } 143 } 144 } 145 146 147 153 public static void removeEnvironment(Object obj) { 154 if (obj != null && _environmentMap != null) { 155 if (obj instanceof Class ) { 156 _environmentMap.remove(new EnvironmentKey((Class )obj)); 157 } else { 158 _environmentMap.remove(obj); 159 } 160 } 161 } 162 163 164 168 175 static final class EnvironmentKey { 176 177 184 public EnvironmentKey(Class cl) { 185 synchronized(this) { 186 _class = cl; 187 _thread = Thread.currentThread(); 188 } 189 } 190 191 198 public boolean equals(Object obj) { 199 if (obj == this) { 200 return true; 201 } else if (obj == null) { 202 return false; 203 } else if ( ! (obj instanceof EnvironmentKey)) { 204 return false; 205 } else { 206 EnvironmentKey key = (EnvironmentKey)obj; 207 208 if (_thread == key._thread && _class.equals(key._class)) { 209 return true; 210 } else { 211 return false; 212 } 213 } 214 } 215 216 221 public int hashCode() { 222 return (_thread.hashCode() << 4) + _class.getName().hashCode(); 223 } 224 225 private Class _class = null; 229 private Thread _thread = null; 230 } 231 232 233 private static DefaultEnvironment _defaultEnvironment = null; 237 private static Hashtable _environmentMap = null; 238 private static Object _syncMonitor = new Object (); 239 } 240 241 | Popular Tags |