Input: Query by both base id and related id [CODESPLIT] public UserCustomCursor queryByIds ( long baseId , long relatedId ) { return query ( buildWhereIds ( baseId , relatedId ) , buildWhereIdsArgs ( baseId , relatedId ) ) ; }


Input: Get the unique base ids [CODESPLIT] public List < Long > uniqueBaseIds ( ) { return querySingleColumnTypedResults ( "SELECT DISTINCT " + CoreSQLUtils . quoteWrap ( UserMappingTable . COLUMN_BASE_ID ) + " FROM " + CoreSQLUtils . quoteWrap ( getTableName ( ) ) , null ) ; }


Input: Get the unique related ids [CODESPLIT] public List < Long > uniqueRelatedIds ( ) { return querySingleColumnTypedResults ( "SELECT DISTINCT " + CoreSQLUtils . quoteWrap ( UserMappingTable . COLUMN_RELATED_ID ) + " FROM " + CoreSQLUtils . quoteWrap ( getTableName ( ) ) , null ) ; }


Input: Delete user mappings by base id [CODESPLIT] public int deleteByBaseId ( long baseId ) { StringBuilder where = new StringBuilder ( ) ; where . append ( buildWhere ( UserMappingTable . COLUMN_BASE_ID , baseId ) ) ; String [ ] whereArgs = buildWhereArgs ( new Object [ ] { baseId } ) ; int deleted = delete ( where . toString ( ) , whereArgs ) ; return deleted ; }


Input: Delete user mappings by related id [CODESPLIT] public int deleteByRelatedId ( long relatedId ) { StringBuilder where = new StringBuilder ( ) ; where . append ( buildWhere ( UserMappingTable . COLUMN_RELATED_ID , relatedId ) ) ; String [ ] whereArgs = buildWhereArgs ( new Object [ ] { relatedId } ) ; int deleted = delete ( where . toString ( ) , whereArgs ) ; return deleted ; }


Input: Delete user mappings by both base id and related id [CODESPLIT] public int deleteByIds ( long baseId , long relatedId ) { return delete ( buildWhereIds ( baseId , relatedId ) , buildWhereIdsArgs ( baseId , relatedId ) ) ; }


Input: Build the where ids clause [CODESPLIT] private String buildWhereIds ( long baseId , long relatedId ) { StringBuilder where = new StringBuilder ( ) ; where . append ( buildWhere ( UserMappingTable . COLUMN_BASE_ID , baseId ) ) ; where . append ( " AND " ) ; where . append ( buildWhere ( UserMappingTable . COLUMN_RELATED_ID , relatedId ) ) ; return where . toString ( ) ; }


Input: Create a new GeoPackage metadata [CODESPLIT] public void create ( GeoPackageMetadata metadata ) { ContentValues values = new ContentValues ( ) ; values . put ( GeoPackageMetadata . COLUMN_NAME , metadata . getName ( ) ) ; values . put ( GeoPackageMetadata . COLUMN_EXTERNAL_PATH , metadata . getExternalPath ( ) ) ; long insertId = db . insert ( GeoPackageMetadata . TABLE_NAME , null , values ) ; if ( insertId == - 1 ) { throw new GeoPackageException ( "Failed to insert GeoPackage metadata. Name: " + metadata . getName ( ) + ", External Path: " + metadata . getExternalPath ( ) ) ; } metadata . setId ( insertId ) ; }


Input: Delete the database [CODESPLIT] public boolean delete ( String database ) { GeoPackageMetadata metadata = get ( database ) ; if ( metadata != null ) { TableMetadataDataSource tableDs = new TableMetadataDataSource ( db ) ; tableDs . delete ( metadata . getId ( ) ) ; } String whereClause = GeoPackageMetadata . COLUMN_NAME + " = ?" ; String [ ] whereArgs = new String [ ] { database } ; int deleteCount = db . delete ( GeoPackageMetadata . TABLE_NAME , whereClause , whereArgs ) ; return deleteCount > 0 ; }


Input: Rename the GeoPackage metadata to the new name [CODESPLIT] public boolean rename ( GeoPackageMetadata metadata , String newName ) { boolean renamed = rename ( metadata . getName ( ) , newName ) ; if ( renamed ) { metadata . setName ( newName ) ; } return renamed ; }


Input: Rename the GeoPackage name to the new name [CODESPLIT] public boolean rename ( String name , String newName ) { String whereClause = GeoPackageMetadata . COLUMN_NAME + " = ?" ; String [ ] whereArgs = new String [ ] { name } ; ContentValues values = new ContentValues ( ) ; values . put ( GeoPackageMetadata . COLUMN_NAME , newName ) ; int updateCount = db . update ( GeoPackageMetadata . TABLE_NAME , values , whereClause , whereArgs ) ; return updateCount > 0 ; }


Input: Get all GeoPackage metadata [CODESPLIT] public List < GeoPackageMetadata > getAll ( ) { List < GeoPackageMetadata > allMetadata = new ArrayList < GeoPackageMetadata > ( ) ; Cursor cursor = db . query ( GeoPackageMetadata . TABLE_NAME , GeoPackageMetadata . COLUMNS , null , null , null , null , null ) ; try { while ( cursor . moveToNext ( ) ) { GeoPackageMetadata metadata = createGeoPackageMetadata ( cursor ) ; allMetadata . add ( metadata ) ; } } finally { cursor . close ( ) ; } return allMetadata ; }


Input: Get all external GeoPackage metadata [CODESPLIT] public List < GeoPackageMetadata > getAllExternal ( ) { List < GeoPackageMetadata > allMetadata = new ArrayList < GeoPackageMetadata > ( ) ; String selection = GeoPackageMetadata . COLUMN_EXTERNAL_PATH + " IS NOT NULL" ; Cursor cursor = db . query ( GeoPackageMetadata . TABLE_NAME , GeoPackageMetadata . COLUMNS , selection , null , null , null , null ) ; try { while ( cursor . moveToNext ( ) ) { GeoPackageMetadata metadata = createGeoPackageMetadata ( cursor ) ; allMetadata . add ( metadata ) ; } } finally { cursor . close ( ) ; } return allMetadata ; }


Input: Get GeoPackage metadata by name [CODESPLIT] public GeoPackageMetadata get ( String database ) { GeoPackageMetadata metadata = null ; String selection = GeoPackageMetadata . COLUMN_NAME + " = ?" ; String [ ] selectionArgs = new String [ ] { database } ; Cursor cursor = db . query ( GeoPackageMetadata . TABLE_NAME , GeoPackageMetadata . COLUMNS , selection , selectionArgs , null , null , null ) ; try { if ( cursor . moveToNext ( ) ) { metadata = createGeoPackageMetadata ( cursor ) ; } } finally { cursor . close ( ) ; } return metadata ; }


Input: Get GeoPackage metadata by id [CODESPLIT] public GeoPackageMetadata get ( long id ) { GeoPackageMetadata metadata = null ; String selection = GeoPackageMetadata . COLUMN_ID + " = ?" ; String [ ] selectionArgs = new String [ ] { String . valueOf ( id ) } ; Cursor cursor = db . query ( GeoPackageMetadata . TABLE_NAME , GeoPackageMetadata . COLUMNS , selection , selectionArgs , null , null , null ) ; try { if ( cursor . moveToNext ( ) ) { metadata = createGeoPackageMetadata ( cursor ) ; } } finally { cursor . close ( ) ; } return metadata ; }


Input: Get GeoPackage metadata or create it if it does not exist [CODESPLIT] public GeoPackageMetadata getOrCreate ( String geoPackage ) { GeoPackageMetadata metadata = get ( geoPackage ) ; if ( metadata == null ) { metadata = new GeoPackageMetadata ( ) ; metadata . setName ( geoPackage ) ; create ( metadata ) ; } return metadata ; }


Input: Determine if the GeoPackage is external [CODESPLIT] public boolean isExternal ( String database ) { GeoPackageMetadata metadata = get ( database ) ; return get ( database ) != null && metadata . getExternalPath ( ) != null ; }


Input: Get external GeoPackage metadata by external path [CODESPLIT] public GeoPackageMetadata getExternalAtPath ( String path ) { GeoPackageMetadata metadata = null ; String selection = GeoPackageMetadata . COLUMN_EXTERNAL_PATH + " = ?" ; String [ ] selectionArgs = new String [ ] { path } ; Cursor cursor = db . query ( GeoPackageMetadata . TABLE_NAME , GeoPackageMetadata . COLUMNS , selection , selectionArgs , null , null , null ) ; try { if ( cursor . moveToNext ( ) ) { metadata = createGeoPackageMetadata ( cursor ) ; } } finally { cursor . close ( ) ; } return metadata ; }


Input: Get metadata where the name is like [CODESPLIT] public List < String > getMetadataWhereNameLike ( String like , String sortColumn ) { return getMetadataWhereNameLike ( like , sortColumn , false ) ; }


Input: Get metadata where the name is not like [CODESPLIT] public List < String > getMetadataWhereNameNotLike ( String notLike , String sortColumn ) { return getMetadataWhereNameLike ( notLike , sortColumn , true ) ; }


Input: Get metadata where the name is like or not like [CODESPLIT] private List < String > getMetadataWhereNameLike ( String like , String sortColumn , boolean notLike ) { List < String > names = new ArrayList <> ( ) ; StringBuilder where = new StringBuilder ( GeoPackageMetadata . COLUMN_NAME ) ; if ( notLike ) { where . append ( " not" ) ; } where . append ( " like ?" ) ; String [ ] whereArgs = new String [ ] { like } ; Cursor cursor = db . query ( GeoPackageMetadata . TABLE_NAME , new String [ ] { GeoPackageMetadata . COLUMN_NAME } , where . toString ( ) , whereArgs , null , null , sortColumn ) ; try { while ( cursor . moveToNext ( ) ) { names . add ( cursor . getString ( 0 ) ) ; } } finally { cursor . close ( ) ; } return names ; }


Input: Create a GeoPackage metadata from the current cursor location [CODESPLIT] private GeoPackageMetadata createGeoPackageMetadata ( Cursor cursor ) { GeoPackageMetadata metadata = new GeoPackageMetadata ( ) ; metadata . setId ( cursor . getLong ( 0 ) ) ; metadata . setName ( cursor . getString ( 1 ) ) ; metadata . setExternalPath ( cursor . getString ( 2 ) ) ; return metadata ; }


