1 17 package org.apache.log; 18 19 import java.io.Serializable ; 20 import java.util.Hashtable ; 21 22 41 public final class ContextMap 42 implements Serializable 43 { 44 private static final ThreadLocal c_localContext = new InheritableThreadLocal (); 46 47 private final ContextMap m_parent; 48 49 private Hashtable m_map = new Hashtable (); 51 52 private transient boolean m_readOnly; 54 55 63 public static final ContextMap getCurrentContext() 64 { 65 return getCurrentContext( true ); 66 } 67 68 77 public static final ContextMap getCurrentContext( final boolean autocreate ) 78 { 79 ContextMap context = (ContextMap)c_localContext.get(); 81 82 if( null == context && autocreate ) 83 { 84 context = new ContextMap(); 85 c_localContext.set( context ); 86 } 87 88 return context; 89 } 90 91 96 public static final void bind( final ContextMap context ) 97 { 98 c_localContext.set( context ); 100 } 101 102 105 public ContextMap() 106 { 107 this( null ); 108 } 109 110 115 public ContextMap( final ContextMap parent ) 116 { 117 m_parent = parent; 118 } 119 120 125 public void makeReadOnly() 126 { 127 m_readOnly = true; 128 } 129 130 135 public boolean isReadOnly() 136 { 137 return m_readOnly; 138 } 139 140 144 public void clear() 145 { 146 checkReadable(); 147 148 m_map.clear(); 149 } 150 151 158 public Object get( final String key, final Object defaultObject ) 159 { 160 final Object object = get( key ); 161 162 if( null != object ) 163 { 164 return object; 165 } 166 else 167 { 168 return defaultObject; 169 } 170 } 171 172 178 public Object get( final String key ) 179 { 180 if( key == null ) 181 return null; 182 183 final Object result = m_map.get( key ); 184 185 if( null == result && null != m_parent ) 186 { 187 return m_parent.get( key ); 188 } 189 190 return result; 191 } 192 193 199 public void set( final String key, final Object value ) 200 { 201 checkReadable(); 202 203 if( value == null ) 204 { 205 m_map.remove( key ); 206 } 207 else 208 { 209 m_map.put( key, value ); 210 } 211 } 212 213 218 224 225 230 public int getSize() 231 { 232 return m_map.size(); 233 } 234 235 240 private Object readResolve() 241 { 242 makeReadOnly(); 243 return this; 244 } 245 246 249 private void checkReadable() 250 { 251 if( isReadOnly() ) 252 { 253 throw new IllegalStateException ( "ContextMap is read only and can not be modified" ); 254 } 255 } 256 } 257 | Popular Tags |