1 8 package org.jivesoftware.util.log; 9 10 import java.io.ObjectStreamException ; 11 import java.io.Serializable ; 12 import java.util.Collections ; 13 import java.util.HashMap ; 14 import java.util.Map ; 15 16 34 public final class ContextMap implements Serializable { 35 private static final ThreadLocal c_context = new InheritableThreadLocal (); 37 38 private final ContextMap m_parent; 39 40 private Map m_map = Collections.synchronizedMap(new HashMap ()); 42 43 private transient boolean m_readOnly; 45 46 54 public final static ContextMap getCurrentContext() { 55 return getCurrentContext(true); 56 } 57 58 67 public final static ContextMap getCurrentContext(final boolean autocreate) { 68 ContextMap context = (ContextMap)c_context.get(); 70 71 if (null == context && autocreate) { 72 context = new ContextMap(); 73 c_context.set(context); 74 } 75 76 return context; 77 } 78 79 84 public final static void bind(final ContextMap context) { 85 c_context.set(context); 87 } 88 89 92 public ContextMap() { 93 this(null); 94 } 95 96 101 public ContextMap(final ContextMap parent) { 102 m_parent = parent; 103 } 104 105 110 public void makeReadOnly() { 111 m_readOnly = true; 112 } 113 114 119 public boolean isReadOnly() { 120 return m_readOnly; 121 } 122 123 126 public void clear() { 127 checkReadable(); 128 129 m_map.clear(); 130 } 131 132 139 public Object get(final String key, final Object defaultObject) { 140 final Object object = get(key); 141 142 if (null != object) 143 return object; 144 else 145 return defaultObject; 146 } 147 148 154 public Object get(final String key) { 155 final Object result = m_map.get(key); 156 157 if (null == result && null != m_parent) { 158 return m_parent.get(key); 159 } 160 161 return result; 162 } 163 164 170 public void set(final String key, final Object value) { 171 checkReadable(); 172 173 if (value == null) { 174 m_map.remove(key); 175 } 176 else { 177 m_map.put(key, value); 178 } 179 } 180 181 182 187 public int getSize() { 188 return m_map.size(); 189 } 190 191 197 private Object readResolve() throws ObjectStreamException { 198 makeReadOnly(); 199 return this; 200 } 201 202 205 private void checkReadable() { 206 if (isReadOnly()) { 207 throw new IllegalStateException ("ContextMap is read only and can not be modified"); 208 } 209 } 210 } 211 | Popular Tags |