1 9 package javolution.context; 10 import j2me.lang.UnsupportedOperationException; 11 import javolution.util.FastMap; 12 13 39 public class LocalContext extends Context { 40 41 44 private static Factory FACTORY = new Factory() { 45 protected Object create() { 46 return new LocalContext(); 47 } 48 }; 49 50 54 final FastMap _references = new FastMap(); 55 56 59 public LocalContext() { 60 } 61 62 68 public staticContext current() { 69 for (Context ctx = Context.current(); ctx != null; ctx = ctx.getOuter()) { 70 if (ctx instanceof LocalContext) 71 return (LocalContext) ctx; 72 } 73 return null; 74 } 75 76 79 public static void enter() { 80 LocalContext ctx = (LocalContext) FACTORY.object(); 81 ctx._isInternal = true; 82 Context.enter(ctx); 83 } 84 private transient boolean _isInternal; 85 86 92 public static void exit() { 93 LocalContext ctx = (LocalContext) Context.current(); 94 if (!ctx._isInternal) throw new UnsupportedOperationException 95 ("The context to exit must be specified"); 96 ctx._isInternal = false; 97 Context.exitNoCheck(ctx); 98 FACTORY.recycle(ctx); 99 } 100 101 protected void enterAction() { 103 } 105 106 protected void exitAction() { 108 _references.clear(); 109 } 110 111 138 public static class Referenceimplements javolution.lang.Reference { 139 140 143 private Object _defaultValue; 144 145 149 private boolean _hasBeenLocallyOverriden; 150 151 154 public Reference() { 155 this(null); 156 } 157 158 163 public Reference(Object defaultValue) { 164 _defaultValue = defaultValue; 165 } 166 167 175 public final Object get() { 176 return (_hasBeenLocallyOverriden) ? retrieveValue() : _defaultValue; 177 } 178 179 private Object retrieveValue() { 180 for (Context ctx = Context.current(); ctx != null; ctx = ctx.getOuter()) { 181 if (ctx instanceof LocalContext) { 182 LocalContext localContext = (LocalContext) ctx; 183 Object value = localContext._references.get(this); 184 if (value != null) { 185 return (Object ) value; 186 } 187 } 188 } 189 return _defaultValue; 191 } 192 193 199 public void set(Object value) { 200 LocalContext ctx = (LocalContext) LocalContext.current(); 201 if (ctx != null) { 202 FastMap references = ctx._references; 203 references.put(this, value); 204 _hasBeenLocallyOverriden = true; 205 return; 206 } 207 _defaultValue = value; 209 } 210 211 216 public Object getDefault() { 217 return _defaultValue; 218 } 219 220 226 public Object getLocal() { 227 LocalContext ctx = (LocalContext) LocalContext.current(); 228 return (ctx != null) ? (Object ) ctx._references.get(this) 229 : _defaultValue; 230 } 231 232 237 public void setDefault(Object defaultValue) { 238 _defaultValue = defaultValue; 239 } 240 241 247 public String toString() { 248 return String.valueOf(this.get()); 249 } 250 } 251 } | Popular Tags |