1 8 package org.apache.avalon.excalibur.lang; 9 10 import java.util.HashMap ; 11 import java.util.Map ; 12 import java.util.Iterator ; 13 14 40 public final class ThreadContext 41 { 42 45 private final static RuntimePermission c_setThreadContext = 46 new RuntimePermission ( "ThreadContext.setThreadContext" ); 47 48 private final static InheritableThreadLocal c_context = new InheritableThreadLocal (); 49 50 private final ThreadContextAccessor m_accessor = new InnerThreadContextAccessor(); 52 53 private final ThreadContextPolicy m_policy; 55 56 private final HashMap m_map; 58 59 64 public static ThreadContext getThreadContext() 65 { 66 return (ThreadContext)c_context.get(); 67 } 68 69 78 public static void setThreadContext( final ThreadContext threadContext ) 79 throws SecurityException 80 { 81 final SecurityManager securityManager = System.getSecurityManager(); 82 if( null != securityManager ) 83 { 84 securityManager.checkPermission( c_setThreadContext ); 85 } 86 87 final ThreadContext oldThreadContext = (ThreadContext)c_context.get(); 88 if( null != oldThreadContext ) oldThreadContext.deactivate(); 89 90 c_context.set( threadContext ); 91 if( null != threadContext ) 92 { 93 threadContext.activate(); 94 } 95 } 96 97 103 public ThreadContext( final ThreadContextPolicy policy, final Map map ) 104 { 105 if( null == policy ) 106 { 107 throw new NullPointerException ( "policy property is null" ); 108 } 109 110 if( null == map ) 111 { 112 throw new NullPointerException ( "map property is null" ); 113 } 114 115 m_policy = policy; 116 m_map = new HashMap (); 117 118 final Iterator keys = map.keySet().iterator(); 119 while( keys.hasNext() ) 120 { 121 final Object key = keys.next(); 122 final Object value = map.get( key ); 123 final String keyString = key.toString(); 124 125 m_policy.verifyKeyValue( keyString, value ); 126 m_map.put( keyString, value ); 127 } 128 } 129 130 133 private void activate() 134 { 135 m_policy.activate( m_accessor ); 136 } 137 138 141 private void deactivate() 142 { 143 m_policy.deactivate( m_accessor ); 144 } 145 146 149 private class InnerThreadContextAccessor implements ThreadContextAccessor 150 { 151 public boolean containsKey( final String key ) 152 { 153 if( null == m_map ) return false; 154 else return m_map.containsKey( key ); 155 } 156 157 public Object get( final String key ) 158 { 159 if( null == m_map ) return null; 160 else return m_map.get( key ); 161 } 162 } 163 } 164 | Popular Tags |