idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
2,700
private Class < ? > loadClass ( final ClassLoader lastLoader , final String className ) { Class < ? > clazz ; if ( lastLoader != null ) { try { clazz = lastLoader . loadClass ( className ) ; if ( clazz != null ) { return clazz ; } } catch ( final Throwable ignore ) { } } try { clazz = LoaderUtil . loadClass ( className ) ; } catch ( final ClassNotFoundException | NoClassDefFoundError e ) { return loadClass ( className ) ; } catch ( final SecurityException e ) { return null ; } return clazz ; }
Loads classes not located via Reflection . getCallerClass .
2,701
private CacheEntry toCacheEntry ( final StackTraceElement stackTraceElement , final Class < ? > callerClass , final boolean exact ) { String location = "?" ; String version = "?" ; ClassLoader lastLoader = null ; if ( callerClass != null ) { try { Bundle bundle = FrameworkUtil . getBundle ( callerClass ) ; if ( bundle != null ) { location = bundle . getBundleId ( ) + ":" + bundle . getSymbolicName ( ) ; version = bundle . getVersion ( ) . toString ( ) ; } } catch ( final Exception ex ) { } lastLoader = callerClass . getClassLoader ( ) ; } return new CacheEntry ( new ExtendedClassInfo ( exact , location , version ) , lastLoader ) ; }
Construct the CacheEntry from the Class s information .
2,702
ExtendedStackTraceElement [ ] toExtendedStackTrace ( final Stack < Class < ? > > stack , final Map < String , CacheEntry > map , final StackTraceElement [ ] rootTrace , final StackTraceElement [ ] stackTrace ) { int stackLength ; if ( rootTrace != null ) { int rootIndex = rootTrace . length - 1 ; int stackIndex = stackTrace . length - 1 ; while ( rootIndex >= 0 && stackIndex >= 0 && rootTrace [ rootIndex ] . equals ( stackTrace [ stackIndex ] ) ) { -- rootIndex ; -- stackIndex ; } this . commonElementCount = stackTrace . length - 1 - stackIndex ; stackLength = stackIndex + 1 ; } else { this . commonElementCount = 0 ; stackLength = stackTrace . length ; } final ExtendedStackTraceElement [ ] extStackTrace = new ExtendedStackTraceElement [ stackLength ] ; Class < ? > clazz = stack . isEmpty ( ) ? null : stack . peek ( ) ; ClassLoader lastLoader = null ; for ( int i = stackLength - 1 ; i >= 0 ; -- i ) { final StackTraceElement stackTraceElement = stackTrace [ i ] ; final String className = stackTraceElement . getClassName ( ) ; ExtendedClassInfo extClassInfo ; if ( clazz != null && className . equals ( clazz . getName ( ) ) ) { final CacheEntry entry = this . toCacheEntry ( stackTraceElement , clazz , true ) ; extClassInfo = entry . element ; lastLoader = entry . loader ; stack . pop ( ) ; clazz = stack . isEmpty ( ) ? null : stack . peek ( ) ; } else { final CacheEntry cacheEntry = map . get ( className ) ; if ( cacheEntry != null ) { final CacheEntry entry = cacheEntry ; extClassInfo = entry . element ; if ( entry . loader != null ) { lastLoader = entry . loader ; } } else { final CacheEntry entry = this . toCacheEntry ( stackTraceElement , this . loadClass ( lastLoader , className ) , false ) ; extClassInfo = entry . element ; map . put ( stackTraceElement . toString ( ) , entry ) ; if ( entry . loader != null ) { lastLoader = entry . loader ; } } } extStackTrace [ i ] = new ExtendedStackTraceElement ( stackTraceElement , extClassInfo ) ; } return extStackTrace ; }
Resolve all the stack entries in this stack trace that are not common with the parent .
2,703
private boolean purge ( final int lowIndex , final int highIndex ) { int suffixLength = 0 ; List renames = new ArrayList ( ) ; StringBuffer buf = new StringBuffer ( ) ; formatFileName ( new Integer ( lowIndex ) , buf ) ; String lowFilename = buf . toString ( ) ; if ( lowFilename . endsWith ( ".gz" ) ) { suffixLength = 3 ; } else if ( lowFilename . endsWith ( ".zip" ) ) { suffixLength = 4 ; } for ( int i = lowIndex ; i <= highIndex ; i ++ ) { File toRename = new File ( lowFilename ) ; boolean isBase = false ; if ( suffixLength > 0 ) { File toRenameBase = new File ( lowFilename . substring ( 0 , lowFilename . length ( ) - suffixLength ) ) ; if ( toRename . exists ( ) ) { if ( toRenameBase . exists ( ) ) { toRenameBase . delete ( ) ; } } else { toRename = toRenameBase ; isBase = true ; } } if ( toRename . exists ( ) ) { if ( i == highIndex ) { if ( ! toRename . delete ( ) ) { return false ; } break ; } buf . setLength ( 0 ) ; formatFileName ( new Integer ( i + 1 ) , buf ) ; String highFilename = buf . toString ( ) ; String renameTo = highFilename ; if ( isBase ) { renameTo = highFilename . substring ( 0 , highFilename . length ( ) - suffixLength ) ; } renames . add ( new FileRenameAction ( toRename , new File ( renameTo ) , true ) ) ; lowFilename = highFilename ; } else { break ; } } for ( int i = renames . size ( ) - 1 ; i >= 0 ; i -- ) { Action action = ( Action ) renames . get ( i ) ; try { if ( ! action . execute ( ) ) { return false ; } } catch ( Exception ex ) { LogLog . warn ( "Exception during purge in RollingFileAppender" , ex ) ; return false ; } } return true ; }
Purge and rename old log files in preparation for rollover
2,704
public static boolean isOperand ( final String s ) { String symbol = s . toLowerCase ( Locale . ENGLISH ) ; return ( ! operators . contains ( symbol ) ) ; }
Evaluates whether symbol is operand .
2,705
boolean precedes ( final String s1 , final String s2 ) { String symbol1 = s1 . toLowerCase ( Locale . ENGLISH ) ; String symbol2 = s2 . toLowerCase ( Locale . ENGLISH ) ; if ( ! precedenceMap . keySet ( ) . contains ( symbol1 ) ) { return false ; } if ( ! precedenceMap . keySet ( ) . contains ( symbol2 ) ) { return false ; } int index1 = ( ( Integer ) precedenceMap . get ( symbol1 ) ) . intValue ( ) ; int index2 = ( ( Integer ) precedenceMap . get ( symbol2 ) ) . intValue ( ) ; boolean precedesResult = ( index1 < index2 ) ; return precedesResult ; }
Determines whether one symbol precedes another .
2,706
String infixToPostFix ( final CustomTokenizer tokenizer ) { final String space = " " ; StringBuffer postfix = new StringBuffer ( ) ; Stack stack = new Stack ( ) ; while ( tokenizer . hasMoreTokens ( ) ) { String token = tokenizer . nextToken ( ) ; boolean inText = ( token . startsWith ( "'" ) && ( ! token . endsWith ( "'" ) ) ) || ( token . startsWith ( "\"" ) && ( ! token . endsWith ( "\"" ) ) ) ; String quoteChar = token . substring ( 0 , 1 ) ; if ( inText ) { while ( inText && tokenizer . hasMoreTokens ( ) ) { token = token + " " + tokenizer . nextToken ( ) ; inText = ! ( token . endsWith ( quoteChar ) ) ; } } if ( "(" . equals ( token ) ) { postfix . append ( infixToPostFix ( tokenizer ) ) ; postfix . append ( space ) ; } else if ( ")" . equals ( token ) ) { while ( stack . size ( ) > 0 ) { postfix . append ( stack . pop ( ) . toString ( ) ) ; postfix . append ( space ) ; } return postfix . toString ( ) ; } else if ( isOperand ( token ) ) { postfix . append ( token ) ; postfix . append ( space ) ; } else { if ( stack . size ( ) > 0 ) { String peek = stack . peek ( ) . toString ( ) ; if ( precedes ( peek , token ) ) { stack . push ( token ) ; } else { boolean bypass = false ; do { if ( ( stack . size ( ) > 0 ) && ! precedes ( stack . peek ( ) . toString ( ) , token ) ) { postfix . append ( stack . pop ( ) . toString ( ) ) ; postfix . append ( space ) ; } else { bypass = true ; } } while ( ! bypass ) ; stack . push ( token ) ; } } else { stack . push ( token ) ; } } } while ( stack . size ( ) > 0 ) { postfix . append ( stack . pop ( ) . toString ( ) ) ; postfix . append ( space ) ; } return postfix . toString ( ) ; }
convert in - fix expression to post - fix .
2,707
public void addFilter ( final Filter newFilter ) { if ( headFilter == null ) { headFilter = newFilter ; tailFilter = newFilter ; } else { tailFilter . next = newFilter ; tailFilter = newFilter ; } }
Add a filter to end of the filter list .
2,708
private static int extractConverter ( char lastChar , final String pattern , int i , final StringBuffer convBuf , final StringBuffer currentLiteral ) { convBuf . setLength ( 0 ) ; if ( ! Character . isUnicodeIdentifierStart ( lastChar ) ) { return i ; } convBuf . append ( lastChar ) ; while ( ( i < pattern . length ( ) ) && Character . isUnicodeIdentifierPart ( pattern . charAt ( i ) ) ) { convBuf . append ( pattern . charAt ( i ) ) ; currentLiteral . append ( pattern . charAt ( i ) ) ; i ++ ; } return i ; }
Extract the converter identifier found at position i .
2,709
private static int extractOptions ( String pattern , int i , List options ) { while ( ( i < pattern . length ( ) ) && ( pattern . charAt ( i ) == '{' ) ) { int end = pattern . indexOf ( '}' , i ) ; if ( end == - 1 ) { break ; } String r = pattern . substring ( i + 1 , end ) ; options . add ( r ) ; i = end + 1 ; } return i ; }
Extract options .
2,710
private static PatternConverter createConverter ( final String converterId , final StringBuffer currentLiteral , final Map converterRegistry , final Map rules , final List options ) { String converterName = converterId ; Object converterObj = null ; for ( int i = converterId . length ( ) ; ( i > 0 ) && ( converterObj == null ) ; i -- ) { converterName = converterName . substring ( 0 , i ) ; if ( converterRegistry != null ) { converterObj = converterRegistry . get ( converterName ) ; } if ( ( converterObj == null ) && ( rules != null ) ) { converterObj = rules . get ( converterName ) ; } } if ( converterObj == null ) { LogLog . error ( "Unrecognized format specifier [" + converterId + "]" ) ; return null ; } Class converterClass ; if ( converterObj instanceof Class ) { converterClass = ( Class ) converterObj ; } else { if ( converterObj instanceof String ) { try { converterClass = Loader . loadClass ( ( String ) converterObj ) ; } catch ( ClassNotFoundException ex ) { LogLog . warn ( "Class for conversion pattern %" + converterName + " not found" , ex ) ; return null ; } } else { LogLog . warn ( "Bad map entry for conversion pattern %" + converterName + "." ) ; return null ; } } try { Method factory = converterClass . getMethod ( "newInstance" , new Class [ ] { Class . forName ( "[Ljava.lang.String;" ) } ) ; String [ ] optionsArray = new String [ options . size ( ) ] ; optionsArray = ( String [ ] ) options . toArray ( optionsArray ) ; Object newObj = factory . invoke ( null , new Object [ ] { optionsArray } ) ; if ( newObj instanceof PatternConverter ) { currentLiteral . delete ( 0 , currentLiteral . length ( ) - ( converterId . length ( ) - converterName . length ( ) ) ) ; return ( PatternConverter ) newObj ; } else { LogLog . warn ( "Class " + converterClass . getName ( ) + " does not extend PatternConverter." ) ; } } catch ( Exception ex ) { LogLog . error ( "Error creating converter for " + converterId , ex ) ; try { PatternConverter pc = ( PatternConverter ) converterClass . newInstance ( ) ; currentLiteral . delete ( 0 , currentLiteral . length ( ) - ( converterId . length ( ) - converterName . length ( ) ) ) ; return pc ; } catch ( Exception ex2 ) { LogLog . error ( "Error creating converter for " + converterId , ex2 ) ; } } return null ; }
Creates a new PatternConverter .
2,711
private static int finalizeConverter ( char c , String pattern , int i , final StringBuffer currentLiteral , final ExtrasFormattingInfo formattingInfo , final Map converterRegistry , final Map rules , final List patternConverters , final List formattingInfos ) { StringBuffer convBuf = new StringBuffer ( ) ; i = extractConverter ( c , pattern , i , convBuf , currentLiteral ) ; String converterId = convBuf . toString ( ) ; List options = new ArrayList ( ) ; i = extractOptions ( pattern , i , options ) ; PatternConverter pc = createConverter ( converterId , currentLiteral , converterRegistry , rules , options ) ; if ( pc == null ) { StringBuffer msg ; if ( converterId . length ( ) == 0 ) { msg = new StringBuffer ( "Empty conversion specifier starting at position " ) ; } else { msg = new StringBuffer ( "Unrecognized conversion specifier [" ) ; msg . append ( converterId ) ; msg . append ( "] starting at position " ) ; } msg . append ( Integer . toString ( i ) ) ; msg . append ( " in conversion pattern." ) ; LogLog . error ( msg . toString ( ) ) ; patternConverters . add ( new LiteralPatternConverter ( currentLiteral . toString ( ) ) ) ; formattingInfos . add ( ExtrasFormattingInfo . getDefault ( ) ) ; } else { patternConverters . add ( pc ) ; formattingInfos . add ( formattingInfo ) ; if ( currentLiteral . length ( ) > 0 ) { patternConverters . add ( new LiteralPatternConverter ( currentLiteral . toString ( ) ) ) ; formattingInfos . add ( ExtrasFormattingInfo . getDefault ( ) ) ; } } currentLiteral . setLength ( 0 ) ; return i ; }
Processes a format specifier sequence .
2,712
public StructuredDataId makeId ( final StructuredDataId id ) { if ( id == null ) { return this ; } return makeId ( id . getName ( ) , id . getEnterpriseNumber ( ) ) ; }
Creates an id using another id to supply default values .
2,713
public StructuredDataId makeId ( final String defaultId , final int anEnterpriseNumber ) { String id ; String [ ] req ; String [ ] opt ; if ( anEnterpriseNumber <= 0 ) { return this ; } if ( this . name != null ) { id = this . name ; req = this . required ; opt = this . optional ; } else { id = defaultId ; req = null ; opt = null ; } return new StructuredDataId ( id , anEnterpriseNumber , req , opt ) ; }
Creates an id based on the current id .
2,714
public String [ ] getFormats ( ) { final String [ ] formats = new String [ Format . values ( ) . length ] ; int i = 0 ; for ( final Format format : Format . values ( ) ) { formats [ i ++ ] = format . name ( ) ; } return formats ; }
Returns the supported formats .
2,715
public String getFormattedMessage ( ) { if ( formattedMessage != null ) { return formattedMessage ; } final StringBuilder sb = new StringBuilder ( 255 ) ; formatTo ( sb ) ; return sb . toString ( ) ; }
Returns the ThreadDump in printable format .
2,716
public Object [ ] swapParameters ( final Object [ ] emptyReplacement ) { Object [ ] result ; if ( varargs == null ) { result = params ; if ( emptyReplacement . length >= MAX_PARMS ) { params = emptyReplacement ; } else { if ( argCount <= emptyReplacement . length ) { System . arraycopy ( params , 0 , emptyReplacement , 0 , argCount ) ; result = emptyReplacement ; } else { params = new Object [ MAX_PARMS ] ; } } } else { if ( argCount <= emptyReplacement . length ) { result = emptyReplacement ; } else { result = new Object [ argCount ] ; } System . arraycopy ( varargs , 0 , result , 0 , argCount ) ; } return result ; }
see interface javadoc
2,717
void rollOver ( ) throws IOException { if ( getCompressBackups ( ) . equalsIgnoreCase ( "YES" ) || getCompressBackups ( ) . equalsIgnoreCase ( "TRUE" ) ) { File file = new File ( fileName ) ; Thread fileCompressor = new Thread ( new CompressFile ( file ) ) ; fileCompressor . start ( ) ; } if ( datePattern == null ) { errorHandler . error ( "Missing DatePattern option in rollOver()." ) ; return ; } String datedFilename = baseFileName + sdf . format ( now ) ; if ( scheduledFilename . equals ( datedFilename ) ) { return ; } activateOptions ( ) ; }
Rollover the current file to a new file .
2,718
protected void subAppend ( LoggingEvent event ) { long n = event . timeStamp ; if ( n >= nextCheck ) { try { now . setTime ( n ) ; cleanupAndRollOver ( ) ; } catch ( IOException ioe ) { if ( ioe instanceof InterruptedIOException ) { Thread . currentThread ( ) . interrupt ( ) ; } LogLog . error ( "rollOver() failed." , ioe ) ; } } super . subAppend ( event ) ; }
This method differentiates DailyRollingFileAppender from its super class .
2,719
public void printThreadInfo ( final StringBuilder sb ) { StringBuilders . appendDqValue ( sb , name ) . append ( Chars . SPACE ) ; if ( isDaemon ) { sb . append ( "daemon " ) ; } sb . append ( "prio=" ) . append ( priority ) . append ( " tid=" ) . append ( id ) . append ( ' ' ) ; if ( threadGroupName != null ) { StringBuilders . appendKeyDqValue ( sb , "group" , threadGroupName ) ; } sb . append ( '\n' ) ; sb . append ( "\tThread state: " ) . append ( state . name ( ) ) . append ( '\n' ) ; }
Print the thread information .
2,720
public void printStack ( final StringBuilder sb , final StackTraceElement [ ] trace ) { for ( final StackTraceElement element : trace ) { sb . append ( "\tat " ) . append ( element ) . append ( '\n' ) ; } }
Format the StackTraceElements .
2,721
void getProperties ( Connection connection , long id , LoggingEvent event ) throws SQLException { PreparedStatement statement = connection . prepareStatement ( sqlProperties ) ; try { statement . setLong ( 1 , id ) ; ResultSet rs = statement . executeQuery ( ) ; while ( rs . next ( ) ) { String key = rs . getString ( 1 ) ; String value = rs . getString ( 2 ) ; event . setProperty ( key , value ) ; } } finally { statement . close ( ) ; } }
Retrieve the event properties from the logging_event_property table .
2,722
ThrowableInformation getException ( Connection connection , long id ) throws SQLException { PreparedStatement statement = null ; try { statement = connection . prepareStatement ( sqlException ) ; statement . setLong ( 1 , id ) ; ResultSet rs = statement . executeQuery ( ) ; Vector v = new Vector ( ) ; while ( rs . next ( ) ) { v . add ( rs . getString ( 1 ) ) ; } int len = v . size ( ) ; String [ ] strRep = new String [ len ] ; for ( int i = 0 ; i < len ; i ++ ) { strRep [ i ] = ( String ) v . get ( i ) ; } return new ThrowableInformation ( strRep ) ; } finally { if ( statement != null ) { statement . close ( ) ; } } }
Retrieve the exception string representation from the logging_event_exception table .
2,723
public static Priority [ ] getAllPossiblePriorities ( ) { return new Priority [ ] { Priority . FATAL , Priority . ERROR , Level . WARN , Priority . INFO , Priority . DEBUG , Level . TRACE } ; }
Return all possible priorities as an array of Level objects in descending order .
2,724
public static void shutdown ( final LoggerContext context ) { if ( context != null && context instanceof Terminable ) { ( ( Terminable ) context ) . terminate ( ) ; } }
Shutdown the logging system if the logging system supports it .
2,725
public static Logger getLogger ( final Class < ? > clazz ) { final Class < ? > cls = callerClass ( clazz ) ; return getContext ( cls . getClassLoader ( ) , false ) . getLogger ( cls . getCanonicalName ( ) ) ; }
Returns a Logger using the fully qualified name of the Class as the Logger name .
2,726
public static Logger getLogger ( final Object value ) { return getLogger ( value != null ? value . getClass ( ) : StackLocatorUtil . getCallerClass ( 2 ) ) ; }
Returns a Logger using the fully qualified class name of the value as the Logger name .
2,727
public void setProperty ( String name , String value ) { if ( value == null ) return ; name = Introspector . decapitalize ( name ) ; PropertyDescriptor prop = getPropertyDescriptor ( name ) ; if ( prop == null ) { LogLog . warn ( "No such property [" + name + "] in " + obj . getClass ( ) . getName ( ) + "." ) ; } else { try { setProperty ( prop , name , value ) ; } catch ( PropertySetterException ex ) { LogLog . warn ( "Failed to set property [" + name + "] to value \"" + value + "\". " , ex . rootCause ) ; } } }
Set a property on this PaxPropertySetter s Object . If successful this method will invoke a setter method on the underlying Object . The setter is the one for the specified property name and the value is determined partly from the setter argument type and partly from the value specified in the call to this method .
2,728
static Properties loadClose ( final InputStream in , final Object source ) { final Properties props = new Properties ( ) ; if ( null != in ) { try { props . load ( in ) ; } catch ( final IOException e ) { LowLevelLogUtil . logException ( "Unable to read " + source , e ) ; } finally { try { in . close ( ) ; } catch ( final IOException e ) { LowLevelLogUtil . logException ( "Unable to close " + source , e ) ; } } } return props ; }
Loads and closes the given property input stream . If an error occurs log to the status logger .
2,729
public Charset getCharsetProperty ( final String name , final Charset defaultValue ) { final String prop = getStringProperty ( name ) ; try { return prop == null ? defaultValue : Charset . forName ( prop ) ; } catch ( UnsupportedCharsetException e ) { LowLevelLogUtil . logException ( "Unable to get Charset '" + name + "', using default " + defaultValue , e ) ; return defaultValue ; } }
Gets the named property as a Charset value .
2,730
public double getDoubleProperty ( final String name , final double defaultValue ) { final String prop = getStringProperty ( name ) ; if ( prop != null ) { try { return Double . parseDouble ( prop ) ; } catch ( final Exception ignored ) { return defaultValue ; } } return defaultValue ; }
Gets the named property as a double .
2,731
public int getIntegerProperty ( final String name , final int defaultValue ) { final String prop = getStringProperty ( name ) ; if ( prop != null ) { try { return Integer . parseInt ( prop ) ; } catch ( final Exception ignored ) { return defaultValue ; } } return defaultValue ; }
Gets the named property as an integer .
2,732
public long getLongProperty ( final String name , final long defaultValue ) { final String prop = getStringProperty ( name ) ; if ( prop != null ) { try { return Long . parseLong ( prop ) ; } catch ( final Exception ignored ) { return defaultValue ; } } return defaultValue ; }
Gets the named property as a long .
2,733
public String getStringProperty ( final String name ) { String prop = null ; try { prop = System . getProperty ( name ) ; } catch ( final SecurityException ignored ) { } return prop == null ? props . getProperty ( name ) : prop ; }
Gets the named property as a String .
2,734
public static Properties getSystemProperties ( ) { try { return new Properties ( System . getProperties ( ) ) ; } catch ( final SecurityException ex ) { LowLevelLogUtil . logException ( "Unable to access system properties." , ex ) ; return new Properties ( ) ; } }
Return the system properties or an empty Properties object if an error occurs .
2,735
public static Properties extractSubset ( final Properties properties , final String prefix ) { final Properties subset = new Properties ( ) ; if ( prefix == null || prefix . length ( ) == 0 ) { return subset ; } final String prefixToMatch = prefix . charAt ( prefix . length ( ) - 1 ) != '.' ? prefix + '.' : prefix ; final List < String > keys = new ArrayList < > ( ) ; for ( final String key : properties . stringPropertyNames ( ) ) { if ( key . startsWith ( prefixToMatch ) ) { subset . setProperty ( key . substring ( prefixToMatch . length ( ) ) , properties . getProperty ( key ) ) ; keys . add ( key ) ; } } for ( final String key : keys ) { properties . remove ( key ) ; } return subset ; }
Extracts properties that start with or are equals to the specific prefix and returns them in a new Properties object with the prefix removed .
2,736
public static Map < String , Properties > partitionOnCommonPrefixes ( final Properties properties ) { final Map < String , Properties > parts = new ConcurrentHashMap < > ( ) ; for ( final String key : properties . stringPropertyNames ( ) ) { final String prefix = key . substring ( 0 , key . indexOf ( '.' ) ) ; if ( ! parts . containsKey ( prefix ) ) { parts . put ( prefix , new Properties ( ) ) ; } parts . get ( prefix ) . setProperty ( key . substring ( key . indexOf ( '.' ) + 1 ) , properties . getProperty ( key ) ) ; } return parts ; }
Partitions a properties map based on common key prefixes up to the first period .
2,737
public String applyFields ( final String replaceText , final LoggingEvent event ) { if ( replaceText == null ) { return null ; } InFixToPostFix . CustomTokenizer tokenizer = new InFixToPostFix . CustomTokenizer ( replaceText ) ; StringBuffer result = new StringBuffer ( ) ; boolean found = false ; while ( tokenizer . hasMoreTokens ( ) ) { String token = tokenizer . nextToken ( ) ; if ( isField ( token ) || token . toUpperCase ( Locale . US ) . startsWith ( PROP_FIELD ) ) { result . append ( getValue ( token , event ) . toString ( ) ) ; found = true ; } else { result . append ( token ) ; } } if ( found ) { return result . toString ( ) ; } return null ; }
Apply fields .
2,738
public boolean isField ( final String fieldName ) { if ( fieldName != null ) { return ( KEYWORD_LIST . contains ( fieldName . toUpperCase ( Locale . US ) ) || fieldName . toUpperCase ( ) . startsWith ( PROP_FIELD ) ) ; } return false ; }
Determines if specified string is a recognized field .
2,739
public Object getValue ( final String fieldName , final LoggingEvent event ) { String upperField = fieldName . toUpperCase ( Locale . US ) ; if ( LOGGER_FIELD . equals ( upperField ) ) { return event . getLoggerName ( ) ; } else if ( LEVEL_FIELD . equals ( upperField ) ) { return event . getLevel ( ) ; } else if ( MSG_FIELD . equals ( upperField ) ) { return event . getMessage ( ) ; } else if ( NDC_FIELD . equals ( upperField ) ) { String ndcValue = event . getNDC ( ) ; return ( ( ndcValue == null ) ? EMPTY_STRING : ndcValue ) ; } else if ( EXCEPTION_FIELD . equals ( upperField ) ) { String [ ] throwableRep = event . getThrowableStrRep ( ) ; if ( throwableRep == null ) { return EMPTY_STRING ; } else { return getExceptionMessage ( throwableRep ) ; } } else if ( TIMESTAMP_FIELD . equals ( upperField ) ) { return new Long ( event . timeStamp ) ; } else if ( THREAD_FIELD . equals ( upperField ) ) { return event . getThreadName ( ) ; } else if ( upperField . startsWith ( PROP_FIELD ) ) { Object propValue = event . getMDC ( fieldName . substring ( 5 ) ) ; if ( propValue == null ) { String lowerPropKey = fieldName . substring ( 5 ) . toLowerCase ( ) ; Set entrySet = event . getProperties ( ) . entrySet ( ) ; for ( Iterator iter = entrySet . iterator ( ) ; iter . hasNext ( ) ; ) { Map . Entry thisEntry = ( Map . Entry ) iter . next ( ) ; if ( thisEntry . getKey ( ) . toString ( ) . equalsIgnoreCase ( lowerPropKey ) ) { propValue = thisEntry . getValue ( ) ; } } } return ( ( propValue == null ) ? EMPTY_STRING : propValue . toString ( ) ) ; } else { LocationInfo info = event . getLocationInformation ( ) ; if ( CLASS_FIELD . equals ( upperField ) ) { return ( ( info == null ) ? EMPTY_STRING : info . getClassName ( ) ) ; } else if ( FILE_FIELD . equals ( upperField ) ) { return ( ( info == null ) ? EMPTY_STRING : info . getFileName ( ) ) ; } else if ( LINE_FIELD . equals ( upperField ) ) { return ( ( info == null ) ? EMPTY_STRING : info . getLineNumber ( ) ) ; } else if ( METHOD_FIELD . equals ( upperField ) ) { return ( ( info == null ) ? EMPTY_STRING : info . getMethodName ( ) ) ; } } throw new IllegalArgumentException ( "Unsupported field name: " + fieldName ) ; }
Get value of field .
2,740
private static String getExceptionMessage ( final String [ ] exception ) { StringBuffer buff = new StringBuffer ( ) ; for ( int i = 0 ; i < exception . length ; i ++ ) { buff . append ( exception [ i ] ) ; } return buff . toString ( ) ; }
Get message from throwable representation .
2,741
public void trace ( String format , Object arg ) { if ( m_delegate . isTraceEnabled ( ) ) { FormattingTuple tuple = MessageFormatter . format ( format , arg ) ; m_delegate . trace ( tuple . getMessage ( ) , tuple . getThrowable ( ) ) ; } }
Log a message at the TRACE level according to the specified format and argument .
2,742
public void trace ( Marker marker , String msg ) { if ( m_delegate . isTraceEnabled ( ) ) { setMDCMarker ( marker ) ; m_delegate . trace ( msg , null ) ; resetMDCMarker ( ) ; } }
Log a message with the specific Marker at the TRACE level .
2,743
public void debug ( String format , Object arg ) { if ( m_delegate . isDebugEnabled ( ) ) { FormattingTuple tuple = MessageFormatter . format ( format , arg ) ; m_delegate . debug ( tuple . getMessage ( ) , tuple . getThrowable ( ) ) ; } }
Log a message at the DEBUG level according to the specified format and argument .
2,744
public void debug ( Marker marker , String msg ) { if ( m_delegate . isDebugEnabled ( ) ) { setMDCMarker ( marker ) ; m_delegate . debug ( msg , null ) ; resetMDCMarker ( ) ; } }
Log a message with the specific Marker at the DEBUG level .
2,745
public void info ( String format , Object arg1 , Object arg2 ) { if ( m_delegate . isInfoEnabled ( ) ) { FormattingTuple tuple = MessageFormatter . format ( format , arg1 , arg2 ) ; m_delegate . inform ( tuple . getMessage ( ) , tuple . getThrowable ( ) ) ; } }
Log a message at the INFO level according to the specified format and arguments .
2,746
public void info ( Marker marker , String msg ) { if ( m_delegate . isInfoEnabled ( ) ) { setMDCMarker ( marker ) ; m_delegate . inform ( msg , null ) ; resetMDCMarker ( ) ; } }
Log a message with the specific Marker at the INFO level .
2,747
public void warn ( Marker marker , String msg ) { if ( m_delegate . isWarnEnabled ( ) ) { setMDCMarker ( marker ) ; m_delegate . warn ( msg , null ) ; resetMDCMarker ( ) ; } }
Log a message with the specific Marker at the WARN level .
2,748
public void error ( String format , Object arg ) { if ( m_delegate . isErrorEnabled ( ) ) { FormattingTuple tuple = MessageFormatter . format ( format , arg ) ; m_delegate . error ( tuple . getMessage ( ) , tuple . getThrowable ( ) ) ; } }
Log a message at the ERROR level according to the specified format and argument .
2,749
public void error ( Marker marker , String msg ) { if ( m_delegate . isErrorEnabled ( ) ) { setMDCMarker ( marker ) ; m_delegate . error ( msg , null ) ; resetMDCMarker ( ) ; } }
Log a message with the specific Marker at the ERROR level .
2,750
public void log ( Marker marker , String fqcn , int level , String message , Object [ ] argArray , Throwable t ) { setMDCMarker ( marker ) ; switch ( level ) { case ( TRACE_INT ) : if ( m_delegate . isTraceEnabled ( ) ) { FormattingTuple tuple = MessageFormatter . arrayFormat ( message , argArray ) ; m_delegate . trace ( tuple . getMessage ( ) , t , fqcn ) ; } break ; case ( DEBUG_INT ) : if ( m_delegate . isDebugEnabled ( ) ) { FormattingTuple tuple = MessageFormatter . arrayFormat ( message , argArray ) ; m_delegate . debug ( tuple . getMessage ( ) , t , fqcn ) ; } break ; case ( INFO_INT ) : if ( m_delegate . isInfoEnabled ( ) ) { FormattingTuple tuple = MessageFormatter . arrayFormat ( message , argArray ) ; m_delegate . inform ( tuple . getMessage ( ) , t , fqcn ) ; } break ; case ( WARN_INT ) : if ( m_delegate . isWarnEnabled ( ) ) { FormattingTuple tuple = MessageFormatter . arrayFormat ( message , argArray ) ; m_delegate . warn ( tuple . getMessage ( ) , t , fqcn ) ; } break ; case ( ERROR_INT ) : if ( m_delegate . isErrorEnabled ( ) ) { FormattingTuple tuple = MessageFormatter . arrayFormat ( message , argArray ) ; m_delegate . error ( tuple . getMessage ( ) , t , fqcn ) ; } break ; default : break ; } resetMDCMarker ( ) ; }
This method implements LocationAwareLogger . log
2,751
public static Rule getRule ( final Stack stack ) { if ( stack . size ( ) < 1 ) { throw new IllegalArgumentException ( "Invalid NOT rule - expected one rule but received " + stack . size ( ) ) ; } Object o1 = stack . pop ( ) ; if ( o1 instanceof Rule ) { Rule p1 = ( Rule ) o1 ; return new NotRule ( p1 ) ; } throw new IllegalArgumentException ( "Invalid NOT rule: - expected rule but received " + o1 ) ; }
Create new instance from top element of stack .
2,752
public void fatal ( final Object message ) { if ( m_delegate . isFatalEnabled ( ) && message != null ) { m_delegate . fatal ( message . toString ( ) , null ) ; } }
Log a message object with the FATAL Level .
2,753
public String getFormattedMessage ( ) { if ( formattedMessage != null ) { return formattedMessage ; } ResourceBundle bundle = this . resourceBundle ; if ( bundle == null ) { if ( baseName != null ) { bundle = getResourceBundle ( baseName , locale , false ) ; } else { bundle = getResourceBundle ( loggerName , locale , true ) ; } } final String myKey = getFormat ( ) ; final String msgPattern = ( bundle == null || ! bundle . containsKey ( myKey ) ) ? myKey : bundle . getString ( myKey ) ; final Object [ ] array = argArray == null ? stringArgs : argArray ; final FormattedMessage msg = new FormattedMessage ( msgPattern , array ) ; formattedMessage = msg . getFormattedMessage ( ) ; throwable = msg . getThrowable ( ) ; return formattedMessage ; }
Returns the formatted message after looking up the format in the resource bundle .
2,754
protected ResourceBundle getResourceBundle ( final String rbBaseName , final Locale resourceBundleLocale , final boolean loop ) { ResourceBundle rb = null ; if ( rbBaseName == null ) { return null ; } try { if ( resourceBundleLocale != null ) { rb = ResourceBundle . getBundle ( rbBaseName , resourceBundleLocale ) ; } else { rb = ResourceBundle . getBundle ( rbBaseName ) ; } } catch ( final MissingResourceException ex ) { if ( ! loop ) { logger . debug ( "Unable to locate ResourceBundle " + rbBaseName ) ; return null ; } } String substr = rbBaseName ; int i ; while ( rb == null && ( i = substr . lastIndexOf ( '.' ) ) > 0 ) { substr = substr . substring ( 0 , i ) ; try { if ( resourceBundleLocale != null ) { rb = ResourceBundle . getBundle ( substr , resourceBundleLocale ) ; } else { rb = ResourceBundle . getBundle ( substr ) ; } } catch ( final MissingResourceException ex ) { logger . debug ( "Unable to locate ResourceBundle " + substr ) ; } } return rb ; }
Override this to use a ResourceBundle . Control in Java 6
2,755
public static Marker getMarker ( final String name ) { Marker result = MARKERS . get ( name ) ; if ( result == null ) { MARKERS . putIfAbsent ( name , new Log4jMarker ( name ) ) ; result = MARKERS . get ( name ) ; } return result ; }
Retrieves a Marker or create a Marker that has no parent .
2,756
public static Marker getMarker ( final String name , final String parent ) { final Marker parentMarker = MARKERS . get ( parent ) ; if ( parentMarker == null ) { throw new IllegalArgumentException ( "Parent Marker " + parent + " has not been defined" ) ; } return getMarker ( name , parentMarker ) ; }
Retrieves or creates a Marker with the specified parent . The parent must have been previously created .
2,757
public static Marker getMarker ( final String name , final Marker parent ) { return getMarker ( name ) . addParents ( parent ) ; }
Retrieves or creates a Marker with the specified parent .
2,758
public Class < ? > getCallerClass ( final int depth ) { if ( depth < 0 ) { throw new IndexOutOfBoundsException ( Integer . toString ( depth ) ) ; } try { return ( Class < ? > ) GET_CALLER_CLASS . invoke ( null , depth + 1 + JDK_7u25_OFFSET ) ; } catch ( final Exception e ) { return null ; } }
migrated from ReflectiveCallerClassUtility
2,759
public Class < ? > getCallerClass ( final Class < ? > anchor ) { boolean next = false ; Class < ? > clazz ; for ( int i = 2 ; null != ( clazz = getCallerClass ( i ) ) ; i ++ ) { if ( anchor . equals ( clazz ) ) { next = true ; continue ; } if ( next ) { return clazz ; } } return Object . class ; }
added for use in LoggerAdapter implementations mainly
2,760
public Stack < Class < ? > > getCurrentStackTrace ( ) { if ( getSecurityManager ( ) != null ) { final Class < ? > [ ] array = getSecurityManager ( ) . getClassContext ( ) ; final Stack < Class < ? > > classes = new Stack < > ( ) ; classes . ensureCapacity ( array . length ) ; for ( final Class < ? > clazz : array ) { classes . push ( clazz ) ; } return classes ; } final Stack < Class < ? > > classes = new Stack < > ( ) ; Class < ? > clazz ; for ( int i = 1 ; null != ( clazz = getCallerClass ( i ) ) ; i ++ ) { classes . push ( clazz ) ; } return classes ; }
migrated from ThrowableProxy
2,761
public String getFormattedMessage ( ) { if ( formattedMessage == null ) { if ( message == null ) { message = getMessage ( messagePattern , argArray , throwable ) ; } formattedMessage = message . getFormattedMessage ( ) ; } return formattedMessage ; }
Gets the formatted message .
2,762
public void shutdown ( ) { try { if ( reader != null ) { reader . close ( ) ; reader = null ; } } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; } }
Close the receiver release any resources that are accessing the file .
2,763
public void activateOptions ( ) { Runnable runnable = new Runnable ( ) { public void run ( ) { try { URL url = new URL ( fileURL ) ; host = url . getHost ( ) ; if ( host != null && host . equals ( "" ) ) { host = FILE_KEY ; } path = url . getPath ( ) ; } catch ( MalformedURLException e1 ) { e1 . printStackTrace ( ) ; } try { if ( filterExpression != null ) { expressionRule = ExpressionRule . getRule ( filterExpression ) ; } } catch ( Exception e ) { getLogger ( ) . warn ( "Invalid filter expression: " + filterExpression , e ) ; } Class c ; try { c = Class . forName ( decoder ) ; Object o = c . newInstance ( ) ; if ( o instanceof Decoder ) { decoderInstance = ( Decoder ) o ; } } catch ( ClassNotFoundException e ) { e . printStackTrace ( ) ; } catch ( InstantiationException e ) { e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } try { reader = new InputStreamReader ( new URL ( getFileURL ( ) ) . openStream ( ) ) ; process ( reader ) ; } catch ( FileNotFoundException fnfe ) { getLogger ( ) . info ( "file not available" ) ; } catch ( IOException ioe ) { getLogger ( ) . warn ( "unable to load file" , ioe ) ; return ; } } } ; if ( useCurrentThread ) { runnable . run ( ) ; } else { Thread thread = new Thread ( runnable , "LogFileXMLReceiver-" + getName ( ) ) ; thread . start ( ) ; } }
Process the file
2,764
public void setName ( final String repoName ) { if ( name == null ) { name = repoName ; } else if ( ! name . equals ( repoName ) ) { throw new IllegalStateException ( "Repository [" + name + "] cannot be renamed as [" + repoName + "]." ) ; } }
Set the name of this repository .
2,765
public Scheduler getScheduler ( ) { if ( scheduler == null ) { scheduler = new Scheduler ( ) ; scheduler . setDaemon ( true ) ; scheduler . start ( ) ; } return scheduler ; }
Return this repository s own scheduler . The scheduler is lazily instantiated .
2,766
private void parameterizedLog ( final String level , final Object parameterizedMsg , final Object param1 , final Object param2 ) { if ( parameterizedMsg instanceof String ) { String msgStr = ( String ) parameterizedMsg ; msgStr = MessageFormatter . format ( msgStr , param1 , param2 ) ; log ( level , msgStr , null ) ; } else { log ( level , parameterizedMsg . toString ( ) , null ) ; } }
For parameterized messages first substitute parameters and then log .
2,767
boolean archiveFile ( File logFile ) { FileOutputStream fOut ; ZipOutputStream zOut ; try { fOut = new FileOutputStream ( logFile . getPath ( ) + ".zip" ) ; zOut = new ZipOutputStream ( fOut ) ; FileInputStream fIn = new FileInputStream ( logFile ) ; BufferedInputStream bIn = new BufferedInputStream ( fIn ) ; ZipEntry entry = new ZipEntry ( logFile . getCanonicalFile ( ) . getName ( ) ) ; zOut . putNextEntry ( entry ) ; byte [ ] barray = new byte [ 1024 ] ; int bytes ; while ( ( bytes = bIn . read ( barray , 0 , 1024 ) ) > - 1 ) { zOut . write ( barray , 0 , bytes ) ; } zOut . flush ( ) ; zOut . close ( ) ; fOut . close ( ) ; return true ; } catch ( IOException ioE ) { return false ; } }
archive log file
2,768
public ClassLoader getClassLoader ( ) { return classloader != null ? classloader : ( classloader = Loader . getClassLoader ( ResolverUtil . class , null ) ) ; }
Returns the classloader that will be used for scanning for classes . If no explicit ClassLoader has been set by the calling the context class loader will be used .
2,769
protected void addIfMatching ( final Test test , final String fqn ) { try { final ClassLoader loader = getClassLoader ( ) ; if ( test . doesMatchClass ( ) ) { final String externalName = fqn . substring ( 0 , fqn . indexOf ( '.' ) ) . replace ( '/' , '.' ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Checking to see if class " + externalName + " matches criteria [" + test + ']' ) ; } final Class < ? > type = loader . loadClass ( externalName ) ; if ( test . matches ( type ) ) { classMatches . add ( type ) ; } } if ( test . doesMatchResource ( ) ) { URL url = loader . getResource ( fqn ) ; if ( url == null ) { url = loader . getResource ( fqn . substring ( 1 ) ) ; } if ( url != null && test . matches ( url . toURI ( ) ) ) { resourceMatches . add ( url . toURI ( ) ) ; } } } catch ( final Throwable t ) { LOGGER . warn ( "Could not examine class '" + fqn , t ) ; } }
Add the class designated by the fully qualified class name provided to the set of resolved classes if and only if it is approved by the Test supplied .
2,770
public void activateOptions ( ) { if ( follow ) { if ( target . equals ( SYSTEM_ERR ) ) { setWriter ( createWriter ( new SystemErrStream ( ) ) ) ; } else { setWriter ( createWriter ( new SystemOutStream ( ) ) ) ; } } else { if ( target . equals ( SYSTEM_ERR ) ) { setWriter ( createWriter ( unwrap ( System . err ) ) ) ; } else { setWriter ( createWriter ( unwrap ( System . out ) ) ) ; } } super . activateOptions ( ) ; }
Prepares the appender for use .
2,771
protected static void loadProvider ( final URL url , final ClassLoader cl ) { try { final Properties props = PropertiesUtil . loadClose ( url . openStream ( ) , url ) ; if ( validVersion ( props . getProperty ( API_VERSION ) ) ) { final Provider provider = new Provider ( props , url , cl ) ; PROVIDERS . add ( provider ) ; LOGGER . debug ( "Loaded Provider {}" , provider ) ; } } catch ( final IOException e ) { LOGGER . error ( "Unable to open {}" , url , e ) ; } }
Loads an individual Provider implementation . This method is really only useful for the OSGi bundle activator and this class itself .
2,772
protected static void lazyInit ( ) { if ( instance == null ) { try { STARTUP_LOCK . lockInterruptibly ( ) ; try { if ( instance == null ) { instance = new ProviderUtil ( ) ; } } finally { STARTUP_LOCK . unlock ( ) ; } } catch ( final InterruptedException e ) { LOGGER . fatal ( "Interrupted before Log4j Providers could be loaded." , e ) ; Thread . currentThread ( ) . interrupt ( ) ; } } }
Lazily initializes the ProviderUtil singleton .
2,773
public static Object [ ] getAll ( final Supplier < ? > ... suppliers ) { if ( suppliers == null ) { return null ; } final Object [ ] result = new Object [ suppliers . length ] ; for ( int i = 0 ; i < result . length ; i ++ ) { result [ i ] = get ( suppliers [ i ] ) ; } return result ; }
Converts an array of lambda expressions into an array of their evaluation results .
2,774
public static Message getMessage ( final Supplier < ? > supplier , final MessageFactory messageFactory ) { if ( supplier == null ) { return null ; } final Object result = supplier . get ( ) ; return result instanceof Message ? ( Message ) result : messageFactory . newMessage ( result ) ; }
Returns a Message either the value supplied by the specified function or a new Message created by the specified Factory .
2,775
protected Appender findAppenderByName ( Document doc , String appenderName ) { Appender appender = ( Appender ) appenderBag . get ( appenderName ) ; if ( appender != null ) { return appender ; } else { Element element = null ; NodeList list = doc . getElementsByTagName ( "appender" ) ; for ( int t = 0 ; t < list . getLength ( ) ; t ++ ) { Node node = list . item ( t ) ; NamedNodeMap map = node . getAttributes ( ) ; Node attrNode = map . getNamedItem ( "name" ) ; if ( appenderName . equals ( attrNode . getNodeValue ( ) ) ) { element = ( Element ) node ; break ; } } if ( element == null ) { LogLog . error ( "No appender named [" + appenderName + "] could be found." ) ; return null ; } else { appender = parseAppender ( element ) ; if ( appender != null ) { appenderBag . put ( appenderName , appender ) ; } return appender ; } } }
Used internally to parse appenders by IDREF name .
2,776
protected Appender findAppenderByReference ( Element appenderRef ) { String appenderName = subst ( appenderRef . getAttribute ( REF_ATTR ) ) ; Document doc = appenderRef . getOwnerDocument ( ) ; return findAppenderByName ( doc , appenderName ) ; }
Used internally to parse appenders by IDREF element .
2,777
private static void parseUnrecognizedElement ( final Object instance , final Element element , final Properties props ) throws Exception { boolean recognized = false ; if ( instance instanceof UnrecognizedElementHandler ) { recognized = ( ( UnrecognizedElementHandler ) instance ) . parseUnrecognizedElement ( element , props ) ; } if ( ! recognized ) { LogLog . warn ( "Unrecognized element " + element . getNodeName ( ) ) ; } }
Delegates unrecognized content to created instance if it supports UnrecognizedElementParser .
2,778
private static void quietParseUnrecognizedElement ( final Object instance , final Element element , final Properties props ) { try { parseUnrecognizedElement ( instance , element , props ) ; } catch ( Exception ex ) { LogLog . error ( "Error in extension content: " , ex ) ; } }
Delegates unrecognized content to created instance if it supports UnrecognizedElementParser and catches and logs any exception .
2,779
protected Appender parseAppender ( Element appenderElement ) { String className = subst ( appenderElement . getAttribute ( CLASS_ATTR ) ) ; LogLog . debug ( "Class name: [" + className + ']' ) ; try { Object instance = Loader . loadClass ( className ) . newInstance ( ) ; Appender appender = ( Appender ) instance ; PropertySetter propSetter = new PropertySetter ( appender ) ; appender . setName ( subst ( appenderElement . getAttribute ( NAME_ATTR ) ) ) ; NodeList children = appenderElement . getChildNodes ( ) ; final int length = children . getLength ( ) ; for ( int loop = 0 ; loop < length ; loop ++ ) { Node currentNode = children . item ( loop ) ; if ( currentNode . getNodeType ( ) == Node . ELEMENT_NODE ) { Element currentElement = ( Element ) currentNode ; if ( currentElement . getTagName ( ) . equals ( PARAM_TAG ) ) { setParameter ( currentElement , propSetter ) ; } else if ( currentElement . getTagName ( ) . equals ( LAYOUT_TAG ) ) { appender . setLayout ( parseLayout ( currentElement ) ) ; } else if ( currentElement . getTagName ( ) . equals ( FILTER_TAG ) ) { parseFilters ( currentElement , appender ) ; } else if ( currentElement . getTagName ( ) . equals ( ERROR_HANDLER_TAG ) ) { parseErrorHandler ( currentElement , appender ) ; } else if ( currentElement . getTagName ( ) . equals ( APPENDER_REF_TAG ) ) { String refName = subst ( currentElement . getAttribute ( REF_ATTR ) ) ; if ( appender instanceof AppenderAttachable ) { AppenderAttachable aa = ( AppenderAttachable ) appender ; LogLog . debug ( "Attaching appender named [" + refName + "] to appender named [" + appender . getName ( ) + "]." ) ; aa . addAppender ( findAppenderByReference ( currentElement ) ) ; } else { LogLog . error ( "Requesting attachment of appender named [" + refName + "] to appender named [" + appender . getName ( ) + "] which does not implement org.apache.log4j.spi.AppenderAttachable." ) ; } } else { parseUnrecognizedElement ( instance , currentElement , props ) ; } } } propSetter . activate ( ) ; return appender ; } catch ( Exception oops ) { LogLog . error ( "Could not create an Appender. Reported error follows." , oops ) ; return null ; } }
Used internally to parse an appender element .
2,780
protected void parseFilters ( Element element , Appender appender ) { String clazz = subst ( element . getAttribute ( CLASS_ATTR ) ) ; Filter filter = ( Filter ) OptionConverter . instantiateByClassName ( clazz , Filter . class , null ) ; if ( filter != null ) { PropertySetter propSetter = new PropertySetter ( filter ) ; NodeList children = element . getChildNodes ( ) ; final int length = children . getLength ( ) ; for ( int loop = 0 ; loop < length ; loop ++ ) { Node currentNode = children . item ( loop ) ; if ( currentNode . getNodeType ( ) == Node . ELEMENT_NODE ) { Element currentElement = ( Element ) currentNode ; String tagName = currentElement . getTagName ( ) ; if ( tagName . equals ( PARAM_TAG ) ) { setParameter ( currentElement , propSetter ) ; } else { quietParseUnrecognizedElement ( filter , currentElement , props ) ; } } } propSetter . activate ( ) ; LogLog . debug ( "Adding filter of type [" + filter . getClass ( ) + "] to appender named [" + appender . getName ( ) + "]." ) ; appender . addFilter ( filter ) ; } }
Used internally to parse a filter element .
2,781
protected void parseCategory ( Element loggerElement ) { String catName = subst ( loggerElement . getAttribute ( NAME_ATTR ) ) ; Logger cat ; String className = subst ( loggerElement . getAttribute ( CLASS_ATTR ) ) ; if ( EMPTY_STR . equals ( className ) ) { LogLog . debug ( "Retreiving an instance of org.apache.log4j.Logger." ) ; cat = ( catFactory == null ) ? repository . getLogger ( catName ) : repository . getLogger ( catName , catFactory ) ; } else { LogLog . debug ( "Desired logger sub-class: [" + className + ']' ) ; try { Class clazz = Loader . loadClass ( className ) ; Method getInstanceMethod = clazz . getMethod ( "getLogger" , ONE_STRING_PARAM ) ; cat = ( Logger ) getInstanceMethod . invoke ( null , new Object [ ] { catName } ) ; } catch ( Exception oops ) { LogLog . error ( "Could not retrieve category [" + catName + "]. Reported error follows." , oops ) ; return ; } } synchronized ( cat ) { boolean additivity = OptionConverter . toBoolean ( subst ( loggerElement . getAttribute ( ADDITIVITY_ATTR ) ) , true ) ; LogLog . debug ( "Setting [" + cat . getName ( ) + "] additivity to [" + additivity + "]." ) ; cat . setAdditivity ( additivity ) ; parseChildrenOfLoggerElement ( loggerElement , cat , false ) ; } }
Used internally to parse an category element .
2,782
protected void parseCategoryFactory ( Element factoryElement ) { String className = subst ( factoryElement . getAttribute ( CLASS_ATTR ) ) ; if ( EMPTY_STR . equals ( className ) ) { LogLog . error ( "Category Factory tag " + CLASS_ATTR + " attribute not found." ) ; LogLog . debug ( "No Category Factory configured." ) ; } else { LogLog . debug ( "Desired category factory: [" + className + ']' ) ; Object factory = OptionConverter . instantiateByClassName ( className , LoggerFactory . class , null ) ; if ( factory instanceof LoggerFactory ) { catFactory = ( LoggerFactory ) factory ; } else { LogLog . error ( "Category Factory class " + className + " does not implement org.apache.log4j.LoggerFactory" ) ; } PropertySetter propSetter = new PropertySetter ( factory ) ; Element currentElement = null ; Node currentNode = null ; NodeList children = factoryElement . getChildNodes ( ) ; final int length = children . getLength ( ) ; for ( int loop = 0 ; loop < length ; loop ++ ) { currentNode = children . item ( loop ) ; if ( currentNode . getNodeType ( ) == Node . ELEMENT_NODE ) { currentElement = ( Element ) currentNode ; if ( currentElement . getTagName ( ) . equals ( PARAM_TAG ) ) { setParameter ( currentElement , propSetter ) ; } else { quietParseUnrecognizedElement ( factory , currentElement , props ) ; } } } } }
Used internally to parse the category factory element .
2,783
protected void parseRoot ( Element rootElement ) { Logger root = repository . getRootLogger ( ) ; synchronized ( root ) { parseChildrenOfLoggerElement ( rootElement , root , true ) ; } }
Used internally to parse the roor category element .
2,784
protected void parseChildrenOfLoggerElement ( Element catElement , Logger cat , boolean isRoot ) { PropertySetter propSetter = new PropertySetter ( cat ) ; cat . removeAllAppenders ( ) ; NodeList children = catElement . getChildNodes ( ) ; final int length = children . getLength ( ) ; for ( int loop = 0 ; loop < length ; loop ++ ) { Node currentNode = children . item ( loop ) ; if ( currentNode . getNodeType ( ) == Node . ELEMENT_NODE ) { Element currentElement = ( Element ) currentNode ; String tagName = currentElement . getTagName ( ) ; if ( tagName . equals ( APPENDER_REF_TAG ) ) { Element appenderRef = ( Element ) currentNode ; Appender appender = findAppenderByReference ( appenderRef ) ; String refName = subst ( appenderRef . getAttribute ( REF_ATTR ) ) ; if ( appender != null ) LogLog . debug ( "Adding appender named [" + refName + "] to category [" + cat . getName ( ) + "]." ) ; else LogLog . debug ( "Appender named [" + refName + "] not found." ) ; cat . addAppender ( appender ) ; } else if ( tagName . equals ( LEVEL_TAG ) ) { parseLevel ( currentElement , cat , isRoot ) ; } else if ( tagName . equals ( PRIORITY_TAG ) ) { parseLevel ( currentElement , cat , isRoot ) ; } else if ( tagName . equals ( PARAM_TAG ) ) { setParameter ( currentElement , propSetter ) ; } else { quietParseUnrecognizedElement ( cat , currentElement , props ) ; } } } propSetter . activate ( ) ; }
Used internally to parse the children of a category element .
2,785
protected Layout parseLayout ( Element layout_element ) { String className = subst ( layout_element . getAttribute ( CLASS_ATTR ) ) ; LogLog . debug ( "Parsing layout of class: \"" + className + "\"" ) ; try { Object instance = Loader . loadClass ( className ) . newInstance ( ) ; Layout layout = ( Layout ) instance ; PropertySetter propSetter = new PropertySetter ( layout ) ; NodeList params = layout_element . getChildNodes ( ) ; final int length = params . getLength ( ) ; for ( int loop = 0 ; loop < length ; loop ++ ) { Node currentNode = ( Node ) params . item ( loop ) ; if ( currentNode . getNodeType ( ) == Node . ELEMENT_NODE ) { Element currentElement = ( Element ) currentNode ; String tagName = currentElement . getTagName ( ) ; if ( tagName . equals ( PARAM_TAG ) ) { setParameter ( currentElement , propSetter ) ; } else { parseUnrecognizedElement ( instance , currentElement , props ) ; } } } propSetter . activate ( ) ; return layout ; } catch ( Exception oops ) { LogLog . error ( "Could not create the Layout. Reported error follows." , oops ) ; return null ; } }
Used internally to parse a layout element .
2,786
protected void parseLevel ( Element element , Logger logger , boolean isRoot ) { String catName = logger . getName ( ) ; if ( isRoot ) { catName = "root" ; } String priStr = subst ( element . getAttribute ( VALUE_ATTR ) ) ; LogLog . debug ( "Level value for " + catName + " is [" + priStr + "]." ) ; if ( INHERITED . equalsIgnoreCase ( priStr ) || NULL . equalsIgnoreCase ( priStr ) ) { if ( isRoot ) { LogLog . error ( "Root level cannot be inherited. Ignoring directive." ) ; } else { logger . setLevel ( null ) ; } } else { String className = subst ( element . getAttribute ( CLASS_ATTR ) ) ; if ( EMPTY_STR . equals ( className ) ) { logger . setLevel ( OptionConverter . toLevel ( priStr , Level . DEBUG ) ) ; } else { LogLog . debug ( "Desired Level sub-class: [" + className + ']' ) ; try { Class clazz = Loader . loadClass ( className ) ; Method toLevelMethod = clazz . getMethod ( "toLevel" , ONE_STRING_PARAM ) ; Level pri = ( Level ) toLevelMethod . invoke ( null , new Object [ ] { priStr } ) ; logger . setLevel ( pri ) ; } catch ( Exception oops ) { LogLog . error ( "Could not create level [" + priStr + "]. Reported error follows." , oops ) ; return ; } } } LogLog . debug ( catName + " level set to " + logger . getLevel ( ) ) ; }
Used internally to parse a level element .
2,787
public void doConfigure ( final InputStream inputStream , LoggerRepository repository ) throws FactoryConfigurationError { ParseAction action = new ParseAction ( ) { public Document parse ( final DocumentBuilder parser ) throws SAXException , IOException { InputSource inputSource = new InputSource ( inputStream ) ; inputSource . setSystemId ( "dummy://log4j.dtd" ) ; return parser . parse ( inputSource ) ; } public String toString ( ) { return "input stream [" + inputStream . toString ( ) + "]" ; } } ; doConfigure ( action , repository ) ; }
Configure log4j by reading in a log4j . dtd compliant XML configuration file .
2,788
public static String subst ( final String value , final Properties props ) { try { return OptionConverter . substVars ( value , props ) ; } catch ( IllegalArgumentException e ) { LogLog . warn ( "Could not perform variable substitution." , e ) ; return value ; } }
Substitutes property value for any references in expression .
2,789
public static void setParameter ( final Element elem , final PropertySetter propSetter , final Properties props ) { String name = subst ( elem . getAttribute ( "name" ) , props ) ; String value = ( elem . getAttribute ( "value" ) ) ; value = subst ( OptionConverter . convertSpecialChars ( value ) , props ) ; propSetter . setProperty ( name , value ) ; }
Sets a parameter based from configuration file content .
2,790
public static OptionHandler parseElement ( final Element element , final Properties props , final Class expectedClass ) throws Exception { String clazz = subst ( element . getAttribute ( "class" ) , props ) ; Object instance = OptionConverter . instantiateByClassName ( clazz , expectedClass , null ) ; if ( instance instanceof OptionHandler ) { OptionHandler optionHandler = ( OptionHandler ) instance ; PropertySetter propSetter = new PropertySetter ( optionHandler ) ; NodeList children = element . getChildNodes ( ) ; final int length = children . getLength ( ) ; for ( int loop = 0 ; loop < length ; loop ++ ) { Node currentNode = children . item ( loop ) ; if ( currentNode . getNodeType ( ) == Node . ELEMENT_NODE ) { Element currentElement = ( Element ) currentNode ; String tagName = currentElement . getTagName ( ) ; if ( tagName . equals ( "param" ) ) { setParameter ( currentElement , propSetter , props ) ; } else { parseUnrecognizedElement ( instance , currentElement , props ) ; } } } return optionHandler ; } return null ; }
Creates an OptionHandler and processes any nested param elements but does not call activateOptions . If the class also supports UnrecognizedElementParser the parseUnrecognizedElement method will be call for any child elements other than param .
2,791
public String getFormattedStatus ( ) { final StringBuilder sb = new StringBuilder ( ) ; final SimpleDateFormat format = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss,SSS" ) ; sb . append ( format . format ( new Date ( timestamp ) ) ) ; sb . append ( SPACE ) ; sb . append ( getThreadName ( ) ) ; sb . append ( SPACE ) ; sb . append ( level . toString ( ) ) ; sb . append ( SPACE ) ; sb . append ( msg . getFormattedMessage ( ) ) ; final Object [ ] params = msg . getParameters ( ) ; Throwable t ; if ( throwable == null && params != null && params [ params . length - 1 ] instanceof Throwable ) { t = ( Throwable ) params [ params . length - 1 ] ; } else { t = throwable ; } if ( t != null ) { sb . append ( SPACE ) ; final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; t . printStackTrace ( new PrintStream ( baos ) ) ; sb . append ( baos . toString ( ) ) ; } return sb . toString ( ) ; }
Formats the StatusData for viewing .
2,792
public static void putAll ( final Map < String , String > m ) { if ( contextMap instanceof ThreadContextMap2 ) { ( ( ThreadContextMap2 ) contextMap ) . putAll ( m ) ; } else if ( contextMap instanceof DefaultThreadContextMap ) { ( ( DefaultThreadContextMap ) contextMap ) . putAll ( m ) ; } else { for ( final Map . Entry < String , String > entry : m . entrySet ( ) ) { contextMap . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } } }
Puts all given context map entries into the current thread s context map .
2,793
public static Map < String , String > getImmutableContext ( ) { final Map < String , String > map = contextMap . getImmutableMapOrNull ( ) ; return map == null ? EMPTY_MAP : map ; }
Returns an immutable view of the current thread s context Map .
2,794
public static ContextStack getImmutableStack ( ) { final ContextStack result = contextStack . getImmutableStackOrNull ( ) ; return result == null ? EMPTY_STACK : result ; }
Gets an immutable copy of this current thread s context stack .
2,795
public static void setStack ( final Collection < String > stack ) { if ( stack . isEmpty ( ) || ! useStack ) { return ; } contextStack . clear ( ) ; contextStack . addAll ( stack ) ; }
Sets this thread s stack .
2,796
public static void push ( final String message , final Object ... args ) { contextStack . push ( ParameterizedMessage . format ( message , args ) ) ; }
Pushes new diagnostic context information for the current thread .
2,797
protected final void parseFileNamePattern ( ) { List converters = new ArrayList ( ) ; List fields = new ArrayList ( ) ; ExtrasPatternParser . parse ( fileNamePatternStr , converters , fields , null , ExtrasPatternParser . getFileNamePatternRules ( ) ) ; patternConverters = new PatternConverter [ converters . size ( ) ] ; patternConverters = ( PatternConverter [ ] ) converters . toArray ( patternConverters ) ; patternFields = new ExtrasFormattingInfo [ converters . size ( ) ] ; patternFields = ( ExtrasFormattingInfo [ ] ) fields . toArray ( patternFields ) ; }
Parse file name pattern .
2,798
protected final void formatFileName ( final Object obj , final StringBuffer buf ) { for ( int i = 0 ; i < patternConverters . length ; i ++ ) { int fieldStart = buf . length ( ) ; patternConverters [ i ] . format ( obj , buf ) ; if ( patternFields [ i ] != null ) { patternFields [ i ] . format ( fieldStart , buf ) ; } } }
Format file name .
2,799
public void animateProgressFill ( int animateTo ) { mAnimationHandler . removeMessages ( 0 ) ; if ( animateTo > mMax || animateTo < 0 ) { throw new IllegalArgumentException ( String . format ( "Animation progress (%d) is greater than the max progress (%d) or lower than 0 " , animateTo , mMax ) ) ; } mAnimationHandler . setAnimateTo ( animateTo ) ; mAnimationHandler . sendEmptyMessage ( 0 ) ; invalidate ( ) ; }
Animates a progress fill of the view using a Handler .