idx
int64 0
41.2k
| question
stringlengths 74
4.04k
| target
stringlengths 7
750
|
|---|---|---|
40,200
|
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 ) { RNCryptorNativeCallback . done ( null , e ) ; } }
|
Decrypts encrypted base64 string and returns via callback
|
40,201
|
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 ) { RNCryptorNativeCallback . done ( null , e ) ; } }
|
Encrypts raw string and returns result via callback
|
40,202
|
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 ( encryptedFile , encryptedBytes ) ; }
|
Encrypts file using password
|
40,203
|
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 ) ; writeBytes ( result , decodedBytes ) ; }
|
Decrypts file using password
|
40,204
|
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 .
|
40,205
|
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 = AES256v3Ciphertext . HEADER_SIZE + AES256v3Ciphertext . AES_BLOCK_SIZE ; } byte [ ] headerData = new byte [ headerDataSize ] ; StreamUtils . readAllBytesOrFail ( in , headerData ) ; int offset = 0 ; byte version = headerData [ offset ++ ] ; if ( version != AES256v3Ciphertext . EXPECTED_VERSION ) { throw new IOException ( String . format ( "Expected version %d but found %d." , AES256v3Ciphertext . EXPECTED_VERSION , version ) ) ; } byte options = headerData [ offset ++ ] ; if ( isPasswordEncrypted ) { if ( options != AES256v3Ciphertext . FLAG_PASSWORD ) { throw new IOException ( "Expected password flag missing." ) ; } byte [ ] decryptionSalt = new byte [ AES256v3Ciphertext . ENCRYPTION_SALT_LENGTH ] ; System . arraycopy ( headerData , offset , decryptionSalt , 0 , decryptionSalt . length ) ; offset += decryptionSalt . length ; byte [ ] hmacSalt = new byte [ AES256v3Ciphertext . HMAC_SALT_LENGTH ] ; System . arraycopy ( headerData , offset , hmacSalt , 0 , hmacSalt . length ) ; offset += hmacSalt . length ; JNCryptor cryptor = new AES256JNCryptor ( ) ; try { decryptionKey = cryptor . keyForPassword ( password , decryptionSalt ) ; hmacKey = cryptor . keyForPassword ( password , hmacSalt ) ; } catch ( CryptorException e ) { throw new IOException ( "Failed to derive keys from password." , e ) ; } } else { if ( options != 0 ) { throw new IOException ( "Expected options byte to be zero." ) ; } } byte [ ] iv = new byte [ AES256v3Ciphertext . AES_BLOCK_SIZE ] ; System . arraycopy ( headerData , offset , iv , 0 , iv . length ) ; trailerIn = new TrailerInputStream ( in , AES256v3Ciphertext . HMAC_SIZE ) ; try { Cipher decryptCipher = Cipher . getInstance ( AES256JNCryptor . AES_CIPHER_ALGORITHM ) ; decryptCipher . init ( Cipher . DECRYPT_MODE , decryptionKey , new IvParameterSpec ( iv ) ) ; mac = Mac . getInstance ( AES256JNCryptor . HMAC_ALGORITHM ) ; mac . init ( hmacKey ) ; mac . update ( headerData ) ; pushbackInputStream = new PushbackInputStream ( new CipherInputStream ( new MacUpdateInputStream ( trailerIn , mac ) , decryptCipher ) , 1 ) ; } catch ( GeneralSecurityException e ) { throw new IOException ( "Failed to initiate cipher." , e ) ; } }
|
Reads the header data derives keys if necessary and creates the input streams .
|
40,206
|
private int completeRead ( int b ) throws IOException , StreamIntegrityException { if ( b == END_OF_STREAM ) { handleEndOfStream ( ) ; } else { int c = pushbackInputStream . read ( ) ; if ( c == END_OF_STREAM ) { handleEndOfStream ( ) ; } else { pushbackInputStream . unread ( c ) ; } } return b ; }
|
Updates the HMAC value and handles the end of stream .
|
40,207
|
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 StreamIntegrityException ( "MAC validation failed." ) ; } }
|
Verifies the HMAC value and throws an exception if it fails .
|
40,208
|
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 .
|
40,209
|
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 .
|
40,210
|
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 .
|
40,211
|
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 .
|
40,212
|
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 .
|
40,213
|
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
|
40,214
|
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
|
40,215
|
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
|
40,216
|
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
|
40,217
|
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 .
|
40,218
|
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 . batchLoadExceptionCount + other . getBatchLoadExceptionCount ( ) , this . cacheHitCount + other . getCacheHitCount ( ) ) ; }
|
This will combine this set of statistics with another set of statistics so that they become the combined count of each
|
40,219
|
public DataLoaderRegistry register ( String key , DataLoader < ? , ? > dataLoader ) { dataLoaders . put ( key , dataLoader ) ; return this ; }
|
This will register a new dataloader
|
40,220
|
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
|
40,221
|
@ 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
|
40,222
|
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 ( component ) , uri . getQuery ( ) , uri . getFragment ( ) ) ; } catch ( URISyntaxException use ) { throw new IllegalArgumentException ( "Could not add path component \"" + component + "\" to " + uri + ": " + use . getMessage ( ) , use ) ; } return uri ; }
|
This method adds a component to the path of an URI .
|
40,223
|
private boolean includeSuperclass ( TypeElement superclass ) { if ( env . isIncluded ( superclass ) ) return true ; return superclass . getModifiers ( ) . contains ( Modifier . PUBLIC ) || superclass . getModifiers ( ) . contains ( Modifier . PROTECTED ) ; }
|
Determine whether a superclass is included in the documentation .
|
40,224
|
private File getDiagramFile ( FileFormat format ) { File base = getDiagramBaseFile ( ) ; return new File ( base . getParent ( ) , base . getName ( ) + format . getFileSuffix ( ) ) ; }
|
The diagram file in the specified format .
|
40,225
|
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 . getCanonicalPath ( ) . split ( Pattern . quote ( File . separator ) ) ; List < String > toParts = new ArrayList < > ( asList ( to . getCanonicalPath ( ) . split ( Pattern . quote ( File . separator ) ) ) ) ; int skip = 0 ; while ( skip < fromParts . length && skip < toParts . size ( ) && fromParts [ skip ] . equals ( toParts . get ( skip ) ) ) { skip ++ ; } if ( skip > 0 ) toParts = toParts . subList ( skip , toParts . size ( ) ) ; for ( int i = fromParts . length ; i > skip ; i -- ) toParts . add ( 0 , ".." ) ; return toParts . stream ( ) . collect ( joining ( "/" ) ) ; } catch ( IOException ioe ) { throw new IllegalStateException ( "I/O exception calculating relative path from \"" + from + "\" to \"" + to + "\": " + ioe . getMessage ( ) , ioe ) ; } }
|
Returns the relative path from one file to another .
|
40,226
|
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 .
|
40,227
|
private static Indentation resolve ( final int width , final char ch , final int level ) { return width == 0 ? NONE : ch == ' ' ? spaces ( width , level ) : width == 1 && ch == '\t' ? tabs ( level ) : new Indentation ( width , ch , level ) ; }
|
Internal factory method that tries to resolve a constant indentation instance before returning a new object .
|
40,228
|
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
|
40,229
|
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 " + jarEntry ) ; } bytes = new byte [ ( int ) jarEntrySize ] ; InputStream inputStream = jarFileInfo . getJarFile ( ) . getInputStream ( jarEntry ) ; dataInputStream = new DataInputStream ( inputStream ) ; dataInputStream . readFully ( bytes ) ; } catch ( IOException e ) { throw new EeClassLoaderException ( null , e ) ; } finally { if ( dataInputStream != null ) { try { dataInputStream . close ( ) ; } catch ( IOException e ) { } } } return bytes ; }
|
Read JAR entry and return byte array of this JAR entry .
|
40,230
|
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 ) ) ; } else { parsedString . append ( c ) ; } } return parsedString . toString ( ) ; }
|
Parse upper camel case to lower hyphen case .
|
40,231
|
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 = 1 ; i < words . size ( ) ; i ++ ) { parsedString . append ( Character . toUpperCase ( words . get ( i ) . charAt ( 0 ) ) ) . append ( words . get ( i ) . substring ( 1 ) ) ; } return parsedString . toString ( ) ; }
|
Parse lower hyphen case to upper camel case .
|
40,232
|
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 .
|
40,233
|
private Object getValue ( String key ) { String [ ] splittedKeys = key . split ( "\\." ) ; Object value = config ; for ( int i = 0 ; i < splittedKeys . length ; i ++ ) { String splittedKey = splittedKeys [ i ] ; if ( value == null ) { return null ; } if ( representsArray ( splittedKey ) ) { int arrayIndex ; int openingBracket = splittedKey . indexOf ( "[" ) ; int closingBracket = splittedKey . indexOf ( "]" ) ; try { arrayIndex = Integer . parseInt ( splittedKey . substring ( openingBracket + 1 , closingBracket ) ) ; } catch ( NumberFormatException e ) { if ( log != null ) { log . severe ( "Cannot cast array index." ) ; } return null ; } splittedKey = splittedKey . substring ( 0 , openingBracket ) ; if ( value instanceof Map ) { value = ( ( Map ) value ) . get ( splittedKey ) ; } else { return null ; } if ( value instanceof List ) { value = ( arrayIndex < ( ( List ) value ) . size ( ) ) ? ( ( List ) value ) . get ( arrayIndex ) : null ; } } else { if ( value instanceof Map ) { Object tmpValue = ( ( Map ) value ) . get ( splittedKey ) ; if ( tmpValue == null && i != splittedKeys . length - 1 ) { String postfixKey = Arrays . stream ( splittedKeys ) . skip ( i ) . collect ( Collectors . joining ( "." ) ) ; return ( ( Map ) value ) . get ( postfixKey ) ; } else { value = tmpValue ; } } else { return null ; } } } return value ; }
|
Parses configuration map returns value for given key .
|
40,234
|
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 { JarEntryInfo jarEntryInfo = new JarEntryInfo ( jarFileInfo , je ) ; File tempFile = createJarFile ( jarEntryInfo ) ; debug ( String . format ( "Loading inner JAR %s from temp file %s" , jarEntryInfo . getJarEntry ( ) , getFilenameForLog ( tempFile ) ) ) ; URL url = tempFile . toURI ( ) . toURL ( ) ; ProtectionDomain pdParent = jarFileInfo . getProtectionDomain ( ) ; CodeSource csParent = pdParent . getCodeSource ( ) ; Certificate [ ] certParent = csParent . getCertificates ( ) ; CodeSource csChild = certParent == null ? new CodeSource ( url , csParent . getCodeSigners ( ) ) : new CodeSource ( url , certParent ) ; ProtectionDomain pdChild = new ProtectionDomain ( csChild , pdParent . getPermissions ( ) , pdParent . getClassLoader ( ) , pdParent . getPrincipals ( ) ) ; loadJar ( new JarFileInfo ( new JarFile ( tempFile ) , jarEntryInfo . getName ( ) , jarFileInfo , pdChild , tempFile ) ) ; } catch ( IOException e ) { throw new RuntimeException ( String . format ( "Cannot load jar entries from jar %s" , je . getName ( ) . toLowerCase ( ) ) , e ) ; } catch ( EeClassLoaderException e ) { throw new RuntimeException ( "ERROR on loading inner JAR: " + e . getMessageAll ( ) ) ; } } ) ; }
|
Loads specified JAR .
|
40,235
|
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 ( ) ) { JarEntry jarEntry = entries . nextElement ( ) ; if ( jarEntry . isDirectory ( ) ) { continue ; } String jarEntryName = jarEntry . getName ( ) ; String [ ] token = jarEntryName . split ( "/" ) ; if ( token . length > 0 && token [ token . length - 1 ] . equals ( name ) ) { debug ( String . format ( "Loading native library '%s' found as '%s' in JAR %s" , libraryName , jarEntryName , jarFileInfo . getSimpleName ( ) ) ) ; return new JarEntryInfo ( jarFileInfo , jarEntry ) ; } } } return null ; }
|
Finds native library entry .
|
40,236
|
private Class < ? > findJarClass ( String className ) throws EeClassLoaderException { Class < ? > clazz = classes . get ( className ) ; if ( clazz != null ) { return clazz ; } String fullClassName = className . replace ( '.' , '/' ) + ".class" ; JarEntryInfo jarEntryInfo = findJarEntry ( fullClassName ) ; String jarSimpleName = null ; if ( jarEntryInfo != null ) { jarSimpleName = jarEntryInfo . getJarFileInfo ( ) . getSimpleName ( ) ; definePackage ( className , jarEntryInfo ) ; byte [ ] bytes = jarEntryInfo . getJarBytes ( ) ; try { clazz = defineClass ( className , bytes , 0 , bytes . length , jarEntryInfo . getJarFileInfo ( ) . getProtectionDomain ( ) ) ; } catch ( ClassFormatError e ) { throw new EeClassLoaderException ( null , e ) ; } } if ( clazz == null ) { throw new EeClassLoaderException ( className ) ; } classes . put ( className , clazz ) ; debug ( String . format ( "Loaded %s by %s from JAR %s" , className , getClass ( ) . getName ( ) , jarSimpleName ) ) ; return clazz ; }
|
Loads class from a JAR and searches for all jar - in - jar .
|
40,237
|
public Object loadConfiguration ( InvocationContext ic ) throws Exception { Object target = ic . getTarget ( ) ; Class targetClass = target . getClass ( ) ; if ( targetClassIsProxied ( targetClass ) ) { targetClass = targetClass . getSuperclass ( ) ; } ConfigBundle configBundleAnnotation = ( ConfigBundle ) targetClass . getDeclaredAnnotation ( ConfigBundle . class ) ; processConfigBundleBeanSetters ( target , targetClass , getKeyPrefix ( targetClass ) , new HashMap < > ( ) , configBundleAnnotation . watch ( ) ) ; return ic . proceed ( ) ; }
|
Method initialises class fields from configuration .
|
40,238
|
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 . class ) || type . equals ( float . class ) ) { return configurationUtil . getFloat ( key ) ; } else if ( type . equals ( Double . class ) || type . equals ( double . class ) ) { return configurationUtil . getDouble ( key ) ; } else if ( type . equals ( Integer . class ) || type . equals ( int . class ) ) { return configurationUtil . getInteger ( key ) ; } else if ( type . equals ( Long . class ) || type . equals ( long . class ) ) { return configurationUtil . getLong ( key ) ; } else { return Optional . empty ( ) ; } }
|
Returns a value of a primitive configuration type
|
40,239
|
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 nestedTargetClass = nestedTarget . getClass ( ) ; if ( processedClassRelations . containsKey ( nestedTargetClass ) && processedClassRelations . get ( nestedTargetClass ) . equals ( targetClass ) ) { log . warning ( "There is a cycle in the configuration class tree. ConfigBundle class may not " + "be populated as expected." ) ; } else { String key = getKeyName ( targetClass , method . getName ( ) , keyPrefix ) ; if ( arrayIndex >= 0 ) { key += "[" + arrayIndex + "]" ; } boolean isEmpty = processConfigBundleBeanSetters ( nestedTarget , nestedTargetClass , key , processedClassRelations , watchAllFields ) ; if ( isEmpty ) { return null ; } } return nestedTarget ; }
|
Create a new instance for nested class check for cycles and populate nested instance .
|
40,240
|
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 = "" ; } return prefix ; }
|
Generate a key prefix from annotation class name or parent prefix in case of nested classes .
|
40,241
|
private String setterToField ( String setter ) { return Character . toLowerCase ( setter . charAt ( 3 ) ) + setter . substring ( 4 ) ; }
|
Parse setter name to field name .
|
40,242
|
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" : protocol = new TextCommandFactory ( ) ; break ; default : protocol = new BinaryCommandFactory ( ) ; break ; } String user = settings . getString ( USER , "" ) ; String pass = settings . getString ( PASS , "" ) ; List < String > autM = settings . getStrings ( AUTM ) ; String [ ] mechanisms = autM . toArray ( new String [ autM . size ( ) ] ) ; return create ( host , protocol , user , pass , mechanisms ) ; }
|
Create a memcached client with pippo settings .
|
40,243
|
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 e ) { log . debug ( "getting Option type for parameter {} failed with {}" , parameter , e ) ; } return null ; }
|
Returns Options for given parameter if present else null
|
40,244
|
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 .
|
40,245
|
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 .
|
40,246
|
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 {} controller classes in {} package(s)" , classes . size ( ) , packageNames . length ) ; for ( Class < ? extends Controller > controllerClass : classes ) { register ( controllerClass ) ; } }
|
Register all controller methods in the specified package names .
|
40,247
|
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,248
|
private void registerControllerMethods ( Map < Method , Class < ? extends Annotation > > controllerMethods , Controller controller ) { List < Route > controllerRoutes = createControllerRoutes ( controllerMethods ) ; for ( Route controllerRoute : controllerRoutes ) { if ( controller != null ) { ( ( ControllerHandler ) controllerRoute . getRouteHandler ( ) ) . setController ( controller ) ; controllerRoute . bind ( "__controller" , controller ) ; } } this . routes . addAll ( controllerRoutes ) ; }
|
Register the controller methods as routes .
|
40,249
|
@ 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 ( ) . iterator ( ) . next ( ) . getDeclaringClass ( ) ; Set < String > controllerPaths = getControllerPaths ( controllerClass ) ; Collection < Method > methods = sortControllerMethods ( controllerMethods . keySet ( ) ) ; for ( Method method : methods ) { Class < ? extends Annotation > httpMethodAnnotationClass = controllerMethods . get ( method ) ; Annotation httpMethodAnnotation = method . getAnnotation ( httpMethodAnnotationClass ) ; String httpMethod = httpMethodAnnotation . annotationType ( ) . getAnnotation ( HttpMethod . class ) . value ( ) ; String [ ] methodPaths = ClassUtils . executeDeclaredMethod ( httpMethodAnnotation , "value" ) ; if ( controllerPaths . isEmpty ( ) ) { controllerPaths . add ( "" ) ; } for ( String controllerPath : controllerPaths ) { if ( methodPaths . length == 0 ) { String fullPath = StringUtils . addStart ( controllerPath , "/" ) ; RouteHandler handler = new ControllerHandler ( application , method ) ; Route route = new Route ( httpMethod , fullPath , handler ) . bind ( "__controllerClass" , controllerClass ) . bind ( "__controllerMethod" , method ) ; routes . add ( route ) ; } else { for ( String methodPath : methodPaths ) { String path = Stream . of ( StringUtils . removeEnd ( controllerPath , "/" ) , StringUtils . removeStart ( methodPath , "/" ) ) . filter ( Objects :: nonNull ) . collect ( Collectors . joining ( "/" ) ) ; String fullPath = StringUtils . addStart ( path , "/" ) ; RouteHandler handler = new ControllerHandler ( application , method ) ; Route route = new Route ( httpMethod , fullPath , handler ) . bind ( "__controllerClass" , controllerClass ) . bind ( "__controllerMethod" , method ) ; routes . add ( route ) ; } } } } return routes ; }
|
Create controller routes from controller methods .
|
40,250
|
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 controllerPath = controllerClass . getAnnotation ( Path . class ) ; if ( controllerPath != null && controllerPath . value ( ) . length > 0 ) { if ( parentPaths . isEmpty ( ) ) { paths . addAll ( Arrays . asList ( controllerPath . value ( ) ) ) ; } else { for ( String parentPath : parentPaths ) { for ( String path : controllerPath . value ( ) ) { paths . add ( StringUtils . removeEnd ( parentPath , "/" ) + "/" + StringUtils . removeStart ( path , "/" ) ) ; } } } } else { paths . addAll ( parentPaths ) ; } return paths ; }
|
Recursively builds the paths for the controller class .
|
40,251
|
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 . value ( ) ; } int o2 = Integer . MAX_VALUE ; Order order2 = ClassUtils . getAnnotation ( m2 , Order . class ) ; if ( order2 != null ) { o2 = order2 . value ( ) ; } if ( o1 == o2 ) { String s1 = LangUtils . toString ( m1 ) ; String s2 = LangUtils . toString ( m2 ) ; return s1 . compareTo ( s2 ) ; } return ( o1 < o2 ) ? - 1 : 1 ; } ) ; return list ; }
|
Sort the controller s methods by their preferred order if specified .
|
40,252
|
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 .
|
40,253
|
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 .
|
40,254
|
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 ) { Path p = Paths . get ( path ) ; if ( Files . exists ( Paths . get ( path ) ) ) { log . debug ( "Located {} '{}' on file system" , name , path ) ; return path ; } else { URL url = JettyServer . class . getResource ( path ) ; if ( url != null ) { log . debug ( "Located {} '{}' on Classpath" , name , path ) ; return url . toExternalForm ( ) ; } else { throw new IllegalArgumentException ( String . format ( "%s '%s' not found" , name , path ) ) ; } } } }
|
Jetty treats non - URL paths are file paths interpreted in the current working directory . Provide ability to accept paths to resources on the Classpath .
|
40,255
|
private List < String > locatePomProperties ( ) { List < String > propertiesFiles = new ArrayList < > ( ) ; List < URL > packageUrls = ClasspathUtils . getResources ( getResourceBasePath ( ) ) ; for ( URL packageUrl : packageUrls ) { if ( packageUrl . getProtocol ( ) . equals ( "jar" ) ) { log . debug ( "Scanning {}" , packageUrl ) ; try { String jar = packageUrl . toString ( ) . substring ( "jar:" . length ( ) ) . split ( "!" ) [ 0 ] ; File file = new File ( new URI ( jar ) ) ; try ( JarInputStream is = new JarInputStream ( new FileInputStream ( file ) ) ) { JarEntry entry = null ; while ( ( entry = is . getNextJarEntry ( ) ) != null ) { if ( ! entry . isDirectory ( ) && entry . getName ( ) . endsWith ( "pom.properties" ) ) { propertiesFiles . add ( entry . getName ( ) ) ; } } } } catch ( URISyntaxException | IOException e ) { throw new PippoRuntimeException ( "Failed to get classes for package '{}'" , packageUrl ) ; } } } return propertiesFiles ; }
|
Locate all Webjars Maven pom . properties files on the classpath .
|
40,256
|
public void init ( Application application ) { languages = application . getLanguages ( ) ; messages = application . getMessages ( ) ; router = application . getRouter ( ) ; pippoSettings = application . getPippoSettings ( ) ; fileExtension = pippoSettings . getString ( PippoConstants . SETTING_TEMPLATE_EXTENSION , getDefaultFileExtension ( ) ) ; templatePathPrefix = pippoSettings . getString ( PippoConstants . SETTING_TEMPLATE_PATH_PREFIX , TemplateEngine . DEFAULT_PATH_PREFIX ) ; }
|
Performs common initialization for template engines .
|
40,257
|
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 .
|
40,258
|
public void clearLanguageCookie ( Response response ) { String cookieName = generateLanguageCookie ( "" ) . getName ( ) ; response . removeCookie ( cookieName ) ; }
|
Clears the application language cookie .
|
40,259
|
public String getLanguageOrDefault ( RouteContext routeContext ) { final String cookieName = generateLanguageCookie ( defaultLanguage ) . getName ( ) ; Cookie cookie = routeContext . getResponse ( ) . getCookie ( cookieName ) ; if ( cookie != null && ! StringUtils . isNullOrEmpty ( cookie . getValue ( ) ) ) { return getLanguageOrDefault ( cookie . getValue ( ) ) ; } cookie = routeContext . getRequest ( ) . getCookie ( cookieName ) ; if ( cookie != null && ! StringUtils . isNullOrEmpty ( cookie . getValue ( ) ) ) { return getLanguageOrDefault ( cookie . getValue ( ) ) ; } if ( routeContext . getResponse ( ) . getLocals ( ) . containsKey ( PippoConstants . REQUEST_PARAMETER_LANG ) ) { String language = routeContext . getLocal ( PippoConstants . REQUEST_PARAMETER_LANG ) ; language = getLanguageOrDefault ( language ) ; return language ; } String acceptLanguage = routeContext . getHeader ( HttpConstants . Header . ACCEPT_LANGUAGE ) ; return getLanguageOrDefault ( acceptLanguage ) ; }
|
Returns the language for the request . This process considers Request & Response cookies the Request ACCEPT_LANGUAGE header and finally the application default language .
|
40,260
|
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 .
|
40,261
|
public String getLanguageOrDefault ( String language ) { if ( ! StringUtils . isNullOrEmpty ( language ) ) { String [ ] languages = language . toLowerCase ( ) . split ( "," ) ; for ( String lang : languages ) { if ( lang . contains ( ";" ) ) { lang = lang . split ( ";" ) [ 0 ] ; } if ( isSupportedLanguage ( lang ) ) { return lang ; } } } return defaultLanguage ; }
|
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 .
|
40,262
|
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 . error ( NO_LANGUAGES_TEXT ) ; return "en" ; } return applicationLanguages . get ( 0 ) ; }
|
Returns the default language as derived from PippoSettings .
|
40,263
|
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 ) { this . sessions . dropIndex ( SESSION_INDEX_NAME ) ; this . sessions . createIndex ( new Document ( SESSION_TTL , 1 ) , new IndexOptions ( ) . expireAfter ( idleTime , TimeUnit . SECONDS ) . name ( SESSION_INDEX_NAME ) ) ; } }
|
Create TTL index
|
40,264
|
protected void initInterceptors ( ) { interceptors = new ArrayList < > ( ) ; ControllerUtils . collectRouteInterceptors ( controllerMethod ) . forEach ( handlerClass -> { try { interceptors . add ( handlerClass . newInstance ( ) ) ; } catch ( InstantiationException | IllegalAccessException e ) { throw new PippoRuntimeException ( e ) ; } } ) ; }
|
Init interceptors from controller method .
|
40,265
|
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 ) ; MethodParameterExtractor extractor = application . getExtractors ( ) . stream ( ) . filter ( e -> e . isApplicable ( parameter ) ) . findFirst ( ) . orElse ( null ) ; if ( extractor == null ) { throw new PippoRuntimeException ( "Method '{}' parameter {} of type '{}' does not specify a extractor" , LangUtils . toString ( controllerMethod ) , i + 1 , parameter . getParameterType ( ) ) ; } extractors [ i ] = extractor ; } }
|
Init extractors from controller method .
|
40,266
|
protected void validateConsumes ( Collection < String > contentTypes ) { Set < String > ignoreConsumes = new TreeSet < > ( ) ; ignoreConsumes . add ( Consumes . ALL ) ; ignoreConsumes . add ( Consumes . HTML ) ; ignoreConsumes . add ( Consumes . XHTML ) ; ignoreConsumes . add ( Consumes . FORM ) ; ignoreConsumes . add ( Consumes . MULTIPART ) ; for ( String declaredConsume : declaredConsumes ) { if ( ignoreConsumes . contains ( declaredConsume ) ) { continue ; } String consume = declaredConsume ; int fuzz = consume . indexOf ( '*' ) ; if ( fuzz > - 1 ) { consume = consume . substring ( 0 , fuzz ) ; } if ( ! contentTypes . contains ( consume ) ) { if ( consume . equals ( declaredConsume ) ) { throw new PippoRuntimeException ( "{} declares @{}(\"{}\") but there is no registered ContentTypeEngine for that type!" , LangUtils . toString ( controllerMethod ) , Consumes . class . getSimpleName ( ) , declaredConsume ) ; } else { throw new PippoRuntimeException ( "{} declares @{}(\"{}\") but there is no registered ContentTypeEngine for \"{}\"!" , LangUtils . toString ( controllerMethod ) , Consumes . class . getSimpleName ( ) , declaredConsume , consume ) ; } } } }
|
Validates that the declared consumes can actually be processed by Pippo .
|
40,267
|
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 . contains ( produces ) ) { continue ; } if ( ! contentTypes . contains ( produces ) ) { throw new PippoRuntimeException ( "{} declares @{}(\"{}\") but there is no registered ContentTypeEngine for that type!" , LangUtils . toString ( controllerMethod ) , Produces . class . getSimpleName ( ) , produces ) ; } } }
|
Validates that the declared content - types can actually be generated by Pippo .
|
40,268
|
public void runFinallyRoutes ( ) { while ( iterator . hasNext ( ) ) { Route route = iterator . next ( ) . getRoute ( ) ; if ( route . isRunAsFinally ( ) ) { try { handleRoute ( route ) ; } catch ( Exception e ) { log . error ( "Unexpected error in Finally Route" , e ) ; } } else if ( log . isDebugEnabled ( ) ) { if ( StringUtils . isNullOrEmpty ( route . getName ( ) ) ) { log . debug ( "context.next() not called, skipping handler for {} '{}'" , route . getRequestMethod ( ) , route . getUriPattern ( ) ) ; } else { log . debug ( "context.next() not called, skipping '{}' for {} '{}'" , route . getName ( ) , route . getRequestMethod ( ) , route . getUriPattern ( ) ) ; } } } }
|
Execute all routes that are flagged to run as finally .
|
40,269
|
public boolean hasContentTypeEngine ( String contentTypeOrSuffix ) { String sanitizedTypes = sanitizeContentTypes ( contentTypeOrSuffix ) ; String [ ] types = sanitizedTypes . split ( "," ) ; for ( String type : types ) { if ( engines . containsKey ( type ) ) { return true ; } } return suffixes . containsKey ( contentTypeOrSuffix . toLowerCase ( ) ) ; }
|
Returns true if there is an engine registered for the content type or content type suffix .
|
40,270
|
public ContentTypeEngine registerContentTypeEngine ( Class < ? extends ContentTypeEngine > engineClass ) { ContentTypeEngine engine ; try { engine = engineClass . newInstance ( ) ; } catch ( Exception e ) { throw new PippoRuntimeException ( e , "Failed to instantiate '{}'" , engineClass . getName ( ) ) ; } if ( ! engines . containsKey ( engine . getContentType ( ) ) ) { setContentTypeEngine ( engine ) ; return engine ; } else { log . debug ( "'{}' content engine already registered, ignoring '{}'" , engine . getContentType ( ) , engineClass . getName ( ) ) ; return null ; } }
|
Registers a content type engine if no other engine has been registered for the content type .
|
40,271
|
public void setContentTypeEngine ( ContentTypeEngine engine ) { String contentType = engine . getContentType ( ) ; String suffix = StringUtils . removeStart ( contentType . substring ( contentType . lastIndexOf ( '/' ) + 1 ) , "x-" ) ; engines . put ( engine . getContentType ( ) , engine ) ; suffixes . put ( suffix . toLowerCase ( ) , engine ) ; log . debug ( "'{}' content engine is '{}'" , engine . getContentType ( ) , engine . getClass ( ) . getName ( ) ) ; }
|
Sets the engine for it s specified content type . An suffix for the engine is also registered based on the specific type ; extension types are supported and the leading x - is trimmed out .
|
40,272
|
public static < T > Collection < Class < ? extends T > > getSubTypesOf ( Class < T > type , String ... packageNames ) { List < Class < ? extends T > > classes = getClasses ( packageNames ) . stream ( ) . filter ( aClass -> type . isAssignableFrom ( aClass ) ) . map ( aClass -> ( Class < ? extends T > ) aClass ) . collect ( Collectors . toList ( ) ) ; return Collections . unmodifiableCollection ( classes ) ; }
|
Gets all sub types in hierarchy of a given type .
|
40,273
|
public static < T extends Annotation > T getAnnotation ( Method method , Class < T > annotationClass ) { T annotation = method . getAnnotation ( annotationClass ) ; if ( annotation == null ) { annotation = getAnnotation ( method . getDeclaringClass ( ) , annotationClass ) ; } return annotation ; }
|
Extract the annotation from the controllerMethod or the declaring class .
|
40,274
|
public static long copy ( InputStream input , OutputStream output ) throws IOException { byte [ ] buffer = new byte [ 2 * 1024 ] ; long total = 0 ; int count ; while ( ( count = input . read ( buffer ) ) != - 1 ) { output . write ( buffer , 0 , count ) ; total += count ; } return total ; }
|
Copies all data from an InputStream to an OutputStream .
|
40,275
|
public ParameterValue getParameter ( String name ) { if ( ! getParameters ( ) . containsKey ( name ) ) { return buildParameterValue ( ) ; } return getParameters ( ) . get ( name ) ; }
|
Returns one parameter value .
|
40,276
|
public ParameterValue getQueryParameter ( String name ) { if ( ! getQueryParameters ( ) . containsKey ( name ) ) { return buildParameterValue ( ) ; } return getQueryParameters ( ) . get ( name ) ; }
|
Returns one query parameter value .
|
40,277
|
public ParameterValue getPathParameter ( String name ) { if ( ! getPathParameters ( ) . containsKey ( name ) ) { return buildParameterValue ( ) ; } return getPathParameters ( ) . get ( name ) ; }
|
Returns one path parameter .
|
40,278
|
public String getApplicationUriWithQuery ( ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( getApplicationUri ( ) ) ; if ( getQuery ( ) != null ) { sb . append ( '?' ) . append ( getQuery ( ) ) ; } return sb . toString ( ) ; }
|
Returns the uri with the query string relative to the application root path .
|
40,279
|
private Properties loadProperties ( File baseDir , Properties currentProperties , String key , boolean override ) throws IOException { Properties loadedProperties = new Properties ( ) ; String include = ( String ) currentProperties . remove ( key ) ; if ( ! StringUtils . isNullOrEmpty ( include ) ) { List < String > names = StringUtils . getList ( include , DEFAULT_LIST_DELIMITER ) ; for ( String name : names ) { if ( StringUtils . isNullOrEmpty ( name ) ) { continue ; } final String fileName = interpolateString ( name ) ; File file = new File ( baseDir , fileName ) ; if ( ! file . exists ( ) ) { file = new File ( fileName ) ; } if ( ! file . exists ( ) ) { log . warn ( "failed to locate {}" , file ) ; continue ; } log . debug ( "loading {} settings from {}" , key , file ) ; try ( FileInputStream iis = new FileInputStream ( file ) ) { loadedProperties . load ( iis ) ; } loadedProperties = loadProperties ( file . getParentFile ( ) , loadedProperties , key , override ) ; } } Properties merged = new Properties ( ) ; if ( override ) { merged . putAll ( currentProperties ) ; merged . putAll ( loadedProperties ) ; } else { merged . putAll ( loadedProperties ) ; merged . putAll ( currentProperties ) ; } return merged ; }
|
Recursively read referenced properties files .
|
40,280
|
protected void addInterpolationValue ( String name , String value ) { interpolationValues . put ( String . format ( "${%s}" , name ) , value ) ; interpolationValues . put ( String . format ( "@{%s}" , name ) , value ) ; }
|
Add a value that may be interpolated .
|
40,281
|
protected String interpolateString ( String value ) { String interpolatedValue = value ; for ( Map . Entry < String , String > entry : interpolationValues . entrySet ( ) ) { interpolatedValue = interpolatedValue . replace ( entry . getKey ( ) , entry . getValue ( ) ) ; } return interpolatedValue ; }
|
Interpolates a string value using System properties and Environment variables .
|
40,282
|
public List < String > getSettingNames ( String startingWith ) { List < String > names = new ArrayList < > ( ) ; Properties props = getProperties ( ) ; if ( StringUtils . isNullOrEmpty ( startingWith ) ) { names . addAll ( props . stringPropertyNames ( ) ) ; } else { startingWith = startingWith . toLowerCase ( ) ; for ( Object o : props . keySet ( ) ) { String name = o . toString ( ) ; if ( name . toLowerCase ( ) . startsWith ( startingWith ) ) { names . add ( name ) ; } } } return names ; }
|
Returns the list of settings whose name starts with the specified prefix . If the prefix is null or empty all settings names are returned .
|
40,283
|
public String getString ( String name , String defaultValue ) { String value = getProperties ( ) . getProperty ( name , defaultValue ) ; value = overrides . getProperty ( name , value ) ; return value ; }
|
Returns the string value for the specified name . If the name does not exist or the value for the name can not be interpreted as a string the defaultValue is returned .
|
40,284
|
public boolean getBoolean ( String name , boolean defaultValue ) { String value = getString ( name , null ) ; if ( ! StringUtils . isNullOrEmpty ( value ) ) { return Boolean . parseBoolean ( value . trim ( ) ) ; } return defaultValue ; }
|
Returns the boolean value for the specified name . If the name does not exist or the value for the name can not be interpreted as a boolean the defaultValue is returned .
|
40,285
|
public int getInteger ( String name , int defaultValue ) { try { String value = getString ( name , null ) ; if ( ! StringUtils . isNullOrEmpty ( value ) ) { return Integer . parseInt ( value . trim ( ) ) ; } } catch ( NumberFormatException e ) { log . warn ( "Failed to parse integer for " + name + USING_DEFAULT_OF + defaultValue ) ; } return defaultValue ; }
|
Returns the integer value for the specified name . If the name does not exist or the value for the name can not be interpreted as an integer the defaultValue is returned .
|
40,286
|
public long getLong ( String name , long defaultValue ) { try { String value = getString ( name , null ) ; if ( ! StringUtils . isNullOrEmpty ( value ) ) { return Long . parseLong ( value . trim ( ) ) ; } } catch ( NumberFormatException e ) { log . warn ( "Failed to parse long for " + name + USING_DEFAULT_OF + defaultValue ) ; } return defaultValue ; }
|
Returns the long value for the specified name . If the name does not exist or the value for the name can not be interpreted as an long the defaultValue is returned .
|
40,287
|
public float getFloat ( String name , float defaultValue ) { try { String value = getString ( name , null ) ; if ( ! StringUtils . isNullOrEmpty ( value ) ) { return Float . parseFloat ( value . trim ( ) ) ; } } catch ( NumberFormatException e ) { log . warn ( "Failed to parse float for " + name + USING_DEFAULT_OF + defaultValue ) ; } return defaultValue ; }
|
Returns the float value for the specified name . If the name does not exist or the value for the name can not be interpreted as a float the defaultValue is returned .
|
40,288
|
public double getDouble ( String name , double defaultValue ) { try { String value = getString ( name , null ) ; if ( ! StringUtils . isNullOrEmpty ( value ) ) { return Double . parseDouble ( value . trim ( ) ) ; } } catch ( NumberFormatException e ) { log . warn ( "Failed to parse double for " + name + USING_DEFAULT_OF + defaultValue ) ; } return defaultValue ; }
|
Returns the double value for the specified name . If the name does not exist or the value for the name can not be interpreted as a double the defaultValue is returned .
|
40,289
|
public char getChar ( String name , char defaultValue ) { String value = getString ( name , null ) ; if ( ! StringUtils . isNullOrEmpty ( value ) ) { return value . trim ( ) . charAt ( 0 ) ; } return defaultValue ; }
|
Returns the char value for the specified name . If the name does not exist or the value for the name can not be interpreted as a char the defaultValue is returned .
|
40,290
|
public String getRequiredString ( String name ) { String value = getString ( name , null ) ; if ( value != null ) { return value . trim ( ) ; } throw new PippoRuntimeException ( "Setting '{}' has not been configured!" , name ) ; }
|
Returns the string value for the specified name . If the name does not exist an exception is thrown .
|
40,291
|
public List < String > getStrings ( String name , String delimiter ) { String value = getString ( name , null ) ; if ( StringUtils . isNullOrEmpty ( value ) ) { return Collections . emptyList ( ) ; } value = value . trim ( ) ; if ( value . startsWith ( "[" ) && value . endsWith ( "]" ) ) { value = value . substring ( 1 , value . length ( ) - 1 ) ; } return StringUtils . getList ( value , delimiter ) ; }
|
Returns a list of strings from the specified name using the specified delimiter .
|
40,292
|
public List < Integer > getIntegers ( String name , String delimiter ) { List < String > strings = getStrings ( name , delimiter ) ; List < Integer > ints = new ArrayList < > ( strings . size ( ) ) ; for ( String value : strings ) { try { int i = Integer . parseInt ( value ) ; ints . add ( i ) ; } catch ( NumberFormatException e ) { } } return Collections . unmodifiableList ( ints ) ; }
|
Returns a list of integers from the specified name using the specified delimiter .
|
40,293
|
public List < Long > getLongs ( String name , String delimiter ) { List < String > strings = getStrings ( name , delimiter ) ; List < Long > longs = new ArrayList < > ( strings . size ( ) ) ; for ( String value : strings ) { try { long i = Long . parseLong ( value ) ; longs . add ( i ) ; } catch ( NumberFormatException e ) { } } return Collections . unmodifiableList ( longs ) ; }
|
Returns a list of longs from the specified name using the specified delimiter .
|
40,294
|
public List < Float > getFloats ( String name , String delimiter ) { List < String > strings = getStrings ( name , delimiter ) ; List < Float > floats = new ArrayList < > ( strings . size ( ) ) ; for ( String value : strings ) { try { float i = Float . parseFloat ( value ) ; floats . add ( i ) ; } catch ( NumberFormatException e ) { } } return Collections . unmodifiableList ( floats ) ; }
|
Returns a list of floats from the specified name using the specified delimiter .
|
40,295
|
public List < Double > getDoubles ( String name , String delimiter ) { List < String > strings = getStrings ( name , delimiter ) ; List < Double > doubles = new ArrayList < > ( strings . size ( ) ) ; for ( String value : strings ) { try { double i = Double . parseDouble ( value ) ; doubles . add ( i ) ; } catch ( NumberFormatException e ) { } } return Collections . unmodifiableList ( doubles ) ; }
|
Returns a list of doubles from the specified name using the specified delimiter .
|
40,296
|
private TimeUnit extractTimeUnit ( String name , String defaultValue ) { String value = getString ( name , defaultValue ) ; try { final String [ ] s = value . split ( " " , 2 ) ; return TimeUnit . valueOf ( s [ 1 ] . trim ( ) . toUpperCase ( ) ) ; } catch ( Exception e ) { throw new PippoRuntimeException ( "{} must have format '<n> <TimeUnit>' where <TimeUnit> is one of 'MILLISECONDS', 'SECONDS', 'MINUTES', 'HOURS', 'DAYS'" , name ) ; } }
|
Extracts the TimeUnit from the name .
|
40,297
|
public static URL locateOnClasspath ( String resourceName ) { URL url = null ; ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( loader != null ) { url = loader . getResource ( resourceName ) ; if ( url != null ) { log . debug ( "Located '{}' in the context classpath" , resourceName ) ; } } if ( url == null ) { url = ClassLoader . getSystemResource ( resourceName ) ; if ( url != null ) { log . debug ( "Located '{}' in the system classpath" , resourceName ) ; } } return url ; }
|
Tries to find a resource with the given name in the classpath .
|
40,298
|
public static List < URL > getResources ( String name ) { List < URL > list = new ArrayList < > ( ) ; try { ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; Enumeration < URL > resources = loader . getResources ( name ) ; while ( resources . hasMoreElements ( ) ) { URL url = resources . nextElement ( ) ; list . add ( url ) ; } } catch ( IOException e ) { throw new PippoRuntimeException ( e ) ; } return list ; }
|
Return a list of resource URLs that match the given name .
|
40,299
|
private void registerDirectory ( Path dir ) throws IOException { Files . walkFileTree ( dir , new SimpleFileVisitor < Path > ( ) { public FileVisitResult preVisitDirectory ( Path dir , BasicFileAttributes attrs ) throws IOException { WatchKey key = dir . register ( watchService , ENTRY_CREATE , ENTRY_DELETE , ENTRY_MODIFY ) ; watchKeyToDirectory . put ( key , dir ) ; return FileVisitResult . CONTINUE ; } } ) ; }
|
Register the given directory and all its sub - directories .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.