idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
40,100
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 .
46
15
40,101
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 sourc...
Establishes the connection to the database .
140
9
40,102
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 .
61
13
40,103
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 .
64
10
40,104
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 < S...
Generates an insert SQL statement for the configured table and its fields .
248
14
40,105
private static void append ( final StringBuilder builder , final String identifier , final String quote ) throws SQLException { if ( identifier . indexOf ( ' ' ) >= 0 || identifier . indexOf ( ' ' ) >= 0 ) { throw new SQLException ( "Identifier contains line breaks: " + identifier ) ; } else if ( " " . equals ( quote )...
Appends a database identifier securely to a builder that is building a SQL statement .
203
16
40,106
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 ( F...
Creates tokens for all configured fields .
109
8
40,107
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 .
44
17
40,108
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 ( ...
Translates an Apache Log4j 1 . 2 priority into a tinylog 2 severity level .
153
21
40,109
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 n...
Translates a tinylog 2 severity level into an Apache Log4j 1 . 2 level .
101
21
40,110
private static ContextProvider createContextProvider ( final Collection < LoggingProvider > loggingProviders ) { Collection < ContextProvider > contextProviders = new ArrayList < ContextProvider > ( loggingProviders . size ( ) ) ; for ( LoggingProvider loggingProvider : loggingProviders ) { contextProviders . add ( log...
Gets all context providers from given logging providers and combine them into a new one .
88
17
40,111
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 P...
Parses a format pattern and produces a generic token from it . This token can be used by writers for rendering log entries .
399
26
40,112
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 ...
Creates a new token for a given placeholder .
122
10
40,113
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 ( ) ; } el...
Creates a new token for a name and configuration .
485
11
40,114
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 { Strin...
Creates style decorators for a token .
270
9
40,115
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 ( ) ; swit...
Loads the actual logging provider .
260
7
40,116
@ Benchmark @ 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 .
56
16
40,117
@ Benchmark @ BenchmarkMode ( Mode . Throughput ) public StackFrame stackWalkerWithAnonymousClass ( ) { return StackWalker . getInstance ( ) . walk ( new Function < Stream < StackFrame > , StackFrame > ( ) { @ Override public StackFrame apply ( final Stream < StackFrame > stream ) { return stream . skip ( 1 ) . findFir...
Benchmarks extracting a stack frame from stack walker by using an anonymous inner class .
89
17
40,118
@ Benchmark @ 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 .
47
17
40,119
@ Benchmark @ BenchmarkMode ( Mode . Throughput ) @ SuppressWarnings ( "removal" ) public Class < ? > sunReflection ( ) { return sun . reflect . Reflection . getCallerClass ( 1 ) ; }
Benchmarks extracting a class via Sun reflection .
53
9
40,120
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 .
66
12
40,121
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 < ' ' || character > ' ' ) { 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 .
90
21
40,122
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 .
54
8
40,123
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 .
85
10
40,124
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 .
39
11
40,125
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 .
77
9
40,126
byte [ ] getRawData ( ) { // Header: [Version | Options] byte [ ] header = new byte [ ] { ( byte ) getVersionNumber ( ) , 0 } ; if ( isPasswordBased ) { header [ 1 ] |= FLAG_PASSWORD ; } // Pack result final int dataSize ; if ( isPasswordBased ) { dataSize = header . length + encryptionSalt . length + hmacSalt . length...
Returns the ciphertext packaged as a byte array .
415
10
40,127
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 .
72
12
40,128
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 ...
Creates the cipher and MAC streams required
214
8
40,129
private void writeHeader ( ) throws IOException { /* Write out the header */ if ( passwordBased ) { macOutputStream . write ( AES256JNCryptor . VERSION ) ; macOutputStream . write ( AES256Ciphertext . FLAG_PASSWORD ) ; macOutputStream . write ( encryptionSalt ) ; macOutputStream . write ( hmacSalt ) ; macOutputStream ....
Writes the header data to the output stream .
129
10
40,130
@ Override public void write ( int b ) throws IOException { if ( ! writtenHeader ) { writeHeader ( ) ; writtenHeader = true ; } cipherStream . write ( b ) ; }
Writes one byte to the encrypted output stream .
41
10
40,131
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 b...
Populates the trailer buffer with data from the stream .
99
11
40,132
public static void decryptAsync ( String encrypted , String password , RNCryptorNativeCallback RNCryptorNativeCallback ) { String decrypted ; try { decrypted = new RNCryptorNative ( ) . decrypt ( encrypted , password ) ; RNCryptorNativeCallback . done ( decrypted , null ) ; } catch ( Exception e ) { RNCryptorNativeCall...
Decrypts encrypted base64 string and returns via callback
84
11
40,133
public static void encryptAsync ( String raw , String password , RNCryptorNativeCallback RNCryptorNativeCallback ) { byte [ ] encrypted ; try { encrypted = new RNCryptorNative ( ) . encrypt ( raw , password ) ; RNCryptorNativeCallback . done ( new String ( encrypted , "UTF-8" ) , null ) ; } catch ( Exception e ) { RNCr...
Encrypts raw string and returns result via callback
93
10
40,134
public static void encryptFile ( File raw , File encryptedFile , String password ) throws IOException { byte [ ] b = readBytes ( raw ) ; String encodedImage = Base64 . encodeToString ( b , Base64 . DEFAULT ) ; byte [ ] encryptedBytes = new RNCryptorNative ( ) . encrypt ( encodedImage , password ) ; writeBytes ( encrypt...
Encrypts file using password
84
6
40,135
public static void decryptFile ( File encryptedFile , File result , String password ) throws IOException { byte [ ] b = readBytes ( encryptedFile ) ; String decryptedImageString = new RNCryptorNative ( ) . decrypt ( new String ( b ) , password ) ; byte [ ] decodedBytes = Base64 . decode ( decryptedImageString , 0 ) ; w...
Decrypts file using password
88
6
40,136
static boolean arraysEqual ( byte [ ] array1 , byte [ ] array2 ) { if ( array1 . length != array2 . length ) { return false ; } boolean isEqual = true ; for ( int i = 0 ; i < array1 . length ; i ++ ) { if ( array1 [ i ] != array2 [ i ] ) { isEqual = false ; } } return isEqual ; }
Compares arrays for equality in constant time . This avoids certain types of timing attacks .
90
17
40,137
private void initializeStream ( ) throws IOException { int headerDataSize ; if ( isPasswordEncrypted ) { headerDataSize = AES256v3Ciphertext . HEADER_SIZE + AES256v3Ciphertext . ENCRYPTION_SALT_LENGTH + AES256v3Ciphertext . HMAC_SALT_LENGTH + AES256v3Ciphertext . AES_BLOCK_SIZE ; } else { headerDataSize = AES256v3Ciphe...
Reads the header data derives keys if necessary and creates the input streams .
780
15
40,138
private int completeRead ( int b ) throws IOException , StreamIntegrityException { if ( b == END_OF_STREAM ) { handleEndOfStream ( ) ; } else { // Have we reached the end of the stream? int c = pushbackInputStream . read ( ) ; if ( c == END_OF_STREAM ) { handleEndOfStream ( ) ; } else { pushbackInputStream . unread ( c...
Updates the HMAC value and handles the end of stream .
100
13
40,139
private void handleEndOfStream ( ) throws StreamIntegrityException { if ( endOfStreamHandled ) { return ; } endOfStreamHandled = true ; byte [ ] originalHMAC = trailerIn . getTrailer ( ) ; byte [ ] calculateHMAC = mac . doFinal ( ) ; if ( ! AES256JNCryptor . arraysEqual ( originalHMAC , calculateHMAC ) ) { throw new St...
Verifies the HMAC value and throws an exception if it fails .
104
14
40,140
static int readAllBytes ( InputStream in , byte [ ] buffer ) throws IOException { int index = 0 ; while ( index < buffer . length ) { int read = in . read ( buffer , index , buffer . length - index ) ; if ( read == - 1 ) { return index ; } index += read ; } return index ; }
Attempts to fill the buffer by reading as many bytes as available . The returned number indicates how many bytes were read which may be smaller than the buffer size if EOF was reached .
72
36
40,141
static void readAllBytesOrFail ( InputStream in , byte [ ] buffer ) throws IOException { int read = readAllBytes ( in , buffer ) ; if ( read != buffer . length ) { throw new EOFException ( String . format ( "Expected %d bytes but read %d bytes." , buffer . length , read ) ) ; } }
Fills the buffer from the input stream . Throws exception if EOF occurs before buffer is filled .
75
21
40,142
public DataLoader < K , V > clear ( K key ) { Object cacheKey = getCacheKey ( key ) ; synchronized ( this ) { futureCache . delete ( cacheKey ) ; } return this ; }
Clears the future with the specified key from the cache if caching is enabled so it will be re - fetched on the next load request .
44
29
40,143
public DataLoader < K , V > prime ( K key , V value ) { Object cacheKey = getCacheKey ( key ) ; synchronized ( this ) { if ( ! futureCache . containsKey ( cacheKey ) ) { futureCache . set ( cacheKey , CompletableFuture . completedFuture ( value ) ) ; } } return this ; }
Primes the cache with the given key and value .
73
11
40,144
public DataLoader < K , V > prime ( K key , Exception error ) { Object cacheKey = getCacheKey ( key ) ; if ( ! futureCache . containsKey ( cacheKey ) ) { futureCache . set ( cacheKey , CompletableFutureKit . failedFuture ( error ) ) ; } return this ; }
Primes the cache with the given key and error .
68
11
40,145
public static < V > Try < V > tryCall ( Callable < V > callable ) { try { return Try . succeeded ( callable . call ( ) ) ; } catch ( Exception e ) { return Try . failed ( e ) ; } }
Calls the callable and if it returns a value the Try is successful with that value or if throws and exception the Try captures that
53
27
40,146
public static < V > CompletionStage < Try < V > > tryStage ( CompletionStage < V > completionStage ) { return completionStage . handle ( ( value , throwable ) -> { if ( throwable != null ) { return failed ( throwable ) ; } return succeeded ( value ) ; } ) ; }
Creates a CompletionStage that when it completes will capture into a Try whether the given completionStage was successful or not
67
24
40,147
public < U > Try < U > map ( Function < ? super V , U > mapper ) { if ( isSuccess ( ) ) { return succeeded ( mapper . apply ( value ) ) ; } return failed ( this . throwable ) ; }
Maps the Try into another Try with a different type
53
10
40,148
public < U > Try < U > flatMap ( Function < ? super V , Try < U > > mapper ) { if ( isSuccess ( ) ) { return mapper . apply ( value ) ; } return failed ( this . throwable ) ; }
Flats maps the Try into another Try type
54
9
40,149
public Try < V > recover ( Function < Throwable , V > recoverFunction ) { if ( isFailure ( ) ) { return succeeded ( recoverFunction . apply ( throwable ) ) ; } return this ; }
Called the recover function of the Try failed otherwise returns this if it was successful .
44
17
40,150
public Statistics combine ( Statistics other ) { return new Statistics ( this . loadCount + other . getLoadCount ( ) , this . loadErrorCount + other . getLoadErrorCount ( ) , this . batchInvokeCount + other . getBatchInvokeCount ( ) , this . batchLoadCount + other . getBatchLoadCount ( ) , this . batchLoadExceptionCoun...
This will combine this set of statistics with another set of statistics so that they become the combined count of each
109
21
40,151
public DataLoaderRegistry register ( String key , DataLoader < ? , ? > dataLoader ) { dataLoaders . put ( key , dataLoader ) ; return this ; }
This will register a new dataloader
37
9
40,152
public DataLoaderRegistry combine ( DataLoaderRegistry registry ) { DataLoaderRegistry combined = new DataLoaderRegistry ( ) ; this . dataLoaders . forEach ( combined :: register ) ; registry . dataLoaders . forEach ( combined :: register ) ; return combined ; }
This will combine all the current data loaders in this registry and all the data loaders from the specified registry and return a new combined registry
60
28
40,153
@ SuppressWarnings ( "unchecked" ) public < K , V > DataLoader < K , V > getDataLoader ( String key ) { return ( DataLoader < K , V > ) dataLoaders . get ( key ) ; }
Returns the dataloader that was registered under the specified key
53
13
40,154
public static URI addPathComponent ( URI uri , String component ) { if ( uri != null && component != null ) try { return new URI ( uri . getScheme ( ) , uri . getUserInfo ( ) , uri . getHost ( ) , uri . getPort ( ) , Optional . ofNullable ( uri . getPath ( ) ) . map ( path -> join ( path , component , ' ' ) ) . orElse ...
This method adds a component to the path of an URI .
177
12
40,155
private boolean includeSuperclass ( TypeElement superclass ) { if ( env . isIncluded ( superclass ) ) return true ; // TODO Make configurable: // See https://github.com/talsma-ict/umldoclet/issues/148 return superclass . getModifiers ( ) . contains ( Modifier . PUBLIC ) || superclass . getModifiers ( ) . contains ( Mod...
Determine whether a superclass is included in the documentation .
94
13
40,156
private File getDiagramFile ( FileFormat format ) { File base = getDiagramBaseFile ( ) ; return new File ( base . getParent ( ) , base . getName ( ) + format . getFileSuffix ( ) ) ; }
The diagram file in the specified format .
53
8
40,157
public static String relativePath ( File from , File to ) { if ( from == null || to == null ) return null ; try { if ( from . isFile ( ) ) from = from . getParentFile ( ) ; if ( ! from . isDirectory ( ) ) throw new IllegalArgumentException ( "Not a directory: " + from ) ; final String [ ] fromParts = from . getCanonica...
Returns the relative path from one file to another .
348
10
40,158
Collection < UmlDiagram > collectDiagrams ( ) throws IOException { if ( diagramExtensions . isEmpty ( ) ) return Collections . emptySet ( ) ; try { Files . walkFileTree ( imagesDirectory . orElse ( basedir ) . toPath ( ) , this ) ; return unmodifiableCollection ( collected . get ( ) ) ; } finally { collected . remove (...
Collects all generated diagram files by walking the specified path .
86
12
40,159
private static Indentation resolve ( final int width , final char ch , final int level ) { return width == 0 ? NONE : ch == ' ' ? spaces ( width , level ) : width == 1 && ch == ' ' ? tabs ( level ) : new Indentation ( width , ch , level ) ; }
Internal factory method that tries to resolve a constant indentation instance before returning a new object .
67
18
40,160
private int [ ] toCodePointArray ( String input ) { int len = input . length ( ) ; int [ ] codePointArray = new int [ input . codePointCount ( 0 , len ) ] ; for ( int i = 0 , j = 0 ; i < len ; i = input . offsetByCodePoints ( i , 1 ) ) { codePointArray [ j ++ ] = input . codePointAt ( i ) ; } return codePointArray ; }
convert from string to code point array
98
8
40,161
public byte [ ] getJarBytes ( ) throws EeClassLoaderException { DataInputStream dataInputStream = null ; byte [ ] bytes ; try { long jarEntrySize = jarEntry . getSize ( ) ; if ( jarEntrySize <= 0 || jarEntrySize >= Integer . MAX_VALUE ) { throw new EeClassLoaderException ( "Invalid size " + jarEntrySize + " for entry "...
Read JAR entry and return byte array of this JAR entry .
211
14
40,162
public static String camelCaseToHyphenCase ( String s ) { StringBuilder parsedString = new StringBuilder ( s . substring ( 0 , 1 ) . toLowerCase ( ) ) ; for ( char c : s . substring ( 1 ) . toCharArray ( ) ) { if ( Character . isUpperCase ( c ) ) { parsedString . append ( "-" ) . append ( Character . toLowerCase ( c ) ...
Parse upper camel case to lower hyphen case .
117
11
40,163
public static String hyphenCaseToCamelCase ( String s ) { List < String > words = Stream . of ( s . split ( "-" ) ) . filter ( w -> ! "" . equals ( w ) ) . collect ( Collectors . toList ( ) ) ; if ( words . size ( ) < 2 ) { return s ; } StringBuilder parsedString = new StringBuilder ( words . get ( 0 ) ) ; for ( int i ...
Parse lower hyphen case to upper camel case .
163
11
40,164
private boolean representsArray ( String key ) { int openingBracket = key . indexOf ( "[" ) ; int closingBracket = key . indexOf ( "]" ) ; return closingBracket == key . length ( ) - 1 && openingBracket != - 1 ; }
Returns true if key represents an array .
58
8
40,165
private Object getValue ( String key ) { // iterate over configuration tree String [ ] splittedKeys = key . split ( "\\." ) ; Object value = config ; for ( int i = 0 ; i < splittedKeys . length ; i ++ ) { String splittedKey = splittedKeys [ i ] ; if ( value == null ) { return null ; } // parse arrays if ( representsArr...
Parses configuration map returns value for given key .
402
11
40,166
private void loadJar ( final JarFileInfo jarFileInfo ) { final String JAR_SUFFIX = ".jar" ; jarFiles . add ( jarFileInfo ) ; jarFileInfo . getJarFile ( ) . stream ( ) . parallel ( ) . filter ( je -> ! je . isDirectory ( ) && je . getName ( ) . toLowerCase ( ) . endsWith ( JAR_SUFFIX ) ) . forEach ( je -> { try { JarEnt...
Loads specified JAR .
477
6
40,167
private JarEntryInfo findJarNativeEntry ( String libraryName ) { String name = System . mapLibraryName ( libraryName ) ; for ( JarFileInfo jarFileInfo : jarFiles ) { JarFile jarFile = jarFileInfo . getJarFile ( ) ; Enumeration < JarEntry > entries = jarFile . entries ( ) ; while ( entries . hasMoreElements ( ) ) { JarE...
Finds native library entry .
323
6
40,168
private Class < ? > findJarClass ( String className ) throws EeClassLoaderException { Class < ? > clazz = classes . get ( className ) ; if ( clazz != null ) { return clazz ; } // Char '/' works for Win32 and Unix. String fullClassName = className . replace ( ' ' , ' ' ) + ".class" ; JarEntryInfo jarEntryInfo = findJarE...
Loads class from a JAR and searches for all jar - in - jar .
298
17
40,169
@ PostConstruct public Object loadConfiguration ( InvocationContext ic ) throws Exception { Object target = ic . getTarget ( ) ; Class targetClass = target . getClass ( ) ; if ( targetClassIsProxied ( targetClass ) ) { targetClass = targetClass . getSuperclass ( ) ; } ConfigBundle configBundleAnnotation = ( ConfigBundl...
Method initialises class fields from configuration .
144
8
40,170
private Optional getValueOfPrimitive ( Class type , String key ) { if ( type . equals ( String . class ) ) { return configurationUtil . get ( key ) ; } else if ( type . equals ( Boolean . class ) || type . equals ( boolean . class ) ) { return configurationUtil . getBoolean ( key ) ; } else if ( type . equals ( Float ....
Returns a value of a primitive configuration type
220
8
40,171
private Object processNestedObject ( Class targetClass , Method method , Class parameterType , String keyPrefix , Map < Class , Class > processedClassRelations , int arrayIndex , boolean watchAllFields ) throws Exception { Object nestedTarget = parameterType . getConstructor ( ) . newInstance ( ) ; Class nestedTargetCl...
Create a new instance for nested class check for cycles and populate nested instance .
237
15
40,172
private String getKeyPrefix ( Class targetClass ) { String prefix = ( ( ConfigBundle ) targetClass . getAnnotation ( ConfigBundle . class ) ) . value ( ) ; if ( prefix . isEmpty ( ) ) { prefix = StringUtils . camelCaseToHyphenCase ( targetClass . getSimpleName ( ) ) ; } if ( "." . equals ( prefix ) ) { prefix = "" ; } ...
Generate a key prefix from annotation class name or parent prefix in case of nested classes .
94
18
40,173
private String setterToField ( String setter ) { return Character . toLowerCase ( setter . charAt ( 3 ) ) + setter . substring ( 4 ) ; }
Parse setter name to field name .
39
9
40,174
public static MemcachedClient create ( final PippoSettings settings ) { String host = settings . getString ( HOST , "localhost:11211" ) ; String prot = settings . getString ( PROT , "BINARY" ) ; CommandFactory protocol ; switch ( prot ) { case "BINARY" : protocol = new BinaryCommandFactory ( ) ; break ; case "TEXT" : p...
Create a memcached client with pippo settings .
191
12
40,175
private < T > Option < T > getOption ( String parameter ) { try { Field field = UndertowOptions . class . getDeclaredField ( parameter ) ; if ( Option . class . getName ( ) . equals ( field . getType ( ) . getTypeName ( ) ) ) { Object value = field . get ( null ) ; return ( Option < T > ) value ; } } catch ( Exception ...
Returns Options for given parameter if present else null
116
9
40,176
private String replacePosixClasses ( String input ) { return input . replace ( ":alnum:" , "\\p{Alnum}" ) . replace ( ":alpha:" , "\\p{L}" ) . replace ( ":ascii:" , "\\p{ASCII}" ) . replace ( ":digit:" , "\\p{Digit}" ) . replace ( ":xdigit:" , "\\p{XDigit}" ) ; }
Replace any specified POSIX character classes with the Java equivalent .
100
13
40,177
public void register ( Package ... packages ) { List < String > packageNames = Arrays . stream ( packages ) . map ( Package :: getName ) . collect ( Collectors . toList ( ) ) ; register ( packageNames . toArray ( new String [ packageNames . size ( ) ] ) ) ; }
Register all controller methods in the specified packages .
65
9
40,178
public void register ( String ... packageNames ) { Collection < Class < ? extends Controller > > classes = getControllerClasses ( packageNames ) ; if ( classes . isEmpty ( ) ) { log . warn ( "No annotated controllers found in package(s) '{}'" , Arrays . toString ( packageNames ) ) ; return ; } log . debug ( "Found {} c...
Register all controller methods in the specified package names .
124
10
40,179
public void register ( Class < ? extends Controller > ... controllerClasses ) { for ( Class < ? extends Controller > controllerClass : controllerClasses ) { register ( controllerClass ) ; } }
Register all controller methods in the specified controller classes .
40
10
40,180
private void registerControllerMethods ( Map < Method , Class < ? extends Annotation > > controllerMethods , Controller controller ) { List < Route > controllerRoutes = createControllerRoutes ( controllerMethods ) ; for ( Route controllerRoute : controllerRoutes ) { if ( controller != null ) { ( ( ControllerHandler ) c...
Register the controller methods as routes .
113
7
40,181
@ SuppressWarnings ( "unchecked" ) private List < Route > createControllerRoutes ( Map < Method , Class < ? extends Annotation > > controllerMethods ) { List < Route > routes = new ArrayList <> ( ) ; Class < ? extends Controller > controllerClass = ( Class < ? extends Controller > ) controllerMethods . keySet ( ) . ite...
Create controller routes from controller methods .
580
7
40,182
private Set < String > getControllerPaths ( Class < ? > controllerClass ) { Set < String > parentPaths = Collections . emptySet ( ) ; if ( controllerClass . getSuperclass ( ) != null ) { parentPaths = getControllerPaths ( controllerClass . getSuperclass ( ) ) ; } Set < String > paths = new LinkedHashSet <> ( ) ; Path c...
Recursively builds the paths for the controller class .
252
11
40,183
private Collection < Method > sortControllerMethods ( Set < Method > controllerMethods ) { List < Method > list = new ArrayList <> ( controllerMethods ) ; list . sort ( ( m1 , m2 ) -> { int o1 = Integer . MAX_VALUE ; Order order1 = ClassUtils . getAnnotation ( m1 , Order . class ) ; if ( order1 != null ) { o1 = order1 ...
Sort the controller s methods by their preferred order if specified .
227
12
40,184
public static String getFileExtension ( String value ) { int index = value . lastIndexOf ( ' ' ) ; if ( index > - 1 ) { return value . substring ( index + 1 ) ; } return "" ; }
Returns the file extension of the value without the dot or an empty string .
49
15
40,185
public static String getPrefix ( String input , char delimiter ) { int index = input . indexOf ( delimiter ) ; if ( index > - 1 ) { return input . substring ( 0 , index ) ; } return input ; }
Returns the prefix of the input string from 0 to the first index of the delimiter OR it returns the input string .
51
24
40,186
private String asJettyFriendlyPath ( String path , String name ) { try { new URL ( path ) ; log . debug ( "Defer interpretation of {} URL '{}' to Jetty" , name , path ) ; return path ; } catch ( MalformedURLException e ) { //Expected. We've got a path and not a URL Path p = Paths . get ( path ) ; if ( Files . exists ( ...
Jetty treats non - URL paths are file paths interpreted in the current working directory . Provide ability to accept paths to resources on the Classpath .
272
29
40,187
private List < String > locatePomProperties ( ) { List < String > propertiesFiles = new ArrayList <> ( ) ; List < URL > packageUrls = ClasspathUtils . getResources ( getResourceBasePath ( ) ) ; for ( URL packageUrl : packageUrls ) { if ( packageUrl . getProtocol ( ) . equals ( "jar" ) ) { // We only care about Webjars ...
Locate all Webjars Maven pom . properties files on the classpath .
291
18
40,188
@ Override public void init ( Application application ) { languages = application . getLanguages ( ) ; messages = application . getMessages ( ) ; router = application . getRouter ( ) ; pippoSettings = application . getPippoSettings ( ) ; fileExtension = pippoSettings . getString ( PippoConstants . SETTING_TEMPLATE_EXTE...
Performs common initialization for template engines .
142
8
40,189
public String getLanguageComponent ( String language ) { if ( StringUtils . isNullOrEmpty ( language ) ) { return "" ; } if ( language . contains ( "-" ) ) { return language . split ( "-" ) [ 0 ] ; } else if ( language . contains ( "_" ) ) { return language . split ( "_" ) [ 0 ] ; } return language ; }
Returns the language component of a language string .
82
9
40,190
public void clearLanguageCookie ( Response response ) { String cookieName = generateLanguageCookie ( "" ) . getName ( ) ; response . removeCookie ( cookieName ) ; }
Clears the application language cookie .
39
7
40,191
public String getLanguageOrDefault ( RouteContext routeContext ) { final String cookieName = generateLanguageCookie ( defaultLanguage ) . getName ( ) ; // Step 1: Look for a Response cookie. // The Response always has priority over the Request because it may have // been set earlier in the HandlerChain. Cookie cookie =...
Returns the language for the request . This process considers Request & Response cookies the Request ACCEPT_LANGUAGE header and finally the application default language .
336
32
40,192
public Locale getLocaleOrDefault ( String language ) { String lang = getLanguageOrDefault ( language ) ; return Locale . forLanguageTag ( lang ) ; }
Returns the Java Locale for the specified language or the Locale for the default language if the requested language can not be mapped to a Locale .
36
30
40,193
public String getLanguageOrDefault ( String language ) { if ( ! StringUtils . isNullOrEmpty ( language ) ) { // Check if we get a registered mapping for the language input // string. The language may be either 'language-country' or // 'language'. String [ ] languages = language . toLowerCase ( ) . split ( "," ) ; for (...
Returns a registered language if one can be matched from the input string OR returns the default language . The input string may be a simple language or locale value or may be as complex as an ACCEPT - LANGUAGE header .
141
47
40,194
private String getDefaultLanguage ( List < String > applicationLanguages ) { if ( applicationLanguages . isEmpty ( ) ) { String NO_LANGUAGES_TEXT = "Please specify the supported languages in 'application.properties'." + " For example 'application.languages=en, ro, de, pt-BR' makes 'en' your default language." ; log . e...
Returns the default language as derived from PippoSettings .
118
12
40,195
private void createIndex ( long idleTime ) { try { this . sessions . createIndex ( new Document ( SESSION_TTL , 1 ) , new IndexOptions ( ) . expireAfter ( idleTime , TimeUnit . SECONDS ) . name ( SESSION_INDEX_NAME ) ) ; } catch ( MongoException ex ) { //update idle time this . sessions . dropIndex ( SESSION_INDEX_NAME...
Create TTL index
144
3
40,196
protected void initInterceptors ( ) { interceptors = new ArrayList <> ( ) ; ControllerUtils . collectRouteInterceptors ( controllerMethod ) . forEach ( handlerClass -> { try { interceptors . add ( handlerClass . newInstance ( ) ) ; } catch ( InstantiationException | IllegalAccessException e ) { throw new PippoRuntimeEx...
Init interceptors from controller method .
86
7
40,197
protected void initExtractors ( ) { Parameter [ ] parameters = controllerMethod . getParameters ( ) ; extractors = new MethodParameterExtractor [ parameters . length ] ; for ( int i = 0 ; i < parameters . length ; i ++ ) { MethodParameter parameter = new MethodParameter ( controllerMethod , i ) ; MethodParameterExtract...
Init extractors from controller method .
187
7
40,198
protected void validateConsumes ( Collection < String > contentTypes ) { Set < String > ignoreConsumes = new TreeSet <> ( ) ; ignoreConsumes . add ( Consumes . ALL ) ; // these are handled by the TemplateEngine ignoreConsumes . add ( Consumes . HTML ) ; ignoreConsumes . add ( Consumes . XHTML ) ; // these are handled b...
Validates that the declared consumes can actually be processed by Pippo .
351
15
40,199
protected void validateProduces ( Collection < String > contentTypes ) { Set < String > ignoreProduces = new TreeSet <> ( ) ; ignoreProduces . add ( Produces . TEXT ) ; ignoreProduces . add ( Produces . HTML ) ; ignoreProduces . add ( Produces . XHTML ) ; for ( String produces : declaredProduces ) { if ( ignoreProduces...
Validates that the declared content - types can actually be generated by Pippo .
164
17