idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
40,100 | public static Locale getLocale ( ) { String tag = Configuration . get ( "locale" ) ; if ( tag == null ) { return Locale . ROOT ; } else { String [ ] splittedTag = tag . split ( "_" , MAX_LOCALE_ARGUMENTS ) ; if ( splittedTag . length == 1 ) { return new Locale ( splittedTag [ 0 ] ) ; } else if ( splittedTag . length == 2 ) { return new Locale ( splittedTag [ 0 ] , splittedTag [ 1 ] ) ; } else { return new Locale ( splittedTag [ 0 ] , splittedTag [ 1 ] , splittedTag [ 2 ] ) ; } } } | Loads the locale from configuration . |
40,101 | public static Map < String , Level > getCustomLevels ( ) { Map < String , Level > levels = new HashMap < String , Level > ( ) ; for ( Entry < String , String > entry : Configuration . getSiblings ( "level@" ) . entrySet ( ) ) { String packageOrClass = entry . getKey ( ) . substring ( "level@" . length ( ) ) ; Level level = parse ( entry . getValue ( ) , null ) ; if ( level != null ) { levels . put ( packageOrClass , level ) ; } } return levels ; } | Loads custom severity levels for packages or classes from configuration . |
40,102 | public static List < String > getTags ( ) { List < String > tags = new ArrayList < String > ( ) ; for ( String writerProperty : Configuration . getSiblings ( "writer" ) . keySet ( ) ) { String tag = Configuration . get ( writerProperty + ".tag" ) ; if ( tag != null && ! tag . isEmpty ( ) && ! tag . equals ( "-" ) && ! tags . contains ( tag ) ) { tags . add ( tag ) ; } } return tags ; } | Loads all tags from writers in configuration . |
40,103 | private static void addWriter ( final Writer writer , final Collection < Writer > [ ] [ ] matrix , final int tagIndex , final Level level ) { for ( int levelIndex = level . ordinal ( ) ; levelIndex < Level . OFF . ordinal ( ) ; ++ levelIndex ) { Collection < Writer > collection = matrix [ tagIndex ] [ levelIndex ] ; if ( collection == null ) { collection = new ArrayList < Writer > ( ) ; matrix [ tagIndex ] [ levelIndex ] = collection ; } collection . add ( writer ) ; } } | Adds a writer to a well - defined matrix . The given writer will be added only at the given tag index for severity levels equal or above the given severity level . |
40,104 | private static Level parse ( final String property , final Level defaultValue ) { if ( property == null ) { return defaultValue ; } else { try { return Level . valueOf ( property . toUpperCase ( Locale . ROOT ) ) ; } catch ( IllegalArgumentException ex ) { InternalLogger . log ( Level . ERROR , "Illegal severity level: " + property ) ; return defaultValue ; } } } | Reads a severity level from configuration . |
40,105 | private static Level calculateMinimumLevel ( final Level globalLevel , final Map < String , Level > customLevels ) { Level minimumLevel = globalLevel ; for ( Level level : customLevels . values ( ) ) { if ( level . ordinal ( ) < minimumLevel . ordinal ( ) ) { minimumLevel = level ; } } return minimumLevel ; } | Calculates the minimum severity level that can output any log entries . |
40,106 | @ SuppressWarnings ( "unchecked" ) private static Collection < LogEntryValue > [ ] [ ] calculateRequiredLogEntryValues ( final Collection < Writer > [ ] [ ] writers ) { Collection < LogEntryValue > [ ] [ ] logEntryValues = new Collection [ writers . length ] [ Level . values ( ) . length - 1 ] ; for ( int tagIndex = 0 ; tagIndex < writers . length ; ++ tagIndex ) { for ( int levelIndex = 0 ; levelIndex < Level . OFF . ordinal ( ) ; ++ levelIndex ) { Set < LogEntryValue > values = EnumSet . noneOf ( LogEntryValue . class ) ; for ( Writer writer : writers [ tagIndex ] [ levelIndex ] ) { values . addAll ( writer . getRequiredLogEntryValues ( ) ) ; } logEntryValues [ tagIndex ] [ levelIndex ] = values ; } } return logEntryValues ; } | Creates a matrix with all required log entry values for each tag and severity level . |
40,107 | private static BitSet calculateFullStackTraceRequirements ( final Collection < LogEntryValue > [ ] [ ] logEntryValues ) { BitSet result = new BitSet ( logEntryValues . length ) ; for ( int i = 0 ; i < logEntryValues . length ; ++ i ) { Collection < LogEntryValue > values = logEntryValues [ i ] [ Level . ERROR . ordinal ( ) ] ; if ( values . contains ( LogEntryValue . METHOD ) || values . contains ( LogEntryValue . FILE ) || values . contains ( LogEntryValue . LINE ) ) { result . set ( i ) ; } } return result ; } | Calculates for which tag a full stack trace element with method name file name and line number is required . |
40,108 | private static WritingThread createWritingThread ( final Collection < Writer > [ ] [ ] matrix ) { Collection < Writer > writers = getAllWriters ( matrix ) ; WritingThread thread = new WritingThread ( writers ) ; thread . start ( ) ; return thread ; } | Creates a writing thread for a matrix of writers . |
40,109 | private static Collection < Writer > getAllWriters ( final Collection < Writer > [ ] [ ] matrix ) { Collection < Writer > writers = Collections . newSetFromMap ( new IdentityHashMap < Writer , Boolean > ( ) ) ; for ( int i = 0 ; i < matrix . length ; ++ i ) { for ( int j = 0 ; j < matrix [ i ] . length ; ++ j ) { writers . addAll ( matrix [ i ] [ j ] ) ; } } return writers ; } | Collects all writer instances from a matrix of writers . |
40,110 | private int getTagIndex ( final String tag ) { if ( tag == null ) { return 0 ; } else { int index = knownTags . indexOf ( tag ) ; return index == - 1 ? knownTags . size ( ) + 1 : index + 1 ; } } | Gets the index of a tag . |
40,111 | private void output ( final LogEntry logEntry , final Iterable < Writer > writers ) { if ( writingThread == null ) { for ( Writer writer : writers ) { try { writer . write ( logEntry ) ; } catch ( Exception ex ) { InternalLogger . log ( Level . ERROR , ex , "Failed to write log entry '" + logEntry . getMessage ( ) + "'" ) ; } } } else { for ( Writer writer : writers ) { writingThread . add ( writer , logEntry ) ; } } } | Outputs a log entry to all passed writers . |
40,112 | public List < File > getAllFiles ( ) { List < File > files = new ArrayList < File > ( ) ; collectFiles ( folder , files ) ; Collections . sort ( files , LastModifiedFileComparator . INSTANCE ) ; return files ; } | Gets all files that are compatible with the dynamic path . The returned files are sorted by the last modification date . The most recently modified files are at the top the oldest at the bottom of the list . |
40,113 | private void collectFiles ( final File folder , final List < File > found ) { File [ ] files = folder . listFiles ( ) ; if ( files != null ) { for ( File file : files ) { if ( file . isDirectory ( ) ) { collectFiles ( file , found ) ; } else if ( file . isFile ( ) && file . getPath ( ) . endsWith ( suffix ) ) { int index = 0 ; for ( String text : plainTexts ) { index = file . getPath ( ) . indexOf ( text , index ) ; if ( index == - 1 ) { break ; } else { index += text . length ( ) ; } } if ( index >= 0 ) { found . add ( file ) ; } } } } } | Collects files from a folder and all nested sub folders . |
40,114 | private boolean isValid ( final String path , final int pathPosition , final int segmentIndex ) { Segment segment = segments . get ( segmentIndex ) ; String expectedValue = segment . getStaticText ( ) ; if ( expectedValue == null ) { if ( segmentIndex == segments . size ( ) - 1 ) { return segment . validateToken ( path . substring ( pathPosition ) ) ; } else { String nextValue = segments . get ( segmentIndex + 1 ) . getStaticText ( ) ; for ( int i = path . indexOf ( nextValue , pathPosition ) ; i >= 0 ; i = path . indexOf ( nextValue , i + 1 ) ) { if ( segment . validateToken ( path . substring ( pathPosition , i ) ) && isValid ( path , i , segmentIndex + 1 ) ) { return true ; } } return false ; } } else if ( path . startsWith ( expectedValue , pathPosition ) ) { if ( segmentIndex == segments . size ( ) - 1 ) { return pathPosition + expectedValue . length ( ) == path . length ( ) ; } else { return isValid ( path , pathPosition + expectedValue . length ( ) , segmentIndex + 1 ) ; } } else { return false ; } } | Checks if a partial path to a file is compatible with this dynamic path . |
40,115 | private static Segment parseSegment ( final String path , final String token ) { int separator = token . indexOf ( ':' ) ; String name ; String parameter ; if ( separator == - 1 ) { name = token . trim ( ) ; parameter = null ; } else { name = token . substring ( 0 , separator ) . trim ( ) ; parameter = token . substring ( separator + 1 ) . trim ( ) ; } if ( "date" . equals ( name ) ) { return new DateSegment ( parameter == null ? DEFAULT_DATE_FORMAT_PATTERN : parameter ) ; } else if ( "count" . equals ( name ) && parameter == null ) { return new CountSegment ( ) ; } else if ( "pid" . equals ( name ) && parameter == null ) { return new ProcessIdSegment ( ) ; } else { throw new IllegalArgumentException ( "Invalid token '" + token + "' in '" + path + "'" ) ; } } | Parses a token from a pattern as a segment . |
40,116 | public void run ( ) { Collection < Writer > writers = new ArrayList < Writer > ( 1 ) ; while ( true ) { for ( Task task : receiveTasks ( ) ) { if ( task == Task . POISON ) { close ( ) ; return ; } else { write ( writers , task ) ; } } flush ( writers ) ; writers . clear ( ) ; try { sleep ( MILLISECONDS_TO_SLEEP ) ; } catch ( InterruptedException ex ) { } } } | Fetches log entries and writes them until receiving a poison task . |
40,117 | void add ( final Writer writer , final LogEntry logEntry ) { Task task = new Task ( writer , logEntry ) ; synchronized ( mutex ) { tasks . add ( task ) ; } } | Adds a log entry for writing . |
40,118 | private List < Task > receiveTasks ( ) { synchronized ( mutex ) { if ( tasks . isEmpty ( ) ) { return Collections . emptyList ( ) ; } else { List < Task > currentTasks = tasks ; tasks = new ArrayList < Task > ( ) ; return currentTasks ; } } } | Receives all added log entries . |
40,119 | private void write ( final Collection < Writer > writers , final Task task ) { try { Writer writer = task . writer ; writer . write ( task . logEntry ) ; if ( ! writers . contains ( writer ) ) { writers . add ( writer ) ; } } catch ( Exception ex ) { InternalLogger . log ( Level . ERROR , ex , "Failed to write log entry '" + task . logEntry . getMessage ( ) + "'" ) ; } } | Writes a log entry . |
40,120 | private void flush ( final Collection < Writer > writers ) { for ( Writer writer : writers ) { try { writer . flush ( ) ; } catch ( Exception ex ) { InternalLogger . log ( Level . ERROR , ex , "Failed to flush writer" ) ; } } } | Flushes a collection of writers . |
40,121 | private void close ( ) { for ( Writer writer : writers ) { try { writer . close ( ) ; } catch ( Exception ex ) { InternalLogger . log ( Level . ERROR , ex , "Failed to close writer" ) ; } } } | Closes all writers . |
40,122 | public void output ( final Map < String , Map < String , List < BigDecimal > > > benchmarks ) { for ( Entry < String , Map < String , List < BigDecimal > > > benchmark : benchmarks . entrySet ( ) ) { BigDecimal max = benchmark . getValue ( ) . values ( ) . stream ( ) . flatMap ( list -> list . stream ( ) ) . max ( Comparator . naturalOrder ( ) ) . orElse ( BigDecimal . ONE ) ; System . out . println ( benchmark . getKey ( ) . toUpperCase ( Locale . ENGLISH ) ) ; System . out . println ( ) ; System . out . println ( "<div class=\"table-responsive\"><table class=\"table benchmark\">" ) ; System . out . println ( "\t<thead>" ) ; System . out . println ( "\t\t<tr>" ) ; System . out . println ( "\t\t\t<th>Framework</th>" ) ; System . out . println ( "\t\t\t<th>Processed Log Entries per Second</th>" ) ; System . out . println ( "\t\t</tr>" ) ; System . out . println ( "\t</thead>" ) ; System . out . println ( "\t<tbody>" ) ; for ( Entry < String , Framework > framework : frameworks . entrySet ( ) ) { List < BigDecimal > scores = benchmark . getValue ( ) . get ( framework . getKey ( ) ) ; for ( int i = 0 ; i < scores . size ( ) ; ++ i ) { BigDecimal total = scores . get ( i ) . setScale ( 0 , RoundingMode . HALF_UP ) ; BigDecimal percentage = scores . get ( i ) . multiply ( PERCENTAGE ) . divide ( max , DECIMAL_PLACES , RoundingMode . HALF_UP ) ; String label = i == 0 ? framework . getValue ( ) . getName ( ) : framework . getValue ( ) . getAsync ( ) ; System . out . println ( "\t\t" + ( i == 0 ? "<tr>" : "<tr class=\"advanced\">" ) ) ; System . out . println ( "\t\t\t<td>" + label + "</td>" ) ; System . out . println ( "\t\t\t<td>" ) ; System . out . println ( "\t\t\t\t<div class=\"bar\" style=\"width: " + percentage + "%\"> </div>" ) ; System . out . println ( "\t\t\t\t<div class=\"total\">" + NUMBER_FORMAT . format ( total ) + "</div></td>" ) ; System . out . println ( "\t\t\t</td>" ) ; System . out . println ( "\t\t</tr>" ) ; } } System . out . println ( "\t</tbody>" ) ; System . out . println ( "</table></div>" ) ; System . out . println ( ) ; } } | Creates and outputs HTML diagrams . |
40,123 | @ SuppressWarnings ( "rawtypes" ) public static Enumeration getCurrentLoggers ( ) { ArrayList < Logger > copy ; synchronized ( mutex ) { copy = new ArrayList < Logger > ( loggers . values ( ) ) ; } copy . remove ( root ) ; return Collections . enumeration ( copy ) ; } | Retrieves all existing loggers . |
40,124 | private static Logger getOrCreateLogger ( final String name ) { if ( name == null || name . length ( ) == 0 ) { return root ; } else { Logger logger = loggers . get ( name ) ; if ( logger == null ) { Logger parent = getOrCreateLogger ( reduce ( name ) ) ; logger = new Logger ( parent , name ) ; loggers . put ( name , logger ) ; } return logger ; } } | Retrieves a logger by name . |
40,125 | private static String reduce ( final String name ) { int index = name . lastIndexOf ( '.' ) ; return index == - 1 ? null : name . substring ( 0 , index ) ; } | Gets the parent s logger name for a given logger name . |
40,126 | public boolean isTraceEnabled ( ) { return MINIMUM_LEVEL_COVERS_TRACE && provider . isEnabled ( STACKTRACE_DEPTH , null , org . tinylog . Level . TRACE ) ; } | Check whether this category is enabled for the TRACE Level . |
40,127 | public T create ( final String name , final Object ... arguments ) { if ( name . indexOf ( '.' ) == - 1 ) { String expectingClassName = toSimpleClassName ( name ) ; for ( String className : classes ) { int split = className . lastIndexOf ( '.' ) ; String simpleClassName = split == - 1 ? className : className . substring ( split + 1 ) ; if ( expectingClassName . equals ( simpleClassName ) ) { return createInstance ( className , arguments ) ; } } InternalLogger . log ( Level . ERROR , "Service implementation '" + name + "' not found" ) ; return null ; } else { return createInstance ( name , arguments ) ; } } | Creates a defined service implementation . The name can be either the fully - qualified class name or the simplified acronym . The acronym is the class name without package and service suffix . |
40,128 | public Collection < T > createAll ( final Object ... arguments ) { Collection < T > instances = new ArrayList < T > ( classes . size ( ) ) ; for ( String className : classes ) { T instance = createInstance ( className , arguments ) ; if ( instance != null ) { instances . add ( instance ) ; } } return instances ; } | Creates all registered service implementations . |
40,129 | private static < T > Collection < String > loadClasses ( final ClassLoader classLoader , final Class < ? extends T > service ) { String name = SERVICE_PREFIX + service . getName ( ) ; Enumeration < URL > urls ; try { urls = classLoader . getResources ( name ) ; } catch ( IOException ex ) { InternalLogger . log ( Level . ERROR , "Failed loading services from '" + name + "'" ) ; return Collections . emptyList ( ) ; } Collection < String > classes = new ArrayList < String > ( ) ; while ( urls . hasMoreElements ( ) ) { URL url = urls . nextElement ( ) ; BufferedReader reader = null ; try { reader = new BufferedReader ( new InputStreamReader ( url . openStream ( ) , "utf-8" ) ) ; for ( String line = reader . readLine ( ) ; line != null ; line = reader . readLine ( ) ) { line = line . trim ( ) ; if ( line . length ( ) > 0 && line . charAt ( 0 ) != '#' && ! classes . contains ( line ) ) { classes . add ( line ) ; } } } catch ( IOException ex ) { InternalLogger . log ( Level . ERROR , "Failed reading service resource '" + url + "'" ) ; } finally { if ( reader != null ) { try { reader . close ( ) ; } catch ( IOException ex ) { } } } } return classes ; } | Loads all registered service class names . |
40,130 | private String toSimpleClassName ( final String name ) { StringBuilder builder = new StringBuilder ( name . length ( ) ) ; for ( String token : SPLIT_PATTERN . split ( name ) ) { if ( ! token . isEmpty ( ) ) { builder . append ( Character . toUpperCase ( token . charAt ( 0 ) ) ) ; builder . append ( token . substring ( 1 ) . toLowerCase ( Locale . ROOT ) ) ; } } builder . append ( service . getSimpleName ( ) ) ; return builder . toString ( ) ; } | Generates the simple class name from an acronym . A simple class name is the class name without package . |
40,131 | @ SuppressWarnings ( "unchecked" ) private T createInstance ( final String className , final Object ... arguments ) { try { Class < ? > implementation = Class . forName ( className , false , classLoader ) ; if ( service . isAssignableFrom ( implementation ) ) { return ( T ) implementation . getDeclaredConstructor ( argumentTypes ) . newInstance ( arguments ) ; } else { InternalLogger . log ( Level . ERROR , "Class '" + className + "' does not implement servcie interface '" + service + "'" ) ; } } catch ( ClassNotFoundException ex ) { InternalLogger . log ( Level . ERROR , "Service implementation '" + className + "' not found" ) ; } catch ( NoSuchMethodException ex ) { InternalLogger . log ( Level . ERROR , "Service implementation '" + className + "' has no matching constructor" ) ; } catch ( InstantiationException ex ) { InternalLogger . log ( Level . ERROR , "Service implementation '" + className + "' is not instantiable" ) ; } catch ( IllegalAccessException ex ) { InternalLogger . log ( Level . ERROR , "Constructor of service implementation '" + className + "' is not accessible" ) ; } catch ( IllegalArgumentException ex ) { InternalLogger . log ( Level . ERROR , "Illegal arguments for constructor of service implementation '" + className + "'" ) ; } catch ( InvocationTargetException ex ) { InternalLogger . log ( Level . ERROR , ex . getTargetException ( ) , "Failed creating service implementation '" + className + "'" ) ; } return null ; } | Creates a new instance of a class . |
40,132 | private static String getVersion ( final Class < ? > clazz ) { CodeSource source = clazz . getProtectionDomain ( ) . getCodeSource ( ) ; URL location = source . getLocation ( ) ; try { Path path = Paths . get ( location . toURI ( ) ) ; return Files . isRegularFile ( path ) ? getVersionFromJar ( path ) : getVersionFromPom ( path ) ; } catch ( URISyntaxException ex ) { Logger . error ( ex , "Unknown location: \"{}\"" , location ) ; return null ; } } | Gets the version for a class . |
40,133 | private static String getVersionFromJar ( final Path path ) { Matcher matcher = JAR_VERSION . matcher ( path . toString ( ) ) ; if ( matcher . matches ( ) ) { return matcher . group ( 1 ) ; } else { Logger . error ( "JAR file \"{}\" does not contain a version" , path ) ; return null ; } } | Gets the version for a JAR file . |
40,134 | private static String getVersionFromPom ( final Path path ) { Path folder = path ; Path file ; while ( true ) { file = folder . resolve ( "pom.xml" ) ; if ( Files . exists ( file ) ) { break ; } folder = folder . getParent ( ) ; if ( folder == null ) { Logger . error ( "pom.xml is missing for \"{}\"" , path ) ; return null ; } } String content ; try { content = new String ( Files . readAllBytes ( file ) , StandardCharsets . UTF_8 ) ; } catch ( IOException ex ) { Logger . error ( ex , "Failed reading \"{}\"" , path ) ; return null ; } Matcher matcher = POM_VERSION . matcher ( content ) ; if ( matcher . find ( ) ) { return matcher . group ( 1 ) ; } else { Logger . error ( "POM \"{}\" does not contain a version" , file ) ; return null ; } } | Gets the version for a folder by searching for a pom . xml in the folder and its folders . |
40,135 | private static StackTraceElement findStackTraceElement ( final String loggerClassName , final StackTraceElement [ ] trace ) { int index = 0 ; while ( index < trace . length && ! loggerClassName . equals ( trace [ index ] . getClassName ( ) ) ) { index = index + 1 ; } while ( index < trace . length && loggerClassName . equals ( trace [ index ] . getClassName ( ) ) ) { index = index + 1 ; } if ( index < trace . length ) { return trace [ index ] ; } else { return null ; } } | Gets the stack trace element that appears before the passed logger class name . |
40,136 | private StackTraceElement [ ] extractCallerStackTraceElements ( final int count ) { if ( stackTraceElementsFiller != null ) { try { StackTraceElement [ ] trace = new StackTraceElement [ count + 1 ] ; stackTraceElementsFiller . invoke ( null , Thread . currentThread ( ) , trace ) ; return trace ; } catch ( IllegalAccessException ex ) { InternalLogger . log ( Level . ERROR , ex , "Failed getting stack trace element from dalvik.system.VMStack" ) ; } catch ( InvocationTargetException ex ) { InternalLogger . log ( Level . ERROR , ex . getTargetException ( ) , "Failed getting stack trace element from dalvik.system.VMStack" ) ; } } return null ; } | Extracts a defined number of elements from stack trace . |
40,137 | public static TaggedLogger tag ( final String tag ) { if ( tag == null || tag . isEmpty ( ) ) { return instance ; } else { TaggedLogger logger = loggers . get ( tag ) ; if ( logger == null ) { logger = new TaggedLogger ( tag ) ; TaggedLogger existing = loggers . putIfAbsent ( tag , logger ) ; return existing == null ? logger : existing ; } else { return logger ; } } } | Gets a tagged logger instance . Tags are case - sensitive . |
40,138 | private static ProcessHandle getCurrentProcess ( ) { try { return ( ProcessHandle ) ProcessHandle . class . getDeclaredMethod ( "current" ) . invoke ( null ) ; } catch ( ReflectiveOperationException ex ) { InternalLogger . log ( Level . ERROR , ex , "Failed to receive the handle of the current process" ) ; return null ; } } | Gets the process handle of the current process . |
40,139 | private static void render ( final Throwable throwable , final StringBuilder builder ) { builder . append ( throwable . getClass ( ) . getName ( ) ) ; String message = throwable . getMessage ( ) ; if ( message != null ) { builder . append ( ": " ) ; builder . append ( message ) ; } StackTraceElement [ ] stackTrace = throwable . getStackTrace ( ) ; for ( int i = 0 ; i < stackTrace . length ; ++ i ) { builder . append ( NEW_LINE ) ; builder . append ( "\tat " ) ; builder . append ( stackTrace [ i ] ) ; } Throwable cause = throwable . getCause ( ) ; if ( cause != null ) { builder . append ( NEW_LINE ) ; builder . append ( "Caused by: " ) ; render ( cause , builder ) ; } } | Renders a throwable including stack trace and cause throwables . |
40,140 | public static void main ( final String [ ] args ) { BenchmarkOutputParser parser = new BenchmarkOutputParser ( FRAMEWORKS . keySet ( ) ) ; HtmlDiagramRenderer renderer = new HtmlDiagramRenderer ( FRAMEWORKS ) ; renderer . output ( parser . parse ( OUTPUT_FILE ) ) ; } | Main method for executing the converter . |
40,141 | protected static String getFileName ( final Map < String , String > properties ) { String fileName = properties . get ( "file" ) ; if ( fileName == null ) { throw new IllegalArgumentException ( "File name is missing for file writer" ) ; } else { return fileName ; } } | Extracts the log file name from configuration . |
40,142 | protected static Charset getCharset ( final Map < String , String > properties ) { String charsetName = properties . get ( "charset" ) ; try { return charsetName == null ? Charset . defaultCharset ( ) : Charset . forName ( charsetName ) ; } catch ( IllegalArgumentException ex ) { InternalLogger . log ( Level . ERROR , "Invalid charset: " + charsetName ) ; return Charset . defaultCharset ( ) ; } } | Extracts the charset from configuration . The default charset will be returned if no charset is defined or the defined charset doesn t exist . |
40,143 | protected final String render ( final LogEntry logEntry ) { if ( builder == null ) { StringBuilder builder = new StringBuilder ( BUILDER_CAPACITY ) ; token . render ( logEntry , builder ) ; return builder . toString ( ) ; } else { builder . setLength ( 0 ) ; token . render ( logEntry , builder ) ; return builder . toString ( ) ; } } | Renders a log entry as string . |
40,144 | private void internalWrite ( final byte [ ] data ) throws IOException { if ( ! canBeContinued ( data , policies ) ) { writer . close ( ) ; String fileName = path . resolve ( ) ; deleteBackups ( path . getAllFiles ( ) , backups ) ; writer = createByteArrayWriter ( fileName , false , buffered , false , false ) ; for ( Policy policy : policies ) { policy . reset ( ) ; } } writer . write ( data , data . length ) ; } | Outputs a passed byte array unsynchronized . |
40,145 | private static List < Policy > createPolicies ( final String property ) { if ( property == null || property . isEmpty ( ) ) { return Collections . < Policy > singletonList ( new StartupPolicy ( null ) ) ; } else { ServiceLoader < Policy > loader = new ServiceLoader < Policy > ( Policy . class , String . class ) ; List < Policy > policies = new ArrayList < Policy > ( ) ; for ( String entry : property . split ( "," ) ) { int separator = entry . indexOf ( ':' ) ; if ( separator == - 1 ) { policies . add ( loader . create ( entry , ( String ) null ) ) ; } else { String name = entry . substring ( 0 , separator ) . trim ( ) ; String argument = entry . substring ( separator + 1 ) . trim ( ) ; policies . add ( loader . create ( name , argument ) ) ; } } return policies ; } } | Creates policies from a nullable string . |
40,146 | private static boolean canBeContinued ( final String fileName , final List < Policy > policies ) { boolean result = true ; for ( Policy policy : policies ) { result &= policy . continueExistingFile ( fileName ) ; } return result ; } | Checks if an already existing log file can be continued . |
40,147 | private static boolean canBeContinued ( final byte [ ] data , final List < Policy > policies ) { boolean result = true ; for ( Policy policy : policies ) { result &= policy . continueCurrentFile ( data ) ; } return result ; } | Checks if a new log entry can be still written to the current log file . |
40,148 | private static void deleteBackups ( final List < File > files , final int count ) { if ( count >= 0 ) { for ( int i = files . size ( ) - Math . max ( 0 , files . size ( ) - count ) ; i < files . size ( ) ; ++ i ) { if ( ! files . get ( i ) . delete ( ) ) { InternalLogger . log ( Level . WARN , "Failed to delete log file '" + files . get ( i ) . getAbsolutePath ( ) + "'" ) ; } } } } | Deletes old log files . |
40,149 | private static long parse ( final String argument ) throws NumberFormatException { if ( argument . endsWith ( "gb" ) ) { return Long . parseLong ( argument . substring ( 0 , argument . length ( ) - "gb" . length ( ) ) . trim ( ) ) * GB ; } else if ( argument . endsWith ( "mb" ) ) { return Long . parseLong ( argument . substring ( 0 , argument . length ( ) - "mb" . length ( ) ) . trim ( ) ) * MB ; } else if ( argument . endsWith ( "kb" ) ) { return Long . parseLong ( argument . substring ( 0 , argument . length ( ) - "kb" . length ( ) ) . trim ( ) ) * KB ; } else if ( argument . endsWith ( "bytes" ) ) { return Long . parseLong ( argument . substring ( 0 , argument . length ( ) - "bytes" . length ( ) ) . trim ( ) ) ; } else { return Long . parseLong ( argument . trim ( ) ) ; } } | Parses file size from a string . The units GB MB KB and bytes are supported . |
40,150 | public static void push ( final String message ) { InternalLogger . log ( org . tinylog . Level . WARN , "tinylog does not support NDC, \"" + message + "\" will be discarded" ) ; } | Push new diagnostic context information for the current thread . |
40,151 | private String format ( final String pattern , final Object argument ) { try { return getFormatter ( pattern , argument ) . format ( argument ) ; } catch ( IllegalArgumentException ex ) { InternalLogger . log ( Level . WARN , "Illegal argument '" + String . valueOf ( argument ) + "' for pattern '" + pattern + "'" ) ; return String . valueOf ( argument ) ; } } | Formats a pattern of a placeholder . |
40,152 | private static String getSimpleClassName ( final String fullyQualifiedClassName ) { int dotIndex = fullyQualifiedClassName . lastIndexOf ( '.' ) ; if ( dotIndex < 0 ) { return fullyQualifiedClassName ; } else { return fullyQualifiedClassName . substring ( dotIndex + 1 ) ; } } | Gets the simple class name from a fully qualified class name . |
40,153 | private static org . tinylog . Level translateLevel ( final Level level ) { switch ( level ) { case TRACE : return org . tinylog . Level . TRACE ; case DEBUG : return org . tinylog . Level . DEBUG ; case INFO : return org . tinylog . Level . INFO ; case WARN : return org . tinylog . Level . WARN ; case ERROR : case FATAL : return org . tinylog . Level . ERROR ; default : throw new IllegalArgumentException ( "Unknown JBoss Logging severity level \"" + level + "\"" ) ; } } | Translate JBoss Logging severity levels . |
40,154 | public static Map < String , String > getSiblings ( final String prefix ) { Map < String , String > map = new HashMap < String , String > ( ) ; for ( Enumeration < Object > enumeration = properties . keys ( ) ; enumeration . hasMoreElements ( ) ; ) { String key = ( String ) enumeration . nextElement ( ) ; if ( key . startsWith ( prefix ) && ( prefix . endsWith ( "@" ) || key . indexOf ( '.' , prefix . length ( ) ) == - 1 ) ) { map . put ( key , ( String ) properties . get ( key ) ) ; } } return map ; } | Gets all siblings with a defined prefix . Child properties will be not returned . |
40,155 | public static Map < String , String > getChildren ( final String key ) { String prefix = key + "." ; Map < String , String > map = new HashMap < String , String > ( ) ; for ( Enumeration < Object > enumeration = properties . keys ( ) ; enumeration . hasMoreElements ( ) ; ) { String property = ( String ) enumeration . nextElement ( ) ; if ( property . startsWith ( prefix ) ) { map . put ( property . substring ( prefix . length ( ) ) , ( String ) properties . get ( property ) ) ; } } return map ; } | Gets all child properties for a parent property . The parent property itself will be not returned . Children keys will be returned without parent key prefix . |
40,156 | public static void replace ( final Map < String , String > configuration ) { synchronized ( properties ) { properties . clear ( ) ; properties . putAll ( configuration ) ; } } | Replaces the current configuration by a new one . Already existing properties will be dropped . |
40,157 | private static Properties load ( ) { Properties properties = new Properties ( ) ; String file = System . getProperty ( CONFIGURATION_PROPERTY ) ; try { if ( file != null ) { InputStream stream ; if ( URL_DETECTION_PATTERN . matcher ( file ) . matches ( ) ) { stream = new URL ( file ) . openStream ( ) ; } else { stream = Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( file ) ; if ( stream == null ) { stream = new FileInputStream ( file ) ; } } load ( properties , stream ) ; } else { InputStream stream = Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( DEFAULT_CONFIGURATION_FILE ) ; if ( stream != null ) { load ( properties , stream ) ; } } } catch ( IOException ex ) { InternalLogger . log ( Level . ERROR , "Failed loading configuration from '" + file + "'" ) ; } for ( Object key : new ArrayList < Object > ( System . getProperties ( ) . keySet ( ) ) ) { String name = ( String ) key ; if ( name . startsWith ( PROPERTIES_PREFIX ) ) { properties . put ( name . substring ( PROPERTIES_PREFIX . length ( ) ) , System . getProperty ( name ) ) ; } } for ( Entry < Object , Object > entry : properties . entrySet ( ) ) { String value = ( String ) entry . getValue ( ) ; if ( value . indexOf ( '{' ) != - 1 ) { value = resolve ( value , EnvironmentVariableResolver . INSTANCE ) ; value = resolve ( value , SystemPropertyResolver . INSTANCE ) ; properties . put ( entry . getKey ( ) , value ) ; } } return properties ; } | Loads all configuration properties . |
40,158 | private static void load ( final Properties properties , final InputStream stream ) throws IOException { try { properties . load ( stream ) ; } finally { stream . close ( ) ; } } | Puts all properties from a stream to an existing properties object . Already existing properties will be overridden . |
40,159 | private static String resolve ( final String value , final Resolver resolver ) { StringBuilder builder = new StringBuilder ( ) ; int position = 0 ; String prefix = resolver . getPrefix ( ) + "{" ; String postfix = "}" ; for ( int index = value . indexOf ( prefix ) ; index != - 1 ; index = value . indexOf ( prefix , position ) ) { builder . append ( value , position , index ) ; int start = index + 2 ; int end = value . indexOf ( postfix , start ) ; if ( end == - 1 ) { InternalLogger . log ( Level . WARN , "Closing curly bracket is missing for '" + value + "'" ) ; return value ; } String name = value . substring ( start , end ) ; if ( name . length ( ) == 0 ) { InternalLogger . log ( Level . WARN , "Empty variable names cannot be resolved: " + value ) ; return value ; } String data = resolver . resolve ( name ) ; if ( data == null ) { InternalLogger . log ( Level . WARN , "'" + name + "' could not be found in " + resolver . getName ( ) ) ; return value ; } else { builder . append ( data ) ; } position = end + 1 ; } builder . append ( value , position , value . length ( ) ) ; return builder . toString ( ) ; } | Resolves placeholders with passed resolver . |
40,160 | void activate ( ) { LogManager . getLogManager ( ) . reset ( ) ; Logger logger = Logger . getLogger ( "" ) ; logger . setLevel ( translateLevel ( provider . getMinimumLevel ( null ) ) ) ; logger . addHandler ( this ) ; } | Activates this handler . |
40,161 | public static void log ( final Level level , final String message ) { System . err . println ( "LOGGER " + level + ": " + message ) ; } | Logs a plain text message . |
40,162 | public static void log ( final Level level , final Throwable exception ) { String nameOfException = exception . getClass ( ) . getName ( ) ; String messageOfException = exception . getMessage ( ) ; if ( messageOfException == null || messageOfException . isEmpty ( ) ) { System . err . println ( "LOGGER " + level + ": " + nameOfException ) ; } else { System . err . println ( "LOGGER " + level + ": " + messageOfException + " (" + nameOfException + ")" ) ; } } | Logs a caught exception . |
40,163 | public static void log ( final Level level , final Throwable exception , final String message ) { String nameOfException = exception . getClass ( ) . getName ( ) ; String messageOfException = exception . getMessage ( ) ; StringBuilder builder = new StringBuilder ( BUFFER_SIZE ) ; builder . append ( level ) ; builder . append ( ": " ) ; builder . append ( message ) ; builder . append ( " (" ) ; builder . append ( nameOfException ) ; if ( messageOfException != null && ! messageOfException . isEmpty ( ) ) { builder . append ( ": " ) ; builder . append ( messageOfException ) ; } builder . append ( ")" ) ; System . err . println ( builder ) ; } | Logs a caught exception with a custom text message . |
40,164 | private void doWrite ( final LogEntry logEntry ) throws SQLException { if ( checkConnection ( ) ) { if ( batch ) { batchCount += 1 ; } try { for ( int i = 0 ; i < tokens . size ( ) ; ++ i ) { tokens . get ( i ) . apply ( logEntry , statement , i + 1 ) ; } } catch ( SQLException ex ) { resetConnection ( ) ; throw ex ; } try { if ( batch ) { statement . addBatch ( ) ; if ( batchCount >= MAX_BATCH_SIZE ) { statement . executeBatch ( ) ; batchCount = 0 ; } } else { statement . executeUpdate ( ) ; } } catch ( SQLException ex ) { resetConnection ( ) ; throw ex ; } } else { lostCount += 1 ; } } | Unsynchronized method for inserting a log entry . |
40,165 | private void doFlush ( ) throws SQLException { if ( batchCount > 0 ) { try { statement . executeBatch ( ) ; batchCount = 0 ; } catch ( SQLException ex ) { resetConnection ( ) ; throw ex ; } } } | Unsynchronized method for flushing all cached batch insert statements . |
40,166 | private void doClose ( ) throws SQLException { try { if ( batch ) { doFlush ( ) ; } } finally { if ( lostCount > 0 ) { InternalLogger . log ( Level . ERROR , "Lost log entries due to broken database connection: " + lostCount ) ; } if ( connection != null ) { connection . close ( ) ; } } } | Unsynchronized method for closing database connection . |
40,167 | private boolean checkConnection ( ) { if ( connection == null ) { if ( System . currentTimeMillis ( ) >= reconnectTimestamp ) { long start = System . currentTimeMillis ( ) ; try { connection = connect ( url , user , password ) ; statement = connection . prepareStatement ( sql ) ; InternalLogger . log ( Level . ERROR , "Lost log entries due to broken database connection: " + lostCount ) ; lostCount = 0 ; return true ; } catch ( NamingException ex ) { long now = System . currentTimeMillis ( ) ; reconnectTimestamp = now + Math . max ( MIN_RETRY_INTERVAL , ( now - start ) * 2 ) ; closeConnectionSilently ( ) ; return false ; } catch ( SQLException ex ) { long now = System . currentTimeMillis ( ) ; reconnectTimestamp = now + Math . max ( MIN_RETRY_INTERVAL , ( now - start ) * 2 ) ; closeConnectionSilently ( ) ; return false ; } } else { return false ; } } else { return true ; } } | Checks if database connection is opened . Regular attempts are made to reestablish a broken database connection . |
40,168 | private void resetConnection ( ) { if ( reconnect ) { closeConnectionSilently ( ) ; statement = null ; lostCount = batch ? batchCount : 1 ; batchCount = 0 ; reconnectTimestamp = 0 ; } } | Resets the database connection after an error if automatic reconnection is enabled . |
40,169 | private static Connection connect ( final String url , final String user , final String password ) throws NamingException , SQLException { if ( url . toLowerCase ( Locale . ROOT ) . startsWith ( "java:" ) ) { DataSource source = ( DataSource ) new InitialContext ( ) . lookup ( url ) ; if ( user == null ) { return source . getConnection ( ) ; } else { return source . getConnection ( user , password ) ; } } else { if ( user == null ) { return DriverManager . getConnection ( url ) ; } else { return DriverManager . getConnection ( url , user , password ) ; } } } | Establishes the connection to the database . |
40,170 | private static String getUrl ( final Map < String , String > properties ) { String url = properties . get ( "url" ) ; if ( url == null ) { throw new IllegalArgumentException ( "URL is missing for JDBC writer" ) ; } else { return url ; } } | Extracts the URL to database or data source from configuration . |
40,171 | private static String getTable ( final Map < String , String > properties ) { String table = properties . get ( "table" ) ; if ( table == null ) { throw new IllegalArgumentException ( "Name of database table is missing for JDBC writer" ) ; } else { return table ; } } | Extracts the database table name from configuration . |
40,172 | private static String renderSql ( final Map < String , String > properties , final String quote ) throws SQLException { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "INSERT INTO " ) ; append ( builder , getTable ( properties ) , quote ) ; builder . append ( " (" ) ; int count = 0 ; for ( Entry < String , String > entry : properties . entrySet ( ) ) { String key = entry . getKey ( ) ; if ( key . toLowerCase ( Locale . ROOT ) . startsWith ( FIELD_PREFIX ) ) { String column = key . substring ( FIELD_PREFIX . length ( ) ) ; if ( count ++ != 0 ) { builder . append ( ", " ) ; } append ( builder , column , quote ) ; } } builder . append ( ") VALUES (" ) ; for ( int i = 0 ; i < count ; ++ i ) { if ( i > 0 ) { builder . append ( ", ?" ) ; } else { builder . append ( "?" ) ; } } builder . append ( ")" ) ; return builder . toString ( ) ; } | Generates an insert SQL statement for the configured table and its fields . |
40,173 | private static void append ( final StringBuilder builder , final String identifier , final String quote ) throws SQLException { if ( identifier . indexOf ( '\n' ) >= 0 || identifier . indexOf ( '\r' ) >= 0 ) { throw new SQLException ( "Identifier contains line breaks: " + identifier ) ; } else if ( " " . equals ( quote ) ) { for ( int i = 0 ; i < identifier . length ( ) ; ++ i ) { char c = identifier . charAt ( i ) ; if ( ! Character . isLetterOrDigit ( c ) && c != '_' && c != '@' && c != '$' && c != '#' ) { throw new SQLException ( "Illegal identifier: " + identifier ) ; } } builder . append ( identifier ) ; } else { builder . append ( quote ) . append ( identifier . replace ( quote , quote + quote ) ) . append ( quote ) ; } } | Appends a database identifier securely to a builder that is building a SQL statement . |
40,174 | private static List < Token > createTokens ( final Map < String , String > properties ) { List < Token > tokens = new ArrayList < Token > ( ) ; for ( Entry < String , String > entry : properties . entrySet ( ) ) { if ( entry . getKey ( ) . toLowerCase ( Locale . ROOT ) . startsWith ( FIELD_PREFIX ) ) { tokens . add ( FormatPatternParser . parse ( entry . getValue ( ) ) ) ; } } return tokens ; } | Creates tokens for all configured fields . |
40,175 | protected static boolean isCoveredByMinimumLevel ( final org . tinylog . Level level ) { return provider . getMinimumLevel ( null ) . ordinal ( ) <= level . ordinal ( ) ; } | Checks if a given severity level is covered by the logging provider s minimum level . |
40,176 | private static org . tinylog . Level translatePriority ( final Priority priority ) { if ( priority . isGreaterOrEqual ( Level . ERROR ) ) { return org . tinylog . Level . ERROR ; } else if ( priority . isGreaterOrEqual ( Level . WARN ) ) { return org . tinylog . Level . WARN ; } else if ( priority . isGreaterOrEqual ( Level . INFO ) ) { return org . tinylog . Level . INFO ; } else if ( priority . isGreaterOrEqual ( Level . DEBUG ) ) { return org . tinylog . Level . DEBUG ; } else { return org . tinylog . Level . TRACE ; } } | Translates an Apache Log4j 1 . 2 priority into a tinylog 2 severity level . |
40,177 | private static Level translateLevel ( final org . tinylog . Level level ) { switch ( level ) { case TRACE : return Level . TRACE ; case DEBUG : return Level . DEBUG ; case INFO : return Level . INFO ; case WARN : return Level . WARN ; case ERROR : return Level . ERROR ; case OFF : return Level . OFF ; default : throw new IllegalArgumentException ( "Unknown tinylog 2 severity level \"" + level + "\"" ) ; } } | Translates a tinylog 2 severity level into an Apache Log4j 1 . 2 level . |
40,178 | private static ContextProvider createContextProvider ( final Collection < LoggingProvider > loggingProviders ) { Collection < ContextProvider > contextProviders = new ArrayList < ContextProvider > ( loggingProviders . size ( ) ) ; for ( LoggingProvider loggingProvider : loggingProviders ) { contextProviders . add ( loggingProvider . getContextProvider ( ) ) ; } return new BundleContextProvider ( contextProviders ) ; } | Gets all context providers from given logging providers and combine them into a new one . |
40,179 | public static Token parse ( final String pattern ) { List < Token > tokens = new ArrayList < Token > ( ) ; int start = 0 ; int count = 0 ; for ( int i = 0 ; i < pattern . length ( ) ; ++ i ) { char character = pattern . charAt ( i ) ; if ( character == '{' ) { if ( count == 0 ) { if ( start < i ) { tokens . add ( new PlainTextToken ( pattern . substring ( start , i ) ) ) ; } start = i ; } count += 1 ; } else if ( character == '}' ) { if ( count == 0 ) { InternalLogger . log ( Level . ERROR , "Opening curly bracket is missing: '" + pattern + "'" ) ; } else { count -= 1 ; if ( count == 0 ) { tokens . add ( parse ( pattern . substring ( start + 1 , i ) ) ) ; start = i + 1 ; } } } } if ( count > 0 ) { InternalLogger . log ( Level . ERROR , "Closing curly bracket is missing: '" + pattern + "'" ) ; } int splitIndex = pattern . indexOf ( '|' , start ) ; if ( splitIndex == - 1 ) { tokens . add ( createPlainToken ( pattern . substring ( start ) ) ) ; return tokens . size ( ) == 1 ? tokens . get ( 0 ) : new BundleToken ( tokens ) ; } else { String token = pattern . substring ( start , splitIndex ) . trim ( ) ; tokens . add ( createPlainToken ( token ) ) ; String [ ] styleOptions = SPLIT_PATTERN . split ( pattern . substring ( splitIndex + 1 ) ) ; return styleToken ( tokens . size ( ) == 1 ? tokens . get ( 0 ) : new BundleToken ( tokens ) , styleOptions ) ; } } | Parses a format pattern and produces a generic token from it . This token can be used by writers for rendering log entries . |
40,180 | private static Token createPlainToken ( final String placeholder ) { int splitIndex = placeholder . indexOf ( ':' ) ; Token token ; if ( splitIndex == - 1 ) { token = createPlainToken ( placeholder . trim ( ) , null ) ; } else { String name = placeholder . substring ( 0 , splitIndex ) . trim ( ) ; String configuration = placeholder . substring ( splitIndex + 1 ) . trim ( ) ; token = createPlainToken ( name , configuration ) ; } return token == null ? new PlainTextToken ( placeholder ) : token ; } | Creates a new token for a given placeholder . |
40,181 | private static Token createPlainToken ( final String name , final String configuration ) { if ( name . equals ( "date" ) ) { return createDateToken ( configuration ) ; } else if ( "pid" . equals ( name ) ) { return new ProcessIdToken ( ) ; } else if ( "thread" . equals ( name ) ) { return new ThreadNameToken ( ) ; } else if ( "thread-id" . equals ( name ) ) { return new ThreadIdToken ( ) ; } else if ( "context" . equals ( name ) ) { return createThreadContextToken ( configuration ) ; } else if ( "class" . equals ( name ) ) { return new FullClassNameToken ( ) ; } else if ( "class-name" . equals ( name ) ) { return new SimpleClassNameToken ( ) ; } else if ( "package" . equals ( name ) ) { return new PackageNameToken ( ) ; } else if ( "method" . equals ( name ) ) { return new MethodNameToken ( ) ; } else if ( "file" . equals ( name ) ) { return new FileNameToken ( ) ; } else if ( "line" . equals ( name ) ) { return new LineNumberToken ( ) ; } else if ( "tag" . equals ( name ) ) { return configuration == null ? new LoggerTagToken ( ) : new LoggerTagToken ( configuration ) ; } else if ( "level" . equals ( name ) ) { return new SeverityLevelToken ( ) ; } else if ( "message" . equals ( name ) ) { return new MessageAndExceptionToken ( ) ; } else if ( "message-only" . equals ( name ) ) { return new MessageToken ( ) ; } else if ( "exception" . equals ( name ) ) { return new ExceptionToken ( ) ; } else if ( "opening-curly-bracket" . equals ( name ) ) { return new PlainTextToken ( "{" ) ; } else if ( "closing-curly-bracket" . equals ( name ) ) { return new PlainTextToken ( "}" ) ; } else if ( "pipe" . equals ( name ) ) { return new PlainTextToken ( "|" ) ; } else { return null ; } } | Creates a new token for a name and configuration . |
40,182 | private static Token styleToken ( final Token token , final String [ ] options ) { Token styledToken = token ; for ( String option : options ) { int splitIndex = option . indexOf ( '=' ) ; if ( splitIndex == - 1 ) { InternalLogger . log ( Level . ERROR , "No value set for '" + option . trim ( ) + "'" ) ; } else { String key = option . substring ( 0 , splitIndex ) . trim ( ) ; String value = option . substring ( splitIndex + 1 ) . trim ( ) ; int number ; try { number = parsePositiveInteger ( value ) ; } catch ( NumberFormatException ex ) { InternalLogger . log ( Level . ERROR , "'" + value + "' is an invalid value for '" + key + "'" ) ; continue ; } if ( "min-size" . equals ( key ) ) { styledToken = new MinimumSizeToken ( styledToken , number ) ; } else if ( "indent" . equals ( key ) ) { styledToken = new IndentationToken ( styledToken , number ) ; } else { InternalLogger . log ( Level . ERROR , "Unknown style option: '" + key + "'" ) ; } } } return styledToken ; } | Creates style decorators for a token . |
40,183 | private static LoggingProvider loadLoggingProvider ( ) { ServiceLoader < LoggingProvider > loader = new ServiceLoader < LoggingProvider > ( LoggingProvider . class ) ; String name = Configuration . get ( PROVIDER_PROPERTY ) ; if ( name == null ) { Collection < LoggingProvider > providers = loader . createAll ( ) ; switch ( providers . size ( ) ) { case 0 : InternalLogger . log ( Level . WARN , "No logging framework implementation found in classpath." + " Add tinylog-impl.jar for outputting log entries." ) ; return new NopLoggingProvider ( ) ; case 1 : return providers . iterator ( ) . next ( ) ; default : return new BundleLoggingProvider ( providers ) ; } } else if ( NOP_PROVIDER_NAME . equalsIgnoreCase ( name ) ) { return new NopLoggingProvider ( ) ; } else { LoggingProvider provider = loader . create ( name ) ; if ( provider == null ) { InternalLogger . log ( Level . ERROR , "Requested logging provider is not available. Logging will be disabled." ) ; return new NopLoggingProvider ( ) ; } else { return provider ; } } } | Loads the actual logging provider . |
40,184 | @ BenchmarkMode ( Mode . Throughput ) public StackFrame stackWalkerWithLambda ( ) { return StackWalker . getInstance ( ) . walk ( stream -> stream . skip ( 1 ) . findFirst ( ) . get ( ) ) ; } | Benchmarks extracting a stack frame from stack walker by using a lambda expression . |
40,185 | @ BenchmarkMode ( Mode . Throughput ) public StackFrame stackWalkerWithAnonymousClass ( ) { return StackWalker . getInstance ( ) . walk ( new Function < Stream < StackFrame > , StackFrame > ( ) { public StackFrame apply ( final Stream < StackFrame > stream ) { return stream . skip ( 1 ) . findFirst ( ) . get ( ) ; } } ) ; } | Benchmarks extracting a stack frame from stack walker by using an anonymous inner class . |
40,186 | @ BenchmarkMode ( Mode . Throughput ) public StackFrame stackWalkerWithInnerClass ( ) { return StackWalker . getInstance ( ) . walk ( new StackFrameExtractor ( 1 ) ) ; } | Benchmarks extracting a stack frame from stack walker by using a static inner class . |
40,187 | @ BenchmarkMode ( Mode . Throughput ) @ SuppressWarnings ( "removal" ) public Class < ? > sunReflection ( ) { return sun . reflect . Reflection . getCallerClass ( 1 ) ; } | Benchmarks extracting a class via Sun reflection . |
40,188 | private static String getPackage ( final String fullyQualifiedClassName ) { int dotIndex = fullyQualifiedClassName . lastIndexOf ( '.' ) ; if ( dotIndex == - 1 ) { return null ; } else { return fullyQualifiedClassName . substring ( 0 , dotIndex ) ; } } | Gets the package name from a fully qualified class name . |
40,189 | private static Long parseDigits ( final String text , final int start ) { for ( int i = start ; i < text . length ( ) ; ++ i ) { char character = text . charAt ( i ) ; if ( character < '0' || character > '9' ) { return parseLong ( text . substring ( start , i ) ) ; } } return parseLong ( text . substring ( start ) ) ; } | Parses digits from a defined position in a text . Following non - numeric characters will be ignored . |
40,190 | private static Long parseLong ( final String text ) { if ( text . length ( ) == 0 ) { return null ; } else { try { return Long . parseLong ( text ) ; } catch ( NumberFormatException ex ) { return null ; } } } | Converts a text into a number . |
40,191 | private static Level translateLevel ( final int level ) { if ( level <= TRACE_INT ) { return Level . TRACE ; } else if ( level <= DEBUG_INT ) { return Level . DEBUG ; } else if ( level <= INFO_INT ) { return Level . INFO ; } else if ( level <= WARN_INT ) { return Level . WARN ; } else { return Level . ERROR ; } } | Translate SLF4J severity level codes . |
40,192 | private static Throwable extractThrowable ( final Object [ ] arguments ) { return arguments . length == 0 ? null : extractThrowable ( arguments [ arguments . length - 1 ] ) ; } | Returns a throwable if the last argument is one . |
40,193 | private static void validateLength ( byte [ ] data , String dataName , int expectedLength ) throws IllegalArgumentException { if ( data . length != expectedLength ) { throw new IllegalArgumentException ( String . format ( "Invalid %s length. Expected %d bytes but found %d." , dataName , expectedLength , data . length ) ) ; } } | Checks the length of a byte array . |
40,194 | byte [ ] getRawData ( ) { byte [ ] header = new byte [ ] { ( byte ) getVersionNumber ( ) , 0 } ; if ( isPasswordBased ) { header [ 1 ] |= FLAG_PASSWORD ; } final int dataSize ; if ( isPasswordBased ) { dataSize = header . length + encryptionSalt . length + hmacSalt . length + iv . length + ciphertext . length + hmac . length ; } else { dataSize = header . length + iv . length + ciphertext . length + hmac . length ; } byte [ ] result = new byte [ dataSize ] ; System . arraycopy ( header , 0 , result , 0 , header . length ) ; if ( isPasswordBased ) { System . arraycopy ( encryptionSalt , 0 , result , header . length , encryptionSalt . length ) ; System . arraycopy ( hmacSalt , 0 , result , header . length + encryptionSalt . length , hmacSalt . length ) ; System . arraycopy ( iv , 0 , result , header . length + encryptionSalt . length + hmacSalt . length , iv . length ) ; System . arraycopy ( ciphertext , 0 , result , header . length + encryptionSalt . length + hmacSalt . length + iv . length , ciphertext . length ) ; System . arraycopy ( hmac , 0 , result , header . length + encryptionSalt . length + hmacSalt . length + iv . length + ciphertext . length , hmac . length ) ; } else { System . arraycopy ( iv , 0 , result , header . length , iv . length ) ; System . arraycopy ( ciphertext , 0 , result , header . length + iv . length , ciphertext . length ) ; System . arraycopy ( hmac , 0 , result , header . length + iv . length + ciphertext . length , hmac . length ) ; } return result ; } | Returns the ciphertext packaged as a byte array . |
40,195 | static void isCorrectLength ( byte [ ] object , int length , String name ) { Validate . notNull ( object , "%s cannot be null." , name ) ; Validate . isTrue ( object . length == length , "%s should be %d bytes, found %d bytes." , name , length , object . length ) ; } | Tests object is not null and is of correct length . |
40,196 | private void createStreams ( SecretKey encryptionKey , SecretKey hmacKey , byte [ ] iv , OutputStream out ) throws CryptorException { this . iv = iv ; try { Cipher cipher = Cipher . getInstance ( AES256JNCryptor . AES_CIPHER_ALGORITHM ) ; cipher . init ( Cipher . ENCRYPT_MODE , encryptionKey , new IvParameterSpec ( iv ) ) ; try { Mac mac = Mac . getInstance ( AES256JNCryptor . HMAC_ALGORITHM ) ; mac . init ( hmacKey ) ; macOutputStream = new MacOutputStream ( out , mac ) ; cipherStream = new CipherOutputStream ( macOutputStream , cipher ) ; } catch ( GeneralSecurityException e ) { throw new CryptorException ( "Failed to initialize HMac" , e ) ; } } catch ( GeneralSecurityException e ) { throw new CryptorException ( "Failed to initialize AES cipher" , e ) ; } } | Creates the cipher and MAC streams required |
40,197 | private void writeHeader ( ) throws IOException { if ( passwordBased ) { macOutputStream . write ( AES256JNCryptor . VERSION ) ; macOutputStream . write ( AES256Ciphertext . FLAG_PASSWORD ) ; macOutputStream . write ( encryptionSalt ) ; macOutputStream . write ( hmacSalt ) ; macOutputStream . write ( iv ) ; } else { macOutputStream . write ( AES256JNCryptor . VERSION ) ; macOutputStream . write ( 0 ) ; macOutputStream . write ( iv ) ; } } | Writes the header data to the output stream . |
40,198 | public void write ( int b ) throws IOException { if ( ! writtenHeader ) { writeHeader ( ) ; writtenHeader = true ; } cipherStream . write ( b ) ; } | Writes one byte to the encrypted output stream . |
40,199 | private void fillTrailerBuffer ( ) throws IOException { trailerBuffer = new byte [ trailerSize ] ; if ( trailerSize == 0 ) { return ; } int bytesRead = StreamUtils . readAllBytes ( in , trailerBuffer ) ; if ( bytesRead != trailerBuffer . length ) { throw new EOFException ( String . format ( "Trailer size was %d bytes but stream only contained %d bytes." , trailerSize , bytesRead ) ) ; } } | Populates the trailer buffer with data from the stream . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.