Input: { [CODESPLIT] @ Override public AttributesRow getRow ( int [ ] columnTypes , Object [ ] values ) { return new AttributesRow ( getTable ( ) , columnTypes , values ) ; }


Input: { [CODESPLIT] @ Override protected UserInvalidCursor < AttributesColumn , AttributesTable , AttributesRow , ? extends UserCursor < AttributesColumn , AttributesTable , AttributesRow > , ? extends UserDao < AttributesColumn , AttributesTable , AttributesRow , ? extends UserCursor < AttributesColumn , AttributesTable , AttributesRow > > > createInvalidCursor ( UserDao dao , UserCursor cursor , List < Integer > invalidPositions , List < AttributesColumn > blobColumns ) { return new AttributesInvalidCursor ( ( AttributesDao ) dao , ( AttributesCursor ) cursor , invalidPositions , blobColumns ) ; }


Input:
{ [CODESPLIT] @ Override public Iterator < FeatureRow > iterator ( ) { return new Iterator < FeatureRow > ( ) { /**
             * {@inheritDoc}
             */ @ Override public boolean hasNext ( ) { return geometryIndices . hasNext ( ) ; } /**
             * {@inheritDoc}
             */ @ Override public FeatureRow next ( ) { GeometryIndex geometryIndex = geometryIndices . next ( ) ; FeatureRow featureRow = featureTableIndex . getFeatureRow ( geometryIndex ) ; return featureRow ; } } ; }


Input:
{ [CODESPLIT] @ Override public Iterable < Long > ids ( ) { return new Iterable < Long > ( ) { /**
             * {@inheritDoc}
             */ @ Override public Iterator < Long > iterator ( ) { return featureIds . iterator ( ) ; } } ; }


Input: Handle the created view [CODESPLIT] public View onViewCreated ( View view , Context context , AttributeSet attrs ) { if ( view == null ) { return null ; } view = onViewCreatedInternal ( view , context , attrs ) ; for ( OnViewCreatedListener listener : otherListeners ) { if ( listener != null ) { view = listener . onViewCreated ( view , context , attrs ) ; } } return view ; }


Input: Sets the { @link ViewPager . OnPageChangeListener } to the embedded { @link ViewPager } created by the container . [CODESPLIT] @ Deprecated protected void attachOnPageChangeListener ( ViewPager viewPager , ViewPager . OnPageChangeListener listener ) { viewPager . setOnPageChangeListener ( listener ) ; }


Input: attach attributes in tag [CODESPLIT] private void addParallaxView ( View view , int pageIndex ) { if ( view instanceof ViewGroup ) { // recurse children ViewGroup viewGroup = ( ViewGroup ) view ; for ( int i = 0 , childCount = viewGroup . getChildCount ( ) ; i < childCount ; i ++ ) { addParallaxView ( viewGroup . getChildAt ( i ) , pageIndex ) ; } } ParallaxViewTag tag = ( ParallaxViewTag ) view . getTag ( R . id . parallax_view_tag ) ; if ( tag != null ) { // only track view if it has a parallax tag tag . index = pageIndex ; parallaxViews . add ( view ) ; } }


Input: The LayoutInflater onCreateView is the fourth port of call for LayoutInflation . BUT only for none CustomViews . Basically if this method doesn t inflate the View nothing probably will . [CODESPLIT] @ Override protected View onCreateView ( String name , AttributeSet attrs ) throws ClassNotFoundException { // This mimics the {@code PhoneLayoutInflater} in the way it tries to inflate the base // classes, if this fails its pretty certain the app will fail at this point. View view = null ; for ( String prefix : sClassPrefixList ) { try { view = createView ( name , prefix , attrs ) ; } catch ( ClassNotFoundException ignored ) { } } // In this case we want to let the base class take a crack // at it. if ( view == null ) { view = super . onCreateView ( name , attrs ) ; } return mParallaxFactory . onViewCreated ( view , view . getContext ( ) , attrs ) ; }


Input: Nasty method to inflate custom layouts that haven t been handled else where . If this fails it will fall back through to the PhoneLayoutInflater method of inflating custom views where Calligraphy will NOT have a hook into . [CODESPLIT] private View createCustomViewInternal ( View parent , View view , String name , Context context , AttributeSet attrs ) { // I by no means advise anyone to do this normally, but Google have locked down access to // the createView() method, so we never get a callback with attributes at the end of the // createViewFromTag chain (which would solve all this unnecessary rubbish). // We at the very least try to optimise this as much as possible. // We only call for customViews (As they are the ones that never go through onCreateView(...)). // We also maintain the Field reference and make it accessible which will make a pretty // significant difference to performance on Android 4.0+. // If CustomViewCreation is off skip this. if ( view == null && name . indexOf ( ' ' ) > - 1 ) { if ( mConstructorArgs == null ) { mConstructorArgs = ReflectionUtils . getField ( LayoutInflater . class , "mConstructorArgs" ) ; } final Object [ ] mConstructorArgsArr = ( Object [ ] ) ReflectionUtils . getValue ( mConstructorArgs , this ) ; final Object lastContext = mConstructorArgsArr [ 0 ] ; mConstructorArgsArr [ 0 ] = parent != null ? parent . getContext ( ) : context ; ReflectionUtils . setValue ( mConstructorArgs , this , mConstructorArgsArr ) ; try { view = createView ( name , null , attrs ) ; } catch ( ClassNotFoundException ignored ) { } finally { mConstructorArgsArr [ 0 ] = lastContext ; ReflectionUtils . setValue ( mConstructorArgs , this , mConstructorArgsArr ) ; } } return view ; }


Input: } [CODESPLIT] @ Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . activity_parallax ) ; if ( savedInstanceState == null ) { getSupportFragmentManager ( ) . beginTransaction ( ) . add ( R . id . content , new ParallaxFragment ( ) ) . commit ( ) ; } }


Input: / * Convert a level to equivalent syslog severity . Only levels for printing methods i . e TRACE DEBUG WARN INFO and ERROR are converted . [CODESPLIT] static public int convert ( ILoggingEvent event ) { Level level = event . getLevel ( ) ; switch ( level . levelInt ) { case Level . ERROR_INT : return SyslogConstants . ERROR_SEVERITY ; case Level . WARN_INT : return SyslogConstants . WARNING_SEVERITY ; case Level . INFO_INT : return SyslogConstants . INFO_SEVERITY ; case Level . DEBUG_INT : case Level . TRACE_INT : return SyslogConstants . DEBUG_SEVERITY ; default : throw new IllegalArgumentException ( "Level " + level + " is not a valid level for a printing method" ) ; } }


Input: Creates a new { @link ch . qos . logback . core . net . AutoFlushingObjectWriter } instance . [CODESPLIT] public AutoFlushingObjectWriter newAutoFlushingObjectWriter ( OutputStream outputStream ) throws IOException { return new AutoFlushingObjectWriter ( new ObjectOutputStream ( outputStream ) , CoreConstants . OOS_RESET_FREQUENCY ) ; }


Input: Perform SMTPAppender specific appending actions mainly adding the event to a cyclic buffer . [CODESPLIT] protected void subAppend ( CyclicBuffer < ILoggingEvent > cb , ILoggingEvent event ) { if ( includeCallerData ) { event . getCallerData ( ) ; } event . prepareForDeferredProcessing ( ) ; cb . add ( event ) ; }


Input: Finds a configuration file by system property [CODESPLIT] private URL findConfigFileFromSystemProperties ( boolean updateStatus ) { String logbackConfigFile = OptionHelper . getSystemProperty ( CONFIG_FILE_PROPERTY ) ; if ( logbackConfigFile != null ) { URL result = null ; try { File file = new File ( logbackConfigFile ) ; if ( file . exists ( ) && file . isFile ( ) ) { if ( updateStatus ) { statusOnResourceSearch ( logbackConfigFile , this . classLoader , logbackConfigFile ) ; } result = file . toURI ( ) . toURL ( ) ; } else { result = new URL ( logbackConfigFile ) ; } return result ; } catch ( MalformedURLException e ) { // so, resource is not a URL: // attempt to get the resource from the class path result = Loader . getResource ( logbackConfigFile , this . classLoader ) ; if ( result != null ) { return result ; } } finally { if ( updateStatus ) { statusOnResourceSearch ( logbackConfigFile , this . classLoader , result != null ? result . toString ( ) : null ) ; } } } return null ; }


Input: Uses the given classloader to search for a resource [CODESPLIT] private URL getResource ( String filename , ClassLoader myClassLoader , boolean updateStatus ) { URL url = myClassLoader . getResource ( filename ) ; if ( updateStatus ) { String resourcePath = null ; if ( url != null ) { resourcePath = filename ; } statusOnResourceSearch ( filename , myClassLoader , resourcePath ) ; } return url ; }


Input: Configures logback with the first configuration found in the following search path . If no configuration found nothing is done and logging is disabled . [CODESPLIT] public void autoConfig ( ) throws JoranException { StatusListenerConfigHelper . installIfAsked ( loggerContext ) ; new AndroidContextUtil ( ) . setupProperties ( loggerContext ) ; boolean verbose = true ; boolean configured = false ; JoranConfigurator configurator = new JoranConfigurator ( ) ; configurator . setContext ( loggerContext ) ; // search system property if ( ! configured ) { URL url = findConfigFileFromSystemProperties ( verbose ) ; if ( url != null ) { configurator . doConfigure ( url ) ; configured = true ; } } // search assets if ( ! configured ) { URL assetsConfigUrl = findConfigFileURLFromAssets ( verbose ) ; if ( assetsConfigUrl != null ) { configurator . doConfigure ( assetsConfigUrl ) ; configured = true ; } } }


Input: Adds a status message for the result of the resource search [CODESPLIT] private void statusOnResourceSearch ( String resourceName , ClassLoader classLoader , String path ) { StatusManager sm = loggerContext . getStatusManager ( ) ; if ( path == null ) { sm . add ( new InfoStatus ( "Could NOT find resource [" + resourceName + "]" , loggerContext ) ) ; } else { sm . add ( new InfoStatus ( "Found resource [" + resourceName + "] at [" + path + "]" , loggerContext ) ) ; } }


Input: { [CODESPLIT] public T acceptClient ( ) throws IOException { Socket socket = serverSocket . accept ( ) ; return createClient ( socketAddressToString ( socket . getRemoteSocketAddress ( ) ) , socket ) ; }


Input: Converts a socket address to a reasonable display string . [CODESPLIT] private String socketAddressToString ( SocketAddress address ) { String addr = address . toString ( ) ; int i = addr . indexOf ( "/" ) ; if ( i >= 0 ) { addr = addr . substring ( i + 1 ) ; } return addr ; }


Input: Creates an executor service suitable for use by logback components . [CODESPLIT] static public ExecutorService newExecutorService ( ) { return new ThreadPoolExecutor ( CoreConstants . CORE_POOL_SIZE , CoreConstants . MAX_POOL_SIZE , 0L , TimeUnit . MILLISECONDS , new SynchronousQueue < Runnable > ( ) , THREAD_FACTORY ) ; }


Input: Start converters in the chain of converters . [CODESPLIT] public static < E > void startConverters ( Converter < E > head ) { Converter < E > c = head ; while ( c != null ) { // CompositeConverter is a subclass of  DynamicConverter if ( c instanceof CompositeConverter ) { CompositeConverter < E > cc = ( CompositeConverter < E > ) c ; Converter < E > childConverter = cc . childConverter ; startConverters ( childConverter ) ; cc . start ( ) ; } else if ( c instanceof DynamicConverter ) { DynamicConverter < E > dc = ( DynamicConverter < E > ) c ; dc . start ( ) ; } c = c . getNext ( ) ; } }


Input: This method differentiates RollingFileAppender from its super class . [CODESPLIT] @ Override protected void subAppend ( E event ) { // The roll-over check must precede actual writing. This is the // only correct behavior for time driven triggers. // We need to synchronize on triggeringPolicy so that only one rollover // occurs at a time synchronized ( triggeringPolicy ) { if ( triggeringPolicy . isTriggeringEvent ( currentlyActiveFile , event ) ) { rollover ( ) ; } } super . subAppend ( event ) ; }


Input: Sets the rolling policy . In case the policy argument also implements { @link TriggeringPolicy } then the triggering policy for this appender is automatically set to be the policy argument . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public void setRollingPolicy ( RollingPolicy policy ) { rollingPolicy = policy ; if ( rollingPolicy instanceof TriggeringPolicy ) { triggeringPolicy = ( TriggeringPolicy < E > ) policy ; } }


Input: Add a property to the properties of this execution context . If the property exists already it is overwritten . [CODESPLIT] public void addSubstitutionProperty ( String key , String value ) { if ( key == null || value == null ) { return ; } // values with leading or trailing spaces are bad. We remove them now. value = value . trim ( ) ; propertiesMap . put ( key , value ) ; }


Input: If a key is found in propertiesMap then return it . Otherwise delegate to the context . [CODESPLIT] public String getProperty ( String key ) { String v = propertiesMap . get ( key ) ; if ( v != null ) { return v ; } else { return context . getProperty ( key ) ; } }


Input: { [CODESPLIT] @ Override protected ServerSocketFactory getServerSocketFactory ( ) throws Exception { if ( socketFactory == null ) { SSLContext sslContext = getSsl ( ) . createContext ( this ) ; SSLParametersConfiguration parameters = getSsl ( ) . getParameters ( ) ; parameters . setContext ( getContext ( ) ) ; socketFactory = new ConfigurableSSLServerSocketFactory ( parameters , sslContext . getServerSocketFactory ( ) ) ; } return socketFactory ; }


Input: This method takes a string which may contain HTML tags ( ie &lt ; b&gt ; &lt ; table&gt ; etc ) and replaces any &lt ; &gt ; ... characters with respective predefined entity references . [CODESPLIT] public static String escapeTags ( final String input ) { if ( input == null || input . length ( ) == 0 || ! UNSAFE_XML_CHARS . matcher ( input ) . find ( ) ) { return input ; } StringBuffer buf = new StringBuffer ( input ) ; return escapeTags ( buf ) ; }


Input: This method takes a StringBuilder which may contain HTML tags ( ie &lt ; b&gt ; &lt ; table&gt ; etc ) and replaces any &lt ; and &gt ; characters with respective predefined entity references . [CODESPLIT] public static String escapeTags ( final StringBuffer buf ) { for ( int i = 0 ; i < buf . length ( ) ; i ++ ) { char ch = buf . charAt ( i ) ; switch ( ch ) { case ' ' : case ' ' : case ' ' : // These characters are below '\u0020' but are allowed: break ; case ' ' : buf . replace ( i , i + 1 , "&" ) ; break ; case ' ' : buf . replace ( i , i + 1 , "<" ) ; break ; case ' ' : buf . replace ( i , i + 1 , ">" ) ; break ; case ' ' : buf . replace ( i , i + 1 , """ ) ; break ; case ' ' : buf . replace ( i , i + 1 , "'" ) ; break ; default : if ( ch < ' ' ) { // These characters are not allowed, // replace them with "Object replacement character": buf . replace ( i , i + 1 , "\uFFFD" ) ; } break ; } } return buf . toString ( ) ; }


Input: Ensures that embedded CDEnd strings ( ]] &gt ; ) are handled properly within message NDC and throwable tag text . [CODESPLIT] public static void appendEscapingCDATA ( StringBuilder output , String str ) { if ( str == null ) { return ; } int end = str . indexOf ( CDATA_END ) ; if ( end < 0 ) { output . append ( str ) ; return ; } int start = 0 ; while ( end > - 1 ) { output . append ( str . substring ( start , end ) ) ; output . append ( CDATA_EMBEDED_END ) ; start = end + CDATA_END_LEN ; if ( start < str . length ( ) ) { end = str . indexOf ( CDATA_END , start ) ; } else { return ; } } output . append ( str . substring ( start ) ) ; }


Input: Retains all values in the subject collection that are matched by at least one of a collection of regular expressions . <p > This method is a convenience overload for { @link #retainMatching ( Collection Collection ) } . [CODESPLIT] public static void retainMatching ( Collection < String > values , String ... patterns ) { retainMatching ( values , Arrays . asList ( patterns ) ) ; }


Input: Retains all values in the subject collection that are matched by at least one of a collection of regular expressions . <p > The semantics of this method are conceptually similar to { @link Collection#retainAll ( Collection ) } but uses pattern matching instead of exact matching . [CODESPLIT] public static void retainMatching ( Collection < String > values , Collection < String > patterns ) { if ( patterns . isEmpty ( ) ) return ; List < String > matches = new ArrayList < String > ( values . size ( ) ) ; for ( String p : patterns ) { Pattern pattern = Pattern . compile ( p ) ; for ( String value : values ) { if ( pattern . matcher ( value ) . matches ( ) ) { matches . add ( value ) ; } } } values . retainAll ( matches ) ; }


Input: Removes all values in the subject collection that are matched by at least one of a collection of regular expressions . <p > This method is a convenience overload for { @link #removeMatching ( Collection Collection ) } . [CODESPLIT] public static void removeMatching ( Collection < String > values , String ... patterns ) { removeMatching ( values , Arrays . asList ( patterns ) ) ; }


Input: Removes all values in the subject collection that are matched by at least one of a collection of regular expressions . <p > The semantics of this method are conceptually similar to { @link Collection#removeAll ( Collection ) } but uses pattern matching instead of exact matching . [CODESPLIT] public static void removeMatching ( Collection < String > values , Collection < String > patterns ) { List < String > matches = new ArrayList < String > ( values . size ( ) ) ; for ( String p : patterns ) { Pattern pattern = Pattern . compile ( p ) ; for ( String value : values ) { if ( pattern . matcher ( value ) . matches ( ) ) { matches . add ( value ) ; } } } values . removeAll ( matches ) ; }


Input: big - endian [CODESPLIT] static void writeInt ( byte [ ] byteArray , int offset , int i ) { for ( int j = 0 ; j < 4 ; j ++ ) { int shift = 24 - j * 8 ; byteArray [ offset + j ] = ( byte ) ( i >>> shift ) ; } }


Input: big - endian [CODESPLIT] static int readInt ( byte [ ] byteArray , int offset ) { int i = 0 ; for ( int j = 0 ; j < 4 ; j ++ ) { int shift = 24 - j * 8 ; i += ( byteArray [ offset + j ] & 0xFF ) << shift ; } return i ; }


Input: When the parsing step is done the Node list can be transformed into a converter chain . [CODESPLIT] public Converter < E > compile ( final Node top , Map < String , String > converterMap ) { Compiler < E > compiler = new Compiler < E > ( top , converterMap ) ; compiler . setContext ( context ) ; //compiler.setStatusManager(statusManager); return compiler . compile ( ) ; }


Input: E = TEopt [CODESPLIT] Node E ( ) throws ScanException { Node t = T ( ) ; if ( t == null ) { return null ; } Node eOpt = Eopt ( ) ; if ( eOpt != null ) { t . setNext ( eOpt ) ; } return t ; }


Input: Eopt = E|~ [CODESPLIT] Node Eopt ( ) throws ScanException { // System.out.println("in Eopt()"); Token next = getCurentToken ( ) ; // System.out.println("Current token is " + next); if ( next == null ) { return null ; } else { return E ( ) ; } }


Input: T = LITERAL | % C | % FORMAT_MODIFIER C [CODESPLIT] Node T ( ) throws ScanException { Token t = getCurentToken ( ) ; expectNotNull ( t , "a LITERAL or '%'" ) ; switch ( t . getType ( ) ) { case Token . LITERAL : advanceTokenPointer ( ) ; return new Node ( Node . LITERAL , t . getValue ( ) ) ; case Token . PERCENT : advanceTokenPointer ( ) ; // System.out.println("% token found"); FormatInfo fi ; Token u = getCurentToken ( ) ; FormattingNode c ; expectNotNull ( u , "a FORMAT_MODIFIER, SIMPLE_KEYWORD or COMPOUND_KEYWORD" ) ; if ( u . getType ( ) == Token . FORMAT_MODIFIER ) { fi = FormatInfo . valueOf ( ( String ) u . getValue ( ) ) ; advanceTokenPointer ( ) ; c = C ( ) ; c . setFormatInfo ( fi ) ; } else { c = C ( ) ; } return c ; default : return null ; } }


Input:
Formats a { [CODESPLIT] public String doLayout ( ILoggingEvent event ) { // Reset working buffer. If the buffer is too large, then we need a new // one in order to avoid the penalty of creating a large array. if ( buf . capacity ( ) > UPPER_LIMIT ) { buf = new StringBuilder ( DEFAULT_SIZE ) ; } else { buf . setLength ( 0 ) ; } // We yield to the \r\n heresy. buf . append ( "<log4j:event logger=\"" ) ; buf . append ( Transform . escapeTags ( event . getLoggerName ( ) ) ) ; buf . append ( "\"\r\n" ) ; buf . append ( "             timestamp=\"" ) ; buf . append ( event . getTimeStamp ( ) ) ; buf . append ( "\" level=\"" ) ; buf . append ( event . getLevel ( ) ) ; buf . append ( "\" thread=\"" ) ; buf . append ( Transform . escapeTags ( event . getThreadName ( ) ) ) ; buf . append ( "\">\r\n" ) ; buf . append ( "  <log4j:message>" ) ; buf . append ( Transform . escapeTags ( event . getFormattedMessage ( ) ) ) ; buf . append ( "</log4j:message>\r\n" ) ; // logback does not support NDC // String ndc = event.getNDC(); IThrowableProxy tp = event . getThrowableProxy ( ) ; if ( tp != null ) { StackTraceElementProxy [ ] stepArray = tp . getStackTraceElementProxyArray ( ) ; buf . append ( "  <log4j:throwable><![CDATA[" ) ; for ( StackTraceElementProxy step : stepArray ) { buf . append ( CoreConstants . TAB ) ; buf . append ( step . toString ( ) ) ; buf . append ( "\r\n" ) ; } buf . append ( "]]></log4j:throwable>\r\n" ) ; } if ( locationInfo ) { StackTraceElement [ ] callerDataArray = event . getCallerData ( ) ; if ( callerDataArray != null && callerDataArray . length > 0 ) { StackTraceElement immediateCallerData = callerDataArray [ 0 ] ; buf . append ( "  <log4j:locationInfo class=\"" ) ; buf . append ( immediateCallerData . getClassName ( ) ) ; buf . append ( "\"\r\n" ) ; buf . append ( "                      method=\"" ) ; buf . append ( Transform . escapeTags ( immediateCallerData . getMethodName ( ) ) ) ; buf . append ( "\" file=\"" ) ; buf . append ( Transform . escapeTags ( immediateCallerData . getFileName ( ) ) ) ; buf . append ( "\" line=\"" ) ; buf . append ( immediateCallerData . getLineNumber ( ) ) ; buf . append ( "\"/>\r\n" ) ; } } /*
     * <log4j:properties> <log4j:data name="name" value="value"/>
     * </log4j:properties>
     */ if ( this . getProperties ( ) ) { Map < String , String > propertyMap = event . getMDCPropertyMap ( ) ; if ( ( propertyMap != null ) && ( propertyMap . size ( ) != 0 ) ) { Set < Entry < String , String > > entrySet = propertyMap . entrySet ( ) ; buf . append ( "  <log4j:properties>" ) ; for ( Entry < String , String > entry : entrySet ) { buf . append ( "\r\n    <log4j:data" ) ; buf . append ( " name=\"" + Transform . escapeTags ( entry . getKey ( ) ) + "\"" ) ; buf . append ( " value=\"" + Transform . escapeTags ( entry . getValue ( ) ) + "\"" ) ; buf . append ( " />" ) ; } buf . append ( "\r\n  </log4j:properties>" ) ; } } buf . append ( "\r\n</log4j:event>\r\n\r\n" ) ; return buf . toString ( ) ; }


Input: Do not perform any character escaping except for % and ) . [CODESPLIT] public void escape ( String escapeChars , StringBuffer buf , char next , int pointer ) { super . escape ( "" + CoreConstants . PERCENT_CHAR + CoreConstants . RIGHT_PARENTHESIS_CHAR , buf , next , pointer ) ; }


Input: Given date convert this instance to a regular expression . [CODESPLIT] public String toRegexForFixedDate ( Date date ) { StringBuilder buf = new StringBuilder ( ) ; Converter < Object > p = headTokenConverter ; while ( p != null ) { if ( p instanceof LiteralConverter ) { buf . append ( p . convert ( null ) ) ; } else if ( p instanceof IntegerTokenConverter ) { buf . append ( FileFinder . regexEscapePath ( "(\\d+)" ) ) ; } else if ( p instanceof DateTokenConverter ) { DateTokenConverter < Object > dtc = ( DateTokenConverter < Object > ) p ; if ( dtc . isPrimary ( ) ) { buf . append ( p . convert ( date ) ) ; } else { buf . append ( FileFinder . regexEscapePath ( dtc . toRegex ( ) ) ) ; } } p = p . getNext ( ) ; } return buf . toString ( ) ; }


Input: { [CODESPLIT] @ Override public ServerSocket createServerSocket ( int port , int backlog ) throws IOException { SSLServerSocket socket = ( SSLServerSocket ) delegate . createServerSocket ( port , backlog ) ; parameters . configure ( new SSLConfigurableServerSocket ( socket ) ) ; return socket ; }


Input: Instantiates an evaluator of the given class and sets its name . [CODESPLIT] public void begin ( InterpretationContext ec , String name , Attributes attributes ) { // Let us forget about previous errors (in this instance) inError = false ; evaluator = null ; String className = attributes . getValue ( CLASS_ATTRIBUTE ) ; if ( OptionHelper . isEmpty ( className ) ) { className = defaultClassName ( ) ; addInfo ( "Assuming default evaluator class [" + className + "]" ) ; } if ( OptionHelper . isEmpty ( className ) ) { className = defaultClassName ( ) ; inError = true ; addError ( "Mandatory \"" + CLASS_ATTRIBUTE + "\" attribute not set for <evaluator>" ) ; return ; } String evaluatorName = attributes . getValue ( Action . NAME_ATTRIBUTE ) ; if ( OptionHelper . isEmpty ( evaluatorName ) ) { inError = true ; addError ( "Mandatory \"" + NAME_ATTRIBUTE + "\" attribute not set for <evaluator>" ) ; return ; } try { evaluator = ( EventEvaluator < ? > ) OptionHelper . instantiateByClassName ( className , ch . qos . logback . core . boolex . EventEvaluator . class , context ) ; evaluator . setContext ( this . context ) ; evaluator . setName ( evaluatorName ) ; ec . pushObject ( evaluator ) ; addInfo ( "Adding evaluator named [" + evaluatorName + "] to the object stack" ) ; } catch ( Exception oops ) { inError = true ; addError ( "Could not create evaluator of type " + className + "]." , oops ) ; } }


Input: Once the children elements are also parsed now is the time to activate the evaluator options . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public void end ( InterpretationContext ec , String e ) { if ( inError ) { return ; } if ( evaluator instanceof LifeCycle ) { ( ( LifeCycle ) evaluator ) . start ( ) ; addInfo ( "Starting evaluator named [" + evaluator . getName ( ) + "]" ) ; } Object o = ec . peekObject ( ) ; if ( o != evaluator ) { addWarn ( "The object on the top the of the stack is not the evaluator pushed earlier." ) ; } else { ec . popObject ( ) ; try { Map < String , EventEvaluator < ? > > evaluatorMap = ( Map < String , EventEvaluator < ? > > ) context . getObject ( CoreConstants . EVALUATOR_MAP ) ; if ( evaluatorMap == null ) { addError ( "Could not find EvaluatorMap" ) ; } else { evaluatorMap . put ( evaluator . getName ( ) , evaluator ) ; } } catch ( Exception ex ) { addError ( "Could not set evaluator named [" + evaluator + "]." , ex ) ; } } }


Input: FOR INTERNAL USE . This method is intended for use by StaticLoggerBinder . [CODESPLIT] public void init ( LoggerContext defaultLoggerContext , Object key ) throws ClassNotFoundException , NoSuchMethodException , InstantiationException , IllegalAccessException , InvocationTargetException { if ( this . key == null ) { this . key = key ; } else if ( this . key != key ) { throw new IllegalAccessException ( "Only certain classes can access this method." ) ; } String contextSelectorStr = OptionHelper . getSystemProperty ( ClassicConstants . LOGBACK_CONTEXT_SELECTOR ) ; if ( contextSelectorStr == null ) { contextSelector = new DefaultContextSelector ( defaultLoggerContext ) ; } else if ( contextSelectorStr . equals ( "JNDI" ) ) { throw new RuntimeException ( "JNDI not supported" ) ; } else { contextSelector = dynamicalContextSelector ( defaultLoggerContext , contextSelectorStr ) ; } }


Input: Instantiate the context selector class designated by the user . The selector must have a constructor taking a LoggerContext instance as an argument . [CODESPLIT] static ContextSelector dynamicalContextSelector ( LoggerContext defaultLoggerContext , String contextSelectorStr ) throws ClassNotFoundException , SecurityException , NoSuchMethodException , IllegalArgumentException , InstantiationException , IllegalAccessException , InvocationTargetException { Class < ? > contextSelectorClass = Loader . loadClass ( contextSelectorStr ) ; Constructor cons = contextSelectorClass . getConstructor ( new Class [ ] { LoggerContext . class } ) ; return ( ContextSelector ) cons . newInstance ( defaultLoggerContext ) ; }


Input: Sets properties for use in configs [CODESPLIT] public void setupProperties ( LoggerContext context ) { // legacy properties Properties props = new Properties ( ) ; props . setProperty ( CoreConstants . DATA_DIR_KEY , getFilesDirectoryPath ( ) ) ; final String extDir = getMountedExternalStorageDirectoryPath ( ) ; if ( extDir != null ) { props . setProperty ( CoreConstants . EXT_DIR_KEY , extDir ) ; } props . setProperty ( CoreConstants . PACKAGE_NAME_KEY , getPackageName ( ) ) ; props . setProperty ( CoreConstants . VERSION_CODE_KEY , getVersionCode ( ) ) ; props . setProperty ( CoreConstants . VERSION_NAME_KEY , getVersionName ( ) ) ; context . putProperties ( props ) ; }


Input: Gets the path to the external storage directory only if mounted . [CODESPLIT] public String getMountedExternalStorageDirectoryPath ( ) { String path = null ; String state = Environment . getExternalStorageState ( ) ; if ( state . equals ( Environment . MEDIA_MOUNTED ) || state . equals ( Environment . MEDIA_MOUNTED_READ_ONLY ) ) { path = absPath ( Environment . getExternalStorageDirectory ( ) ) ; } return path ; }


Input: Returns the absolute path to the directory on the Android filesystem similar to { @link #getFilesDirectoryPath () } . The difference is these files are excluded from automatic backup to remote storage by { @code android . app . backup . BackupAgent } . This API is only available on SDK 21 + . On older versions this function returns an empty string . [CODESPLIT] @ TargetApi ( 21 ) public String getNoBackupFilesDirectoryPath ( ) { return Build . VERSION . SDK_INT >= 21 && this . context != null ? absPath ( this . context . getNoBackupFilesDir ( ) ) : "" ; }


Input: Returns the absolute path to the directory on the Android filesystem where databases are stored for the current application . [CODESPLIT] public String getDatabaseDirectoryPath ( ) { return this . context != null && this . context . getDatabasePath ( "x" ) != null ? this . context . getDatabasePath ( "x" ) . getParent ( ) : "" ; }


Input: The <b > File< / b > property takes a string value which should be the name of the file to append to . [CODESPLIT] public void setFile ( String file ) { if ( file == null ) { fileName = null ; } else { // Trim spaces from both ends. The users probably does not want // trailing spaces in file names. fileName = file . trim ( ) ; } }


Input: If the value of <b > File< / b > is not <code > null< / code > then { [CODESPLIT] public void start ( ) { int errors = 0 ; // Use getFile() instead of direct access to fileName because // the function is overridden in RollingFileAppender, which // returns a value that doesn't necessarily match fileName. String file = getFile ( ) ; if ( file != null ) { file = getAbsoluteFilePath ( file ) ; addInfo ( "File property is set to [" + file + "]" ) ; if ( prudent ) { if ( ! isAppend ( ) ) { setAppend ( true ) ; addWarn ( "Setting \"Append\" property to true on account of \"Prudent\" mode" ) ; } } if ( ! lazyInit ) { if ( checkForFileCollisionInPreviousFileAppenders ( ) ) { addError ( "Collisions detected with FileAppender/RollingAppender instances defined earlier. Aborting." ) ; addError ( COLLISION_WITH_EARLIER_APPENDER_URL ) ; errors ++ ; } else { // file should be opened only if collision free try { openFile ( file ) ; } catch ( IOException e ) { errors ++ ; addError ( "openFile(" + file + "," + append + ") failed" , e ) ; } } } else { // We'll initialize the file output stream later. Use a dummy for now // to satisfy OutputStreamAppender.start(). setOutputStream ( new NOPOutputStream ( ) ) ; } } else { errors ++ ; addError ( "\"File\" property not set for appender named [" + name + "]" ) ; } if ( errors == 0 ) { super . start ( ) ; } }


Input: <p > Sets and <i > opens< / i > the file where the log output will go . The specified file must be writable . [CODESPLIT] protected boolean openFile ( String filename ) throws IOException { boolean successful = false ; filename = getAbsoluteFilePath ( filename ) ; lock . lock ( ) ; try { File file = new File ( filename ) ; boolean result = FileUtil . createMissingParentDirectories ( file ) ; if ( ! result ) { addError ( "Failed to create parent directories for [" + file . getAbsolutePath ( ) + "]" ) ; } ResilientFileOutputStream resilientFos = new ResilientFileOutputStream ( file , append , bufferSize . getSize ( ) ) ; resilientFos . setContext ( context ) ; setOutputStream ( resilientFos ) ; successful = true ; } finally { lock . unlock ( ) ; } return successful ; }


Input: Gets the absolute path to the filename starting from the app s files directory if it is not already an absolute path [CODESPLIT] private String getAbsoluteFilePath ( String filename ) { // In Android, relative paths created with File() are relative // to root, so fix it by prefixing the path to the app's "files" // directory. // This transformation is rather expensive, since it involves loading the // Android manifest from the APK (which is a ZIP file), and parsing it to // retrieve the application package name. This should be avoided if // possible as it may perceptibly delay the app launch time. if ( EnvUtil . isAndroidOS ( ) && ! new File ( filename ) . isAbsolute ( ) ) { String dataDir = context . getProperty ( CoreConstants . DATA_DIR_KEY ) ; filename = FileUtil . prefixRelativePath ( dataDir , filename ) ; } return filename ; }


Input: Return true if event passed as parameter has level ERROR or higher returns false otherwise . [CODESPLIT] public boolean evaluate ( ILoggingEvent event ) throws NullPointerException , EvaluationException { return event . getLevel ( ) . levelInt >= Level . ERROR_INT ; }


Input: Return the value associated with an MDC entry designated by the Key property . If that value is null then return the value assigned to the DefaultValue property . [CODESPLIT] public String getDiscriminatingValue ( ILoggingEvent event ) { // http://jira.qos.ch/browse/LBCLASSIC-213 Map < String , String > mdcMap = event . getMDCPropertyMap ( ) ; if ( mdcMap == null ) { return defaultValue ; } String mdcValue = mdcMap . get ( key ) ; if ( mdcValue == null ) { return defaultValue ; } else { return mdcValue ; } }


Input: update the mask so as to execute change detection code about once every 100 to 8000 milliseconds . [CODESPLIT] private void updateMaskIfNecessary ( long now ) { final long timeElapsedSinceLastMaskUpdateCheck = now - lastMaskCheck ; lastMaskCheck = now ; if ( timeElapsedSinceLastMaskUpdateCheck < MASK_INCREASE_THRESHOLD && ( mask < MAX_MASK ) ) { mask = ( mask << 1 ) | 1 ; } else if ( timeElapsedSinceLastMaskUpdateCheck > MASK_DECREASE_THRESHOLD ) { mask = mask >>> 2 ; } }


Input: Loop through the filters in the list . As soon as a filter decides on ACCEPT or DENY then that value is returned . If all of the filters return NEUTRAL then NEUTRAL is returned . [CODESPLIT] public FilterReply getFilterChainDecision ( E event ) { final Filter < E > [ ] filterArrray = filterList . asTypedArray ( ) ; final int len = filterArrray . length ; for ( int i = 0 ; i < len ; i ++ ) { final FilterReply r = filterArrray [ i ] . decide ( event ) ; if ( r == FilterReply . DENY || r == FilterReply . ACCEPT ) { return r ; } } // no decision return FilterReply . NEUTRAL ; }


Input: { [CODESPLIT] public void run ( ) { addInfo ( clientId + "connected" ) ; ObjectOutputStream oos = null ; try { int counter = 0 ; oos = createObjectOutputStream ( ) ; while ( ! Thread . currentThread ( ) . isInterrupted ( ) ) { try { Serializable event = queue . take ( ) ; oos . writeObject ( event ) ; oos . flush ( ) ; if ( ++ counter >= CoreConstants . OOS_RESET_FREQUENCY ) { // failing to reset the stream periodically will result in a // serious memory leak (as noted in AbstractSocketAppender) counter = 0 ; oos . reset ( ) ; } } catch ( InterruptedException ex ) { Thread . currentThread ( ) . interrupt ( ) ; } } } catch ( SocketException ex ) { addInfo ( clientId + ex ) ; } catch ( IOException ex ) { addError ( clientId + ex ) ; } catch ( RuntimeException ex ) { addError ( clientId + ex ) ; } finally { if ( oos != null ) { CloseUtil . closeQuietly ( oos ) ; } close ( ) ; addInfo ( clientId + "connection closed" ) ; } }


Input: Creates a new { [CODESPLIT] public SecureRandom createSecureRandom ( ) throws NoSuchProviderException , NoSuchAlgorithmException { try { return getProvider ( ) != null ? SecureRandom . getInstance ( getAlgorithm ( ) , getProvider ( ) ) : SecureRandom . getInstance ( getAlgorithm ( ) ) ; } catch ( NoSuchProviderException ex ) { throw new NoSuchProviderException ( "no such secure random provider: " + getProvider ( ) ) ; } catch ( NoSuchAlgorithmException ex ) { throw new NoSuchAlgorithmException ( "no such secure random algorithm: " + getAlgorithm ( ) ) ; } }


Input: Instantiates an layout of the given class and sets its name . [CODESPLIT] public void begin ( InterpretationContext ec , String localName , Attributes attributes ) { // Let us forget about previous errors (in this object) inError = false ; String errorMsg ; String pattern = attributes . getValue ( Action . PATTERN_ATTRIBUTE ) ; String actionClass = attributes . getValue ( Action . ACTION_CLASS_ATTRIBUTE ) ; if ( OptionHelper . isEmpty ( pattern ) ) { inError = true ; errorMsg = "No 'pattern' attribute in <newRule>" ; addError ( errorMsg ) ; return ; } if ( OptionHelper . isEmpty ( actionClass ) ) { inError = true ; errorMsg = "No 'actionClass' attribute in <newRule>" ; addError ( errorMsg ) ; return ; } try { addInfo ( "About to add new Joran parsing rule [" + pattern + "," + actionClass + "]." ) ; ec . getJoranInterpreter ( ) . getRuleStore ( ) . addRule ( new ElementSelector ( pattern ) , actionClass ) ; } catch ( Exception oops ) { inError = true ; errorMsg = "Could not add new Joran parsing rule [" + pattern + "," + actionClass + "]" ; addError ( errorMsg ) ; } }


Input: Creates a new { [CODESPLIT] public SSLContext createContext ( ContextAware context ) throws NoSuchProviderException , NoSuchAlgorithmException , KeyManagementException , UnrecoverableKeyException , KeyStoreException , CertificateException { SSLContext sslContext = getProvider ( ) != null ? SSLContext . getInstance ( getProtocol ( ) , getProvider ( ) ) : SSLContext . getInstance ( getProtocol ( ) ) ; context . addInfo ( "SSL protocol '" + sslContext . getProtocol ( ) + "' provider '" + sslContext . getProvider ( ) + "'" ) ; KeyManager [ ] keyManagers = createKeyManagers ( context ) ; TrustManager [ ] trustManagers = createTrustManagers ( context ) ; SecureRandom secureRandom = createSecureRandom ( context ) ; sslContext . init ( keyManagers , trustManagers , secureRandom ) ; return sslContext ; }


Input: Creates key managers using the receiver s key store configuration . [CODESPLIT] private KeyManager [ ] createKeyManagers ( ContextAware context ) throws NoSuchProviderException , NoSuchAlgorithmException , UnrecoverableKeyException , KeyStoreException { if ( getKeyStore ( ) == null ) return null ; KeyStore keyStore = getKeyStore ( ) . createKeyStore ( ) ; context . addInfo ( "key store of type '" + keyStore . getType ( ) + "' provider '" + keyStore . getProvider ( ) + "': " + getKeyStore ( ) . getLocation ( ) ) ; KeyManagerFactory kmf = getKeyManagerFactory ( ) . createKeyManagerFactory ( ) ; context . addInfo ( "key manager algorithm '" + kmf . getAlgorithm ( ) + "' provider '" + kmf . getProvider ( ) + "'" ) ; char [ ] passphrase = getKeyStore ( ) . getPassword ( ) . toCharArray ( ) ; kmf . init ( keyStore , passphrase ) ; return kmf . getKeyManagers ( ) ; }


Input: Creates trust managers using the receiver s trust store configuration . [CODESPLIT] private TrustManager [ ] createTrustManagers ( ContextAware context ) throws NoSuchProviderException , NoSuchAlgorithmException , KeyStoreException { if ( getTrustStore ( ) == null ) return null ; KeyStore trustStore = getTrustStore ( ) . createKeyStore ( ) ; context . addInfo ( "trust store of type '" + trustStore . getType ( ) + "' provider '" + trustStore . getProvider ( ) + "': " + getTrustStore ( ) . getLocation ( ) ) ; TrustManagerFactory tmf = getTrustManagerFactory ( ) . createTrustManagerFactory ( ) ; context . addInfo ( "trust manager algorithm '" + tmf . getAlgorithm ( ) + "' provider '" + tmf . getProvider ( ) + "'" ) ; tmf . init ( trustStore ) ; return tmf . getTrustManagers ( ) ; }


Input: Constructs a key store factory bean using JSSE system properties . [CODESPLIT] private KeyStoreFactoryBean keyStoreFromSystemProperties ( String property ) { if ( System . getProperty ( property ) == null ) return null ; KeyStoreFactoryBean keyStore = new KeyStoreFactoryBean ( ) ; keyStore . setLocation ( locationFromSystemProperty ( property ) ) ; keyStore . setProvider ( System . getProperty ( property + "Provider" ) ) ; keyStore . setPassword ( System . getProperty ( property + "Password" ) ) ; keyStore . setType ( System . getProperty ( property + "Type" ) ) ; return keyStore ; }


Input: Constructs a resource location from a JSSE system property . [CODESPLIT] private String locationFromSystemProperty ( String name ) { String location = System . getProperty ( name ) ; if ( location != null && ! location . startsWith ( "file:" ) ) { location = "file:" + location ; } return location ; }


Input: Converts a string describing the location of a resource into a URL object . [CODESPLIT] public static URL urlForResource ( String location ) throws MalformedURLException , FileNotFoundException { if ( location == null ) { throw new NullPointerException ( "location is required" ) ; } URL url = null ; if ( ! location . matches ( SCHEME_PATTERN ) ) { url = Loader . getResourceBySelfClassLoader ( location ) ; } else if ( location . startsWith ( CLASSPATH_SCHEME ) ) { String path = location . substring ( CLASSPATH_SCHEME . length ( ) ) ; if ( path . startsWith ( "/" ) ) { path = path . substring ( 1 ) ; } if ( path . length ( ) == 0 ) { throw new MalformedURLException ( "path is required" ) ; } url = Loader . getResourceBySelfClassLoader ( path ) ; } else { url = new URL ( location ) ; } if ( url == null ) { throw new FileNotFoundException ( location ) ; } return url ; }


Input: Instantiates an layout of the given class and sets its name . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public void begin ( InterpretationContext ec , String localName , Attributes attributes ) { // Let us forget about previous errors (in this object) inError = false ; String errorMsg ; String conversionWord = attributes . getValue ( ActionConst . CONVERSION_WORD_ATTRIBUTE ) ; String converterClass = attributes . getValue ( ActionConst . CONVERTER_CLASS_ATTRIBUTE ) ; if ( OptionHelper . isEmpty ( conversionWord ) ) { inError = true ; errorMsg = "No 'conversionWord' attribute in <conversionRule>" ; addError ( errorMsg ) ; return ; } if ( OptionHelper . isEmpty ( converterClass ) ) { inError = true ; errorMsg = "No 'converterClass' attribute in <conversionRule>" ; ec . addError ( errorMsg ) ; return ; } try { Map < String , String > ruleRegistry = ( Map < String , String > ) context . getObject ( CoreConstants . PATTERN_RULE_REGISTRY ) ; if ( ruleRegistry == null ) { ruleRegistry = new HashMap < String , String > ( ) ; context . putObject ( CoreConstants . PATTERN_RULE_REGISTRY , ruleRegistry ) ; } // put the new rule into the rule registry addInfo ( "registering conversion word " + conversionWord + " with class [" + converterClass + "]" ) ; ruleRegistry . put ( conversionWord , converterClass ) ; } catch ( Exception oops ) { inError = true ; errorMsg = "Could not add conversion rule to PatternLayout." ; addError ( errorMsg ) ; } }


Input: This implementation checks if any of the converters in the chain handles exceptions . If not then this method adds a { @link ThrowableProxyConverter } instance to the end of the chain . <p > This allows appenders using this layout to output exception information event if the user forgets to add %ex to the pattern . Note that the appenders defined in the Core package are not aware of exceptions nor LoggingEvents . <p > If for some reason the user wishes to NOT print exceptions then she can add %nopex to the pattern . [CODESPLIT] public void process ( Context context , Converter < ILoggingEvent > head ) { if ( head == null ) { // this should never happen throw new IllegalArgumentException ( "cannot process empty chain" ) ; } if ( ! chainHandlesThrowable ( head ) ) { Converter < ILoggingEvent > tail = ConverterUtil . findTail ( head ) ; Converter < ILoggingEvent > exConverter = null ; LoggerContext loggerContext = ( LoggerContext ) context ; if ( loggerContext . isPackagingDataEnabled ( ) ) { exConverter = new ExtendedThrowableProxyConverter ( ) ; } else { exConverter = new ThrowableProxyConverter ( ) ; } tail . setNext ( exConverter ) ; } }


Input: This method computes whether a chain of converters handles exceptions or not . [CODESPLIT] public boolean chainHandlesThrowable ( Converter < ILoggingEvent > head ) { Converter < ILoggingEvent > c = head ; while ( c != null ) { if ( c instanceof ThrowableHandlingConverter ) { return true ; } c = c . getNext ( ) ; } return false ; }


Input: Default method for stopping the Logback context [CODESPLIT] protected void stop ( ) { addInfo ( "Logback context being closed via shutdown hook" ) ; Context hookContext = getContext ( ) ; if ( hookContext instanceof ContextBase ) { ContextBase context = ( ContextBase ) hookContext ; context . stop ( ) ; } }


Input: Print the contents of the context status but only if they contain warnings or errors occurring later then the threshold . [CODESPLIT] public static void printInCaseOfErrorsOrWarnings ( Context context , long threshold ) { if ( context == null ) { throw new IllegalArgumentException ( "Context argument cannot be null" ) ; } StatusManager sm = context . getStatusManager ( ) ; if ( sm == null ) { ps . println ( "WARN: Context named \"" + context . getName ( ) + "\" has no status manager" ) ; } else { StatusUtil statusUtil = new StatusUtil ( context ) ; if ( statusUtil . getHighestLevel ( threshold ) >= ErrorStatus . WARN ) { print ( sm , threshold ) ; } } }


Input: Print the contents of the context statuses but only if they contain errors . [CODESPLIT] public static void printIfErrorsOccured ( Context context ) { if ( context == null ) { throw new IllegalArgumentException ( "Context argument cannot be null" ) ; } StatusManager sm = context . getStatusManager ( ) ; if ( sm == null ) { ps . println ( "WARN: Context named \"" + context . getName ( ) + "\" has no status manager" ) ; } else { StatusUtil statusUtil = new StatusUtil ( context ) ; if ( statusUtil . getHighestLevel ( 0 ) == ErrorStatus . ERROR ) { print ( sm ) ; } } }


Input: Print context s status data with a timestamp higher than the threshold . [CODESPLIT] public static void print ( Context context , long threshold ) { if ( context == null ) { throw new IllegalArgumentException ( "Context argument cannot be null" ) ; } StatusManager sm = context . getStatusManager ( ) ; if ( sm == null ) { ps . println ( "WARN: Context named \"" + context . getName ( ) + "\" has no status manager" ) ; } else { print ( sm , threshold ) ; } }


Input: } [CODESPLIT] private static void appendThrowable ( StringBuilder sb , Throwable t ) { String [ ] stringRep = ThrowableToStringArray . convert ( t ) ; for ( String s : stringRep ) { if ( s . startsWith ( CoreConstants . CAUSED_BY ) ) { // nothing } else if ( Character . isDigit ( s . charAt ( 0 ) ) ) { // if line resembles "48 common frames omitted" sb . append ( "\t... " ) ; } else { // most of the time. just add a tab+"at" sb . append ( "\tat " ) ; } sb . append ( s ) . append ( CoreConstants . LINE_SEPARATOR ) ; } }


Input: { [CODESPLIT] public void start ( ) { if ( isStarted ( ) ) return ; int errorCount = 0 ; if ( port <= 0 ) { errorCount ++ ; addError ( "No port was configured for appender" + name + " For more information, please visit http://logback.qos.ch/codes.html#socket_no_port" ) ; } if ( remoteHost == null ) { errorCount ++ ; addError ( "No remote host was configured for appender" + name + " For more information, please visit http://logback.qos.ch/codes.html#socket_no_host" ) ; } if ( queueSize == 0 ) { addWarn ( "Queue size of zero is deprecated, use a size of one to indicate synchronous processing" ) ; } if ( queueSize < 0 ) { errorCount ++ ; addError ( "Queue size must be greater than zero" ) ; } if ( errorCount == 0 ) { try { address = InetAddress . getByName ( remoteHost ) ; } catch ( UnknownHostException ex ) { addError ( "unknown host: " + remoteHost ) ; errorCount ++ ; } } if ( errorCount == 0 ) { deque = queueFactory . newLinkedBlockingDeque ( queueSize ) ; peerId = "remote peer " + remoteHost + ":" + port + ": " ; connector = createConnector ( address , port , 0 , reconnectionDelay . getMilliseconds ( ) ) ; task = getContext ( ) . getScheduledExecutorService ( ) . submit ( new Runnable ( ) { public void run ( ) { connectSocketAndDispatchEvents ( ) ; } } ) ; super . start ( ) ; } }


Input: { [CODESPLIT] @ Override public void stop ( ) { if ( ! isStarted ( ) ) return ; CloseUtil . closeQuietly ( socket ) ; task . cancel ( true ) ; super . stop ( ) ; }


Input: { [CODESPLIT] @ Override protected void append ( E event ) { if ( event == null || ! isStarted ( ) ) return ; try { final boolean inserted = deque . offer ( event , eventDelayLimit . getMilliseconds ( ) , TimeUnit . MILLISECONDS ) ; if ( ! inserted ) { addInfo ( "Dropping event due to timeout limit of [" + eventDelayLimit + "] being exceeded" ) ; } } catch ( InterruptedException e ) { addError ( "Interrupted while appending event to SocketAppender" , e ) ; } }


Input: { [CODESPLIT] public void connectionFailed ( SocketConnector connector , Exception ex ) { if ( ex instanceof InterruptedException ) { addInfo ( "connector interrupted" ) ; } else if ( ex instanceof ConnectException ) { addInfo ( peerId + "connection refused" ) ; } else { addInfo ( peerId + ex ) ; } }


Input: Convert a level to equivalent syslog severity . Only levels for printing methods i . e DEBUG WARN INFO and ERROR are converted . [CODESPLIT] @ Override public int getSeverityForEvent ( Object eventObject ) { ILoggingEvent event = ( ILoggingEvent ) eventObject ; return LevelToSyslogSeverity . convert ( event ) ; }


Input: LOGBACK - 411 and LOGBACK - 750 [CODESPLIT] private void handleThrowableFirstLine ( OutputStream sw , IThrowableProxy tp , String stackTracePrefix , boolean isRootException ) throws IOException { StringBuilder sb = new StringBuilder ( ) . append ( stackTracePrefix ) ; if ( ! isRootException ) { sb . append ( CoreConstants . CAUSED_BY ) ; } sb . append ( tp . getClassName ( ) ) . append ( ": " ) . append ( tp . getMessage ( ) ) ; sw . write ( sb . toString ( ) . getBytes ( ) ) ; sw . flush ( ) ; }


Input: Get an entry from the liveMap if not found search the lingerersMap . [CODESPLIT] private Entry < C > getFromEitherMap ( String key ) { Entry < C > entry = liveMap . get ( key ) ; if ( entry != null ) return entry ; else { return lingerersMap . get ( key ) ; } }


Input: { @inheritDoc } [CODESPLIT] public synchronized C find ( String key ) { Entry < C > entry = getFromEitherMap ( key ) ; if ( entry == null ) return null ; else return entry . component ; }


Input: { @inheritDoc } [CODESPLIT] public synchronized C getOrCreate ( String key , long timestamp ) { Entry < C > entry = getFromEitherMap ( key ) ; if ( entry == null ) { C c = buildComponent ( key ) ; entry = new Entry < C > ( key , c , timestamp ) ; // new entries go into the main map liveMap . put ( key , entry ) ; } else { entry . setTimestamp ( timestamp ) ; } return entry . component ; }


Input: Mark component identified by key as having reached its end - of - life . [CODESPLIT] public void endOfLife ( String key ) { Entry < C > entry = liveMap . remove ( key ) ; if ( entry == null ) return ; lingerersMap . put ( key , entry ) ; }


Input: This method is used to parse a string such as 5 . 7 5 . 7 or - 5 . 7 into a FormatInfo . [CODESPLIT] public static FormatInfo valueOf ( String str ) throws IllegalArgumentException { if ( str == null ) { throw new NullPointerException ( "Argument cannot be null" ) ; } FormatInfo fi = new FormatInfo ( ) ; int indexOfDot = str . indexOf ( ' ' ) ; String minPart = null ; String maxPart = null ; if ( indexOfDot != - 1 ) { minPart = str . substring ( 0 , indexOfDot ) ; if ( indexOfDot + 1 == str . length ( ) ) { throw new IllegalArgumentException ( "Formatting string [" + str + "] should not end with '.'" ) ; } else { maxPart = str . substring ( indexOfDot + 1 ) ; } } else { minPart = str ; } if ( minPart != null && minPart . length ( ) > 0 ) { int min = Integer . parseInt ( minPart ) ; if ( min >= 0 ) { fi . min = min ; } else { fi . min = - min ; fi . leftPad = false ; } } if ( maxPart != null && maxPart . length ( ) > 0 ) { int max = Integer . parseInt ( maxPart ) ; if ( max >= 0 ) { fi . max = max ; } else { fi . max = - max ; fi . leftTruncate = false ; } } return fi ; }


Input: A relatively robust file renaming method which in case of failure due to src and target being on different volumes falls back onto renaming by copying . [CODESPLIT] public void rename ( String src , String target ) throws RolloverFailure { if ( src . equals ( target ) ) { addWarn ( "Source and target files are the same [" + src + "]. Skipping." ) ; return ; } File srcFile = new File ( src ) ; if ( srcFile . exists ( ) ) { File targetFile = new File ( target ) ; createMissingTargetDirsIfNecessary ( targetFile ) ; addInfo ( "Renaming file [" + srcFile + "] to [" + targetFile + "]" ) ; boolean result = srcFile . renameTo ( targetFile ) ; if ( ! result ) { addWarn ( "Failed to rename file [" + srcFile + "] as [" + targetFile + "]." ) ; Boolean areOnDifferentVolumes = areOnDifferentVolumes ( srcFile , targetFile ) ; if ( Boolean . TRUE . equals ( areOnDifferentVolumes ) ) { addWarn ( "Detected different file systems for source [" + src + "] and target [" + target + "]. Attempting rename by copying." ) ; renameByCopying ( src , target ) ; return ; } else { addWarn ( "Please consider leaving the [file] option of " + RollingFileAppender . class . getSimpleName ( ) + " empty." ) ; addWarn ( "See also " + RENAMING_ERROR_URL ) ; } } } else { throw new RolloverFailure ( "File [" + src + "] does not exist." ) ; } }


Input: Attempts tp determine whether both files are on different volumes . Returns true if we could determine that the files are on different volumes . Returns false otherwise or if an error occurred while doing the check . [CODESPLIT] Boolean areOnDifferentVolumes ( File srcFile , File targetFile ) throws RolloverFailure { if ( ! EnvUtil . isJDK7OrHigher ( ) ) { return false ; } // target file is not certain to exist but its parent has to exist given the call hierarchy of this method File parentOfTarget = targetFile . getAbsoluteFile ( ) . getParentFile ( ) ; if ( parentOfTarget == null ) { addWarn ( "Parent of target file [" + targetFile + "] is null" ) ; return null ; } if ( ! parentOfTarget . exists ( ) ) { addWarn ( "Parent of target file [" + targetFile + "] does not exist" ) ; return null ; } try { boolean onSameFileStore = FileStoreUtil . areOnSameFileStore ( srcFile , parentOfTarget ) ; return ! onSameFileStore ; } catch ( RolloverFailure rf ) { addWarn ( "Error while checking file store equality" , rf ) ; return null ; } }


Input: See http : // logback . qos . ch / manual / configuration . html#variableSubstitution [CODESPLIT] public static String substVars ( String input , PropertyContainer pc0 , PropertyContainer pc1 ) { try { return NodeToStringTransformer . substituteVariable ( input , pc0 , pc1 ) ; } catch ( ScanException e ) { throw new IllegalArgumentException ( "Failed to parse input [" + input + "]" , e ) ; } }


Input: Very similar to <code > System . getProperty< / code > except that the { @link SecurityException } is absorbed . [CODESPLIT] public static String getSystemProperty ( String key , String def ) { try { return System . getProperty ( key , def ) ; } catch ( SecurityException e ) { return def ; } }


Input: Lookup a key from the environment . [CODESPLIT] public static String getEnv ( String key ) { try { return System . getenv ( key ) ; } catch ( SecurityException e ) { return null ; } }


Input: Gets an Android system property [CODESPLIT] public static String getAndroidSystemProperty ( String key ) { try { return SystemPropertiesProxy . getInstance ( ) . get ( key , null ) ; } catch ( IllegalArgumentException e ) { return null ; } }


Input: Very similar to <code > System . getProperty< / code > except that the { @link SecurityException } is absorbed . Also checks Android system properties as a fallback . [CODESPLIT] public static String getSystemProperty ( String key ) { try { String prop = System . getProperty ( key ) ; return ( prop == null ) ? getAndroidSystemProperty ( key ) : prop ; } catch ( SecurityException e ) { return null ; } }


Input: Return a String [] of size two . The first item containing the key part and the second item containing a default value specified by the user . The second item will be null if no default value is specified . [CODESPLIT] static public String [ ] extractDefaultReplacement ( String key ) { String [ ] result = new String [ 2 ] ; if ( key == null ) return result ; result [ 0 ] = key ; int d = key . indexOf ( DELIM_DEFAULT ) ; if ( d != - 1 ) { result [ 0 ] = key . substring ( 0 , d ) ; result [ 1 ] = key . substring ( d + DELIM_DEFAULT_LEN ) ; } return result ; }


Input: If <code > value< / code > is true then <code > true< / code > is returned . If <code > value< / code > is false then <code > true< / code > is returned . Otherwise <code > default< / code > is returned . <p > Case of value is unimportant . [CODESPLIT] public static boolean toBoolean ( String value , boolean defaultValue ) { if ( value == null ) { return defaultValue ; } String trimmedVal = value . trim ( ) ; if ( "true" . equalsIgnoreCase ( trimmedVal ) ) { return true ; } if ( "false" . equalsIgnoreCase ( trimmedVal ) ) { return false ; } return defaultValue ; }


Input: This method clears all internal properties except internal status messages closes all appenders removes any turboFilters fires an OnReset event removes all status listeners removes all context listeners ( except those which are reset resistant ) . <p > As mentioned above internal status messages survive resets . [CODESPLIT] @ Override public void reset ( ) { resetCount ++ ; super . reset ( ) ; initEvaluatorMap ( ) ; initCollisionMaps ( ) ; root . recursiveReset ( ) ; resetTurboFilterList ( ) ; cancelScheduledTasks ( ) ; fireOnReset ( ) ; resetListenersExceptResetResistant ( ) ; resetStatusListeners ( ) ; }


Input: Get the caller information for this logging event . If caller information is null at the time of its invocation this method extracts location information . The collected information is cached for future use . <p > Note that after serialization it is impossible to correctly extract caller information . < / p > [CODESPLIT] public StackTraceElement [ ] getCallerData ( ) { if ( callerDataArray == null ) { callerDataArray = CallerData . extract ( new Throwable ( ) , fqnOfLoggerClass , loggerContext . getMaxCallerDataDepth ( ) , loggerContext . getFrameworkPackages ( ) ) ; } return callerDataArray ; }


Input: Set the MDC map for this event . [CODESPLIT] public void setMDCPropertyMap ( Map < String , String > map ) { if ( mdcPropertyMap != null ) { throw new IllegalStateException ( "The MDCPropertyMap has been already set for this event." ) ; } this . mdcPropertyMap = map ; }


Input: if no key is specified return all the values present in the MDC in the format k1 = v1 k2 = v2 ... [CODESPLIT] private String outputMDCForAllKeys ( Map < String , String > mdcPropertyMap ) { StringBuilder buf = new StringBuilder ( ) ; boolean first = true ; for ( Map . Entry < String , String > entry : mdcPropertyMap . entrySet ( ) ) { if ( first ) { first = false ; } else { buf . append ( ", " ) ; } //format: key0=value0, key1=value1 buf . append ( entry . getKey ( ) ) . append ( ' ' ) . append ( entry . getValue ( ) ) ; } return buf . toString ( ) ; }


Input: Returns true if the file specified by { @link #setPath ( String ) path } property exists . Returns false otherwise . [CODESPLIT] public String getPropertyValue ( ) { if ( OptionHelper . isEmpty ( path ) ) { addError ( "The \"path\" property must be set." ) ; return null ; } File file = new File ( path ) ; return booleanAsStr ( file . exists ( ) ) ; }


Input: { [CODESPLIT] @ Override protected boolean configureClient ( RemoteReceiverClient client ) { client . setContext ( getContext ( ) ) ; client . setQueue ( new ArrayBlockingQueue < Serializable > ( clientQueueSize ) ) ; return true ; }


Input: Extract caller data information as an array based on a Throwable passed as parameter [CODESPLIT] public static StackTraceElement [ ] extract ( Throwable t , String fqnOfInvokingClass , final int maxDepth , List < String > frameworkPackageList ) { if ( t == null ) { return null ; } StackTraceElement [ ] steArray = t . getStackTrace ( ) ; StackTraceElement [ ] callerDataArray ; int found = LINE_NA ; for ( int i = 0 ; i < steArray . length ; i ++ ) { if ( isInFrameworkSpace ( steArray [ i ] . getClassName ( ) , fqnOfInvokingClass , frameworkPackageList ) ) { // the caller is assumed to be the next stack frame, hence the +1. found = i + 1 ; } else { if ( found != LINE_NA ) { break ; } } } // we failed to extract caller data if ( found == LINE_NA ) { return EMPTY_CALLER_DATA_ARRAY ; } int availableDepth = steArray . length - found ; int desiredDepth = maxDepth < ( availableDepth ) ? maxDepth : availableDepth ; callerDataArray = new StackTraceElement [ desiredDepth ] ; for ( int i = 0 ; i < desiredDepth ; i ++ ) { callerDataArray [ i ] = steArray [ found + i ] ; } return callerDataArray ; }


Input: Is currentClass present in the list of packages considered part of the logging framework? [CODESPLIT] private static boolean isInFrameworkSpaceList ( String currentClass , List < String > frameworkPackageList ) { if ( frameworkPackageList == null ) return false ; for ( String s : frameworkPackageList ) { if ( currentClass . startsWith ( s ) ) return true ; } return false ; }


Input: Add a new status object . [CODESPLIT] public void add ( Status newStatus ) { // LBCORE-72: fire event before the count check fireStatusAddEvent ( newStatus ) ; count ++ ; if ( newStatus . getLevel ( ) > level ) { level = newStatus . getLevel ( ) ; } synchronized ( statusListLock ) { if ( statusList . size ( ) < MAX_HEADER_COUNT ) { statusList . add ( newStatus ) ; } else { tailBuffer . add ( newStatus ) ; } } }


Input: This implementation does not allow duplicate installations of OnConsoleStatusListener [CODESPLIT] public boolean add ( StatusListener listener ) { synchronized ( statusListenerListLock ) { if ( listener instanceof OnConsoleStatusListener ) { boolean alreadyPresent = checkForPresence ( statusListenerList , listener . getClass ( ) ) ; if ( alreadyPresent ) { return false ; } } statusListenerList . add ( listener ) ; } return true ; }


Input: Check if any implicit actions are applicable . As soon as an applicable action is found it is returned . Thus the returned list will have at most one element . [CODESPLIT] List < Action > lookupImplicitAction ( ElementPath elementPath , Attributes attributes , InterpretationContext ec ) { int len = implicitActions . size ( ) ; for ( int i = 0 ; i < len ; i ++ ) { ImplicitAction ia = ( ImplicitAction ) implicitActions . get ( i ) ; if ( ia . isApplicable ( elementPath , attributes , ec ) ) { List < Action > actionList = new ArrayList < Action > ( 1 ) ; actionList . add ( ia ) ; return actionList ; } } return null ; }


Input: Return the list of applicable patterns for this [CODESPLIT] List < Action > getApplicableActionList ( ElementPath elementPath , Attributes attributes ) { List < Action > applicableActionList = ruleStore . matchActions ( elementPath ) ; // logger.debug("set of applicable patterns: " + applicableActionList); if ( applicableActionList == null ) { applicableActionList = lookupImplicitAction ( elementPath , attributes , interpretationContext ) ; } return applicableActionList ; }


Input: Sets the classloader to lookup the class for android . os . SystemProperties [CODESPLIT] public void setClassLoader ( ClassLoader cl ) throws ClassNotFoundException , SecurityException , NoSuchMethodException { if ( cl == null ) cl = this . getClass ( ) . getClassLoader ( ) ; SystemProperties = cl . loadClass ( "android.os.SystemProperties" ) ; getString = SystemProperties . getMethod ( "get" , new Class [ ] { String . class , String . class } ) ; getBoolean = SystemProperties . getMethod ( "getBoolean" , new Class [ ] { String . class , boolean . class } ) ; }


Input: Get the value for the given key in the Android system properties [CODESPLIT] public String get ( String key , String def ) throws IllegalArgumentException { if ( SystemProperties == null || getString == null ) return null ; String ret = null ; try { ret = ( String ) getString . invoke ( SystemProperties , new Object [ ] { key , def } ) ; } catch ( IllegalArgumentException e ) { throw e ; } catch ( Exception e ) { } // if return value is null or empty, use the default // since neither of those are valid values if ( ret == null || ret . length ( ) == 0 ) { ret = def ; } return ret ; }


Input: Get the value for the given key in the Android system properties returned as a boolean . [CODESPLIT] public Boolean getBoolean ( String key , boolean def ) throws IllegalArgumentException { if ( SystemProperties == null || getBoolean == null ) return def ; Boolean ret = def ; try { ret = ( Boolean ) getBoolean . invoke ( SystemProperties , new Object [ ] { key , def } ) ; } catch ( IllegalArgumentException e ) { throw e ; } catch ( Exception e ) { } return ret ; }


Input: Converts a name string s first letter to lowercase [CODESPLIT] static public String decapitalize ( String name ) { if ( name == null || name . length ( ) == 0 ) { return name ; } else { String nm = name . substring ( 0 , 1 ) . toLowerCase ( Locale . US ) ; if ( name . length ( ) > 1 ) { nm += name . substring ( 1 ) ; } return nm ; } }


Input: Gets a class s method descriptors [CODESPLIT] static public MethodDescriptor [ ] getMethodDescriptors ( Class < ? > clazz ) { ArrayList < MethodDescriptor > methods = new ArrayList < MethodDescriptor > ( ) ; for ( Method m : clazz . getMethods ( ) ) { methods . add ( new MethodDescriptor ( m . getName ( ) , m ) ) ; } return methods . toArray ( new MethodDescriptor [ 0 ] ) ; }


Input: Gets a class s property descriptors . All properties have methods whose name begins with set or get . The setters must have a single parameter and getters must have none . [CODESPLIT] static public PropertyDescriptor [ ] getPropertyDescriptors ( Class < ? > clazz ) { final String SETTER_PREFIX = "set" ; final String GETTER_PREFIX = "get" ; final int LEN_PREFIX = SETTER_PREFIX . length ( ) ; Map < String , PropertyDescriptor > map = new HashMap < String , PropertyDescriptor > ( ) ; for ( Method m : clazz . getMethods ( ) ) { PropertyDescriptor pd = null ; String mName = m . getName ( ) ; boolean isGet = mName . startsWith ( GETTER_PREFIX ) && ( mName . length ( ) > LEN_PREFIX ) ; boolean isSet = mName . startsWith ( SETTER_PREFIX ) && ( mName . length ( ) > LEN_PREFIX ) ; if ( isGet || isSet ) { String propName = decapitalize ( mName . substring ( LEN_PREFIX ) ) ; pd = map . get ( propName ) ; if ( pd == null ) { pd = new PropertyDescriptor ( propName ) ; map . put ( propName , pd ) ; } Class < ? > [ ] parmTypes = m . getParameterTypes ( ) ; if ( isSet ) { if ( parmTypes . length == 1 ) { // we only want the single-parm setter pd . setWriteMethod ( m ) ; pd . setPropertyType ( parmTypes [ 0 ] ) ; } } else if ( isGet ) { if ( parmTypes . length == 0 ) { // we only want the zero-parm getter pd . setReadMethod ( m ) ; // let setter's type take priority if ( pd . getPropertyType ( ) == null ) { pd . setPropertyType ( m . getReturnType ( ) ) ; } } } } } return map . values ( ) . toArray ( new PropertyDescriptor [ 0 ] ) ; }


Input: { [CODESPLIT] protected boolean shouldStart ( ) { int errorCount = 0 ; if ( port == 0 ) { errorCount ++ ; addError ( "No port was configured for receiver. " + "For more information, please visit http://logback.qos.ch/codes.html#receiver_no_port" ) ; } if ( remoteHost == null ) { errorCount ++ ; addError ( "No host name or address was configured for receiver. " + "For more information, please visit http://logback.qos.ch/codes.html#receiver_no_host" ) ; } if ( reconnectionDelay == 0 ) { reconnectionDelay = AbstractSocketAppender . DEFAULT_RECONNECTION_DELAY ; } if ( errorCount == 0 ) { try { address = InetAddress . getByName ( remoteHost ) ; } catch ( UnknownHostException ex ) { addError ( "unknown host: " + remoteHost ) ; errorCount ++ ; } } if ( errorCount == 0 ) { receiverId = "receiver " + remoteHost + ":" + port + ": " ; } return errorCount == 0 ; }


Input: { [CODESPLIT] public void run ( ) { try { LoggerContext lc = ( LoggerContext ) getContext ( ) ; while ( ! Thread . currentThread ( ) . isInterrupted ( ) ) { SocketConnector connector = createConnector ( address , port , 0 , reconnectionDelay ) ; connectorTask = activateConnector ( connector ) ; if ( connectorTask == null ) { break ; } socket = waitForConnectorToReturnASocket ( ) ; if ( socket == null ) break ; dispatchEvents ( lc ) ; } } catch ( InterruptedException ex ) { assert true ; // ok... we'll exit now } addInfo ( "shutting down" ) ; }


Input: { [CODESPLIT] public void connectionFailed ( SocketConnector connector , Exception ex ) { if ( ex instanceof InterruptedException ) { addWarn ( "connector interrupted" , ex ) ; } else if ( ex instanceof ConnectException ) { addWarn ( receiverId + "connection refused" , ex ) ; } else { addWarn ( receiverId + "unspecified error" , ex ) ; } }


Input: Sets the value of the <b > Target< / b > option . Recognized values are System . out and System . err . Any other value will be ignored . [CODESPLIT] public void setTarget ( String value ) { @ SuppressWarnings ( "deprecation" ) ConsoleTarget t = ConsoleTarget . findByName ( value . trim ( ) ) ; if ( t == null ) { targetWarn ( value ) ; } else { target = t ; } }


Input: Checks that requires parameters are set and if everything is in order activates this appender . [CODESPLIT] public void start ( ) { int errors = 0 ; if ( this . encoder == null ) { addStatus ( new ErrorStatus ( "No encoder set for the appender named \"" + name + "\"." , this ) ) ; errors ++ ; } if ( this . outputStream == null ) { addStatus ( new ErrorStatus ( "No output stream set for the appender named \"" + name + "\"." , this ) ) ; errors ++ ; } // only error free appenders should be activated if ( errors == 0 ) { super . start ( ) ; } }


Input: Close the underlying { [CODESPLIT] protected void closeOutputStream ( ) { if ( this . outputStream != null ) { try { // before closing we have to output out layout's footer encoderClose ( ) ; this . outputStream . close ( ) ; this . outputStream = null ; } catch ( IOException e ) { addStatus ( new ErrorStatus ( "Could not close output stream for OutputStreamAppender." , this , e ) ) ; } } }


Input: <p > Sets the @link OutputStream } where the log output will go . The specified <code > OutputStream< / code > must be opened by the user and be writable . The <code > OutputStream< / code > will be closed when the appender instance is closed . [CODESPLIT] public void setOutputStream ( OutputStream outputStream ) { lock . lock ( ) ; try { // close any previously opened output stream closeOutputStream ( ) ; this . outputStream = outputStream ; if ( encoder == null ) { addWarn ( "Encoder has not been set. Cannot invoke its init method." ) ; return ; } encoderInit ( ) ; } finally { lock . unlock ( ) ; } }


Input: Actual writing occurs here . <p > Most subclasses of <code > WriterAppender< / code > will need to override this method . [CODESPLIT] protected void subAppend ( E event ) { if ( ! isStarted ( ) ) { return ; } try { // this step avoids LBCLASSIC-139 if ( event instanceof DeferredProcessingAware ) { ( ( DeferredProcessingAware ) event ) . prepareForDeferredProcessing ( ) ; } // the synchronization prevents the OutputStream from being closed while we // are writing. It also prevents multiple threads from entering the same // converter. Converters assume that they are in a synchronized block. //lock.lock(); byte [ ] byteArray = this . encoder . encode ( event ) ; writeBytes ( byteArray ) ; } catch ( IOException ioe ) { // as soon as an exception occurs, move to non-started state // and add a single ErrorStatus to the SM. this . started = false ; addStatus ( new ErrorStatus ( "IO failure in appender" , this , ioe ) ) ; } }


Input: Resets this manager . <p > All registered components are stopped and removed from the manager . [CODESPLIT] public void reset ( ) { for ( LifeCycle component : components ) { if ( component . isStarted ( ) ) { component . stop ( ) ; } } components . clear ( ) ; }


Input: This utility method adds a new OnConsoleStatusListener to the context passed as parameter . [CODESPLIT] static public void addOnConsoleListenerInstance ( Context context , OnConsoleStatusListener onConsoleStatusListener ) { onConsoleStatusListener . setContext ( context ) ; boolean effectivelyAdded = context . getStatusManager ( ) . add ( onConsoleStatusListener ) ; if ( effectivelyAdded ) { onConsoleStatusListener . start ( ) ; } }


Input: Now property definer is initialized by all properties and we can put property value to context [CODESPLIT] public void end ( InterpretationContext ec , String name ) { if ( inError ) { return ; } Object o = ec . peekObject ( ) ; if ( o != definer ) { addWarn ( "The object at the of the stack is not the property definer for property named [" + propertyName + "] pushed earlier." ) ; } else { addInfo ( "Popping property definer for property named [" + propertyName + "] from the object stack" ) ; ec . popObject ( ) ; // let's put defined property and value to context but only if it is // not null String propertyValue = definer . getPropertyValue ( ) ; if ( propertyValue != null ) { ActionUtil . setProperty ( ec , propertyName , propertyValue , scope ) ; } } }


Input: Return the name of the current context name as found in the logging event . [CODESPLIT] public String getDiscriminatingValue ( ILoggingEvent event ) { String contextName = event . getLoggerContextVO ( ) . getName ( ) ; if ( contextName == null ) { return defaultValue ; } else { return contextName ; } }


Input: Do not perform any character escaping . <p > Note that this method assumes that it is called after the escape character has been consumed . [CODESPLIT] public void escape ( String escapeChars , StringBuffer buf , char next , int pointer ) { // restitute the escape char (because it was consumed // before this method was called). buf . append ( "\\" ) ; // restitute the next character buf . append ( next ) ; }


Input: Events of level TRACE DEBUG and INFO are deemed to be discardable . [CODESPLIT] protected boolean isDiscardable ( ILoggingEvent event ) { Level level = event . getLevel ( ) ; return level . toInt ( ) <= Level . INFO_INT ; }


Input: Instantiates a shutdown hook of the given class and sets its name . [CODESPLIT] @ Override public void begin ( InterpretationContext ic , String name , Attributes attributes ) throws ActionException { hook = null ; inError = false ; String className = attributes . getValue ( CLASS_ATTRIBUTE ) ; if ( OptionHelper . isEmpty ( className ) ) { className = DefaultShutdownHook . class . getName ( ) ; addInfo ( "Assuming className [" + className + "]" ) ; } try { addInfo ( "About to instantiate shutdown hook of type [" + className + "]" ) ; hook = ( ShutdownHookBase ) OptionHelper . instantiateByClassName ( className , ShutdownHookBase . class , context ) ; hook . setContext ( context ) ; ic . pushObject ( hook ) ; } catch ( Exception e ) { inError = true ; addError ( "Could not create a shutdown hook of type [" + className + "]." , e ) ; throw new ActionException ( e ) ; } }


Input: Once the children elements are also parsed now is the time to activate the shutdown hook options . [CODESPLIT] @ Override public void end ( InterpretationContext ic , String name ) throws ActionException { if ( inError ) { return ; } Object o = ic . peekObject ( ) ; if ( o != hook ) { addWarn ( "The object at the of the stack is not the hook pushed earlier." ) ; } else { ic . popObject ( ) ; Thread hookThread = new Thread ( hook , "Logback shutdown hook [" + context . getName ( ) + "]" ) ; addInfo ( "Registering shutdown hook with JVM runtime" ) ; context . putObject ( CoreConstants . SHUTDOWN_HOOK_THREAD , hookThread ) ; Runtime . getRuntime ( ) . addShutdownHook ( hookThread ) ; } }


Input: Creates a { [CODESPLIT] public KeyManagerFactory createKeyManagerFactory ( ) throws NoSuchProviderException , NoSuchAlgorithmException { return getProvider ( ) != null ? KeyManagerFactory . getInstance ( getAlgorithm ( ) , getProvider ( ) ) : KeyManagerFactory . getInstance ( getAlgorithm ( ) ) ; }


Input: Closes a closeable while suppressing any { [CODESPLIT] public static void closeQuietly ( Closeable closeable ) { if ( closeable == null ) return ; try { closeable . close ( ) ; } catch ( IOException ex ) { assert true ; // avoid an empty catch } }


Input: Closes a socket while suppressing any { [CODESPLIT] public static void closeQuietly ( Socket socket ) { if ( socket == null ) return ; try { socket . close ( ) ; } catch ( IOException ex ) { assert true ; // avoid an empty catch } }


Input: Closes a server socket while suppressing any { [CODESPLIT] public static void closeQuietly ( ServerSocket serverSocket ) { if ( serverSocket == null ) return ; try { serverSocket . close ( ) ; } catch ( IOException ex ) { assert true ; // avoid an empty catch } }


Input: Configures SSL parameters on an { [CODESPLIT] public void configure ( SSLConfigurable socket ) { socket . setEnabledProtocols ( enabledProtocols ( socket . getSupportedProtocols ( ) , socket . getDefaultProtocols ( ) ) ) ; socket . setEnabledCipherSuites ( enabledCipherSuites ( socket . getSupportedCipherSuites ( ) , socket . getDefaultCipherSuites ( ) ) ) ; if ( isNeedClientAuth ( ) != null ) { socket . setNeedClientAuth ( isNeedClientAuth ( ) ) ; } if ( isWantClientAuth ( ) != null ) { socket . setWantClientAuth ( isWantClientAuth ( ) ) ; } }


Input: Gets the set of enabled protocols based on the configuration . [CODESPLIT] private String [ ] enabledProtocols ( String [ ] supportedProtocols , String [ ] defaultProtocols ) { if ( enabledProtocols == null ) { // we're assuming that the same engine is used for all configurables // so once we determine the enabled set, we won't do it again if ( OptionHelper . isEmpty ( getIncludedProtocols ( ) ) && OptionHelper . isEmpty ( getExcludedProtocols ( ) ) ) { enabledProtocols = Arrays . copyOf ( defaultProtocols , defaultProtocols . length ) ; } else { enabledProtocols = includedStrings ( supportedProtocols , getIncludedProtocols ( ) , getExcludedProtocols ( ) ) ; } for ( String protocol : enabledProtocols ) { addInfo ( "enabled protocol: " + protocol ) ; } } return enabledProtocols ; }


Input: Gets the set of enabled cipher suites based on the configuration . [CODESPLIT] private String [ ] enabledCipherSuites ( String [ ] supportedCipherSuites , String [ ] defaultCipherSuites ) { if ( enabledCipherSuites == null ) { // we're assuming that the same engine is used for all configurables // so once we determine the enabled set, we won't do it again if ( OptionHelper . isEmpty ( getIncludedCipherSuites ( ) ) && OptionHelper . isEmpty ( getExcludedCipherSuites ( ) ) ) { enabledCipherSuites = Arrays . copyOf ( defaultCipherSuites , defaultCipherSuites . length ) ; } else { enabledCipherSuites = includedStrings ( supportedCipherSuites , getIncludedCipherSuites ( ) , getExcludedCipherSuites ( ) ) ; } for ( String cipherSuite : enabledCipherSuites ) { addInfo ( "enabled cipher suite: " + cipherSuite ) ; } } return enabledCipherSuites ; }


Input: Applies include and exclude patterns to an array of default string values to produce an array of strings included by the patterns . [CODESPLIT] private String [ ] includedStrings ( String [ ] defaults , String included , String excluded ) { List < String > values = new ArrayList < String > ( defaults . length ) ; values . addAll ( Arrays . asList ( defaults ) ) ; if ( included != null ) { StringCollectionUtil . retainMatching ( values , stringToArray ( included ) ) ; } if ( excluded != null ) { StringCollectionUtil . removeMatching ( values , stringToArray ( excluded ) ) ; } return values . toArray ( new String [ values . size ( ) ] ) ; }


Input: Creates a new { @link LinkedBlockingDeque } with the given { @code capacity } . In case the given capacity is smaller than one it will automatically be converted to one . [CODESPLIT] public < E > LinkedBlockingDeque < E > newLinkedBlockingDeque ( int capacity ) { final int actualCapacity = capacity < 1 ? 1 : capacity ; return new LinkedBlockingDeque < E > ( actualCapacity ) ; }


Input: Convert a string into a scope . Scope . LOCAL is returned by default . [CODESPLIT] static public Scope stringToScope ( String scopeStr ) { if ( Scope . SYSTEM . toString ( ) . equalsIgnoreCase ( scopeStr ) ) return Scope . SYSTEM ; if ( Scope . CONTEXT . toString ( ) . equalsIgnoreCase ( scopeStr ) ) return Scope . CONTEXT ; return Scope . LOCAL ; }


Input: Add all the properties found in the argument named props to an InterpretationContext . [CODESPLIT] static public void setProperties ( InterpretationContext ic , Properties props , Scope scope ) { switch ( scope ) { case LOCAL : ic . addSubstitutionProperties ( props ) ; break ; case CONTEXT : ContextUtil cu = new ContextUtil ( ic . getContext ( ) ) ; cu . addProperties ( props ) ; break ; case SYSTEM : OptionHelper . setSystemProperties ( ic , props ) ; } }


Input: Attach an appender . If the appender is already in the list in won t be added again . [CODESPLIT] public void addAppender ( Appender < E > newAppender ) { if ( newAppender == null ) { throw new IllegalArgumentException ( "Null argument disallowed" ) ; } appenderList . addIfAbsent ( newAppender ) ; }


Input: Call the <code > doAppend< / code > method on all attached appenders . [CODESPLIT] public int appendLoopOnAppenders ( E e ) { int size = 0 ; final Appender < E > [ ] appenderArray = appenderList . asTypedArray ( ) ; final int len = appenderArray . length ; for ( int i = 0 ; i < len ; i ++ ) { appenderArray [ i ] . doAppend ( e ) ; size ++ ; } return size ; }


Input: Returns <code > true< / code > if the specified appender is in the list of attached appenders <code > false< / code > otherwise . [CODESPLIT] public boolean isAttached ( Appender < E > appender ) { if ( appender == null ) { return false ; } for ( Appender < E > a : appenderList ) { if ( a == appender ) return true ; } return false ; }


Input: Remove the appender passed as parameter form the list of attached appenders . [CODESPLIT] public boolean detachAppender ( Appender < E > appender ) { if ( appender == null ) { return false ; } boolean result ; result = appenderList . remove ( appender ) ; return result ; }


Input: Remove the appender with the name passed as parameter form the list of appenders . [CODESPLIT] public boolean detachAppender ( String name ) { if ( name == null ) { return false ; } boolean removed = false ; for ( Appender < E > a : appenderList ) { if ( name . equals ( ( a ) . getName ( ) ) ) { removed = appenderList . remove ( a ) ; break ; } } return removed ; }


Input: This method is invoked by parent logger to let this logger know that the prent s levelInt changed . [CODESPLIT] private synchronized void handleParentLevelChange ( int newParentLevelInt ) { // changes in the parent levelInt affect children only if their levelInt is // null if ( level == null ) { effectiveLevelInt = newParentLevelInt ; // propagate the parent levelInt change to this logger's children if ( childrenList != null ) { int len = childrenList . size ( ) ; for ( int i = 0 ; i < len ; i ++ ) { Logger child = ( Logger ) childrenList . get ( i ) ; child . handleParentLevelChange ( newParentLevelInt ) ; } } } }


Input: details . [CODESPLIT] public synchronized void addAppender ( Appender < ILoggingEvent > newAppender ) { if ( aai == null ) { aai = new AppenderAttachableImpl < ILoggingEvent > ( ) ; } aai . addAppender ( newAppender ) ; }


Input: Invoke all the appenders of this logger . [CODESPLIT] public void callAppenders ( ILoggingEvent event ) { int writes = 0 ; for ( Logger l = this ; l != null ; l = l . parent ) { writes += l . appendLoopOnAppenders ( event ) ; if ( ! l . additive ) { break ; } } // No appenders in hierarchy if ( writes == 0 ) { loggerContext . noAppenderDefinedWarning ( this ) ; } }


Input: Remove the appender passed as parameter form the list of appenders . [CODESPLIT] public boolean detachAppender ( Appender < ILoggingEvent > appender ) { if ( aai == null ) { return false ; } return aai . detachAppender ( appender ) ; }


Input: Create a child of this logger by suffix that is the part of the name extending this logger . For example if this logger is named x . y and the lastPart is z then the created child logger will be named x . y . z . [CODESPLIT] Logger createChildByLastNamePart ( final String lastPart ) { int i_index = LoggerNameUtil . getFirstSeparatorIndexOf ( lastPart ) ; if ( i_index != - 1 ) { throw new IllegalArgumentException ( "Child name [" + lastPart + " passed as parameter, may not include [" + CoreConstants . DOT + "]" ) ; } if ( childrenList == null ) { childrenList = new CopyOnWriteArrayList < Logger > ( ) ; } Logger childLogger ; if ( this . isRootLogger ( ) ) { childLogger = new Logger ( lastPart , this , this . loggerContext ) ; } else { childLogger = new Logger ( name + CoreConstants . DOT + lastPart , this , this . loggerContext ) ; } childrenList . add ( childLogger ) ; childLogger . effectiveLevelInt = this . effectiveLevelInt ; return childLogger ; }


Input: The next methods are not merged into one because of the time we gain by not creating a new Object [] with the params . This reduces the cost of not logging by about 20 nanoseconds . [CODESPLIT] private void filterAndLog_0_Or3Plus ( final String localFQCN , final Marker marker , final Level level , final String msg , final Object [ ] params , final Throwable t ) { final FilterReply decision = loggerContext . getTurboFilterChainDecision_0_3OrMore ( marker , this , level , msg , params , t ) ; if ( decision == FilterReply . NEUTRAL ) { if ( effectiveLevelInt > level . levelInt ) { return ; } } else if ( decision == FilterReply . DENY ) { return ; } buildLoggingEventAndAppend ( localFQCN , marker , level , msg , params , t ) ; }


Input: Method that calls the attached TurboFilter objects based on the logger and the level . [CODESPLIT] private FilterReply callTurboFilters ( Marker marker , Level level ) { return loggerContext . getTurboFilterChainDecision_0_3OrMore ( marker , this , level , null , null , null ) ; }


Input: Support SLF4J interception during initialization as introduced in SLF4J version 1 . 7 . 15 [CODESPLIT] public void log ( org . slf4j . event . LoggingEvent slf4jEvent ) { Level level = Level . fromLocationAwareLoggerInteger ( slf4jEvent . getLevel ( ) . toInt ( ) ) ; filterAndLog_0_Or3Plus ( FQCN , slf4jEvent . getMarker ( ) , level , slf4jEvent . getMessage ( ) , slf4jEvent . getArgumentArray ( ) , slf4jEvent . getThrowable ( ) ) ; }


Input: Loops until the desired connection is established and returns the resulting connector . [CODESPLIT] public Socket call ( ) throws InterruptedException { useDefaultsForMissingFields ( ) ; Socket socket = createSocket ( ) ; while ( socket == null && ! Thread . currentThread ( ) . isInterrupted ( ) ) { Thread . sleep ( delayStrategy . nextDelay ( ) ) ; socket = createSocket ( ) ; } return socket ; }


Input: Creates the parent directories of a file . If parent directories not specified in file s path then nothing is done and this returns gracefully . [CODESPLIT] static public boolean createMissingParentDirectories ( File file ) { File parent = file . getParentFile ( ) ; if ( parent == null ) { // Parent directory not specified, therefore it's a request to // create nothing. Done! ;) return true ; } // File.mkdirs() creates the parent directories only if they don't // already exist; and it's okay if they do. parent . mkdirs ( ) ; return parent . exists ( ) ; }


Input: Prepends a string to a path if the path is relative . If the path is already absolute the same path is returned ( nothing changed ) . This is useful for converting relative paths to absolute ones given the absolute directory path as a prefix . [CODESPLIT] public static String prefixRelativePath ( String prefix , String path ) { if ( prefix != null && ! OptionHelper . isEmpty ( prefix . trim ( ) ) && ! new File ( path ) . isAbsolute ( ) ) { path = prefix + "/" + path ; } return path ; }


Input: Convert a Level to an Integer object . [CODESPLIT] public Integer toInteger ( ) { switch ( levelInt ) { case ALL_INT : return ALL_INTEGER ; case TRACE_INT : return TRACE_INTEGER ; case DEBUG_INT : return DEBUG_INTEGER ; case INFO_INT : return INFO_INTEGER ; case WARN_INT : return WARN_INTEGER ; case ERROR_INT : return ERROR_INTEGER ; case OFF_INT : return OFF_INTEGER ; default : throw new IllegalStateException ( "Level " + levelStr + ", " + levelInt + " is unknown." ) ; } }


Input: Convert an integer passed as argument to a Level . If the conversion fails then this method returns the specified default . [CODESPLIT] public static Level toLevel ( int val , Level defaultLevel ) { switch ( val ) { case ALL_INT : return ALL ; case TRACE_INT : return TRACE ; case DEBUG_INT : return DEBUG ; case INFO_INT : return INFO ; case WARN_INT : return WARN ; case ERROR_INT : return ERROR ; case OFF_INT : return OFF ; default : return defaultLevel ; } }