1 55 package org.apache.log; 56 57 import java.util.Stack ; 58 59 71 public class ContextStack 72 { 73 private static final ThreadLocal c_context = new ThreadLocal (); 75 76 private Stack m_stack = new Stack (); 78 79 87 public static final ContextStack getCurrentContext() 88 { 89 return getCurrentContext( true ); 90 } 91 92 102 static final ContextStack getCurrentContext( final boolean autocreate ) 103 { 104 ContextStack context = (ContextStack)c_context.get(); 105 106 if( null == context && autocreate ) 107 { 108 context = new ContextStack(); 109 context.push( Thread.currentThread().getName() ); 110 c_context.set( context ); 111 } 112 113 return context; 114 } 115 116 120 public void clear() 121 { 122 m_stack.setSize( 0 ); 123 } 124 125 131 public Object get( final int index ) 132 { 133 return m_stack.elementAt( index ); 134 } 135 136 141 public Object pop() 142 { 143 return m_stack.pop(); 144 } 145 146 151 public void push( final Object context ) 152 { 153 m_stack.push( context ); 154 } 155 156 161 public void set( final ContextStack stack ) 162 { 163 clear(); 164 final int size = stack.m_stack.size(); 165 166 for( int i = 0; i < size; i++ ) 167 { 168 m_stack.push( stack.m_stack.elementAt( i ) ); 169 } 170 } 171 172 177 public int getSize() 178 { 179 return m_stack.size(); 180 } 181 182 188 public String toString() 189 { 190 return toString( getSize() ); 191 } 192 193 201 public String toString( final int count ) 202 { 203 final StringBuffer sb = new StringBuffer (); 204 205 final int end = getSize() - 1; 206 final int start = Math.max( end - count + 1, 0 ); 207 208 for( int i = start; i < end; i++ ) 209 { 210 sb.append( fix( get( i ).toString() ) ); 211 sb.append( '.' ); 212 } 213 214 sb.append( fix( get( end ).toString() ) ); 215 216 return sb.toString(); 217 } 218 219 225 private String fix( final String context ) 226 { 227 return context.replace( '.', '_' ); 228 } 229 } 230 | Popular Tags |