1 11 12 13 package com.sun.jmx.snmp; 14 15 import java.util.Stack ; 16 import java.util.EmptyStackException ; 17 18 53 public class ThreadContext implements Cloneable { 54 55 84 85 87 private ThreadContext previous; 88 private String key; 89 private Object value; 90 91 private ThreadContext(ThreadContext previous, String key, Object value) { 92 this.previous = previous; 93 this.key = key; 94 this.value = value; 95 } 96 97 112 public static Object get(String key) throws IllegalArgumentException { 113 ThreadContext context = contextContaining(key); 114 if (context == null) 115 return null; 116 else 117 return context.value; 118 } 119 120 134 public static boolean contains(String key) 135 throws IllegalArgumentException { 136 return (contextContaining(key) != null); 137 } 138 139 145 private static ThreadContext contextContaining(String key) 146 throws IllegalArgumentException { 147 if (key == null) 148 throw new IllegalArgumentException ("null key"); 149 for (ThreadContext context = getContext(); 150 context != null; 151 context = context.previous) { 152 if (key.equals(context.key)) 153 return context; 154 156 } 157 return null; 158 } 159 160 184 199 public static ThreadContext push(String key, Object value) 200 throws IllegalArgumentException { 201 if (key == null) 202 throw new IllegalArgumentException ("null key"); 203 204 ThreadContext oldContext = getContext(); 205 if (oldContext == null) 206 oldContext = new ThreadContext(null, null, null); ThreadContext newContext = new ThreadContext(oldContext, key, value); 208 setContext(newContext); 209 return oldContext; 210 } 211 212 219 public static ThreadContext getThreadContext() { 220 return getContext(); 221 } 222 223 235 public static void restore(ThreadContext oldContext) 236 throws NullPointerException , IllegalArgumentException { 237 243 if (oldContext == null) 244 throw new NullPointerException (); 245 246 247 for (ThreadContext context = getContext(); 248 context != oldContext; 249 context = context.previous) { 250 if (context == null) { 251 throw new IllegalArgumentException ("Restored context is not " + 252 "contained in current " + 253 "context"); 254 } 255 } 256 257 262 if (oldContext.key == null) 263 oldContext = null; 264 265 setContext(oldContext); 266 } 267 268 289 295 public void setInitialContext(ThreadContext context) 296 throws IllegalArgumentException { 297 299 if (getContext() != null) 300 throw new IllegalArgumentException ("previous context not empty"); 301 setContext(context); 302 } 303 304 private static ThreadContext getContext() { 305 return (ThreadContext) localContext.get(); 306 } 307 308 private static void setContext(ThreadContext context) { 309 localContext.set(context); 310 } 311 312 private static ThreadLocal localContext = new ThreadLocal (); 313 } 314 | Popular Tags |