idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
16,000 | @ Override public void close ( ) { synchronized ( this ) { if ( object != null ) { T object_ = object ; object = null ; try { finalizer . accept ( object_ ) ; } catch ( Exception e ) { // Ignored } } } } | Close the lazy factory and destroy the instance if created . | 56 | 11 |
16,001 | public ByteArrayQueue add ( byte [ ] b , int off , int len ) { int newLength = addLength ( len ) ; System . arraycopy ( b , off , array , offset + length , len ) ; length = newLength ; return this ; } | Adds a sequence of bytes into the tail of the queue . | 55 | 12 |
16,002 | public ByteArrayQueue add ( int b ) { int newLength = addLength ( 1 ) ; array [ offset + length ] = ( byte ) b ; length = newLength ; return this ; } | Adds one byte into the tail of the queue . | 41 | 10 |
16,003 | public ByteArrayQueue remove ( byte [ ] b , int off , int len ) { System . arraycopy ( array , offset , b , off , len ) ; return remove ( len ) ; } | Retrieves a sequence of bytes from the head of the queue . | 41 | 14 |
16,004 | public ByteArrayQueue remove ( int len ) { offset += len ; length -= len ; // Release buffer if empty if ( length == 0 && array . length > 1024 ) { array = new byte [ 32 ] ; offset = 0 ; shared = false ; } return this ; } | Removes a sequence of bytes from the head of the queue . | 57 | 13 |
16,005 | public List < String > escapePiecesForUri ( final List < String > pieces ) { final List < String > escapedPieces = new ArrayList <> ( pieces . size ( ) ) ; for ( final String piece : pieces ) { final String escaped = escapeForUri ( piece ) ; escapedPieces . add ( escaped ) ; } return escapedPieces ; } | Do a poor man s URI escaping . We aren t terribly interested in precision here or in introducing a library that would do it better . | 79 | 27 |
16,006 | public void addIds ( Collection < String > ids ) { if ( this . ids == null ) { this . ids = new ArrayList <> ( ids ) ; } else { this . ids . retainAll ( ids ) ; if ( this . ids . isEmpty ( ) ) { LOGGER . warn ( "No ids remain after addIds. All elements will be filtered out." ) ; } } } | When called the first time all ids are added to the filter . When called two or more times the provided id s are and ed with the those provided in the previous lists . | 94 | 36 |
16,007 | private static void forceInit ( Class < ? > cls ) { try { Class . forName ( cls . getName ( ) , true , cls . getClassLoader ( ) ) ; } catch ( ClassNotFoundException e ) { throw new IllegalArgumentException ( "Can't initialize class " + cls , e ) ; } } | Force initialization of the static members . As of Java 5 referencing a class doesn t force it to initialize . Since this class requires that the classes be initialized to declare their comparators we force that initialization to happen . | 73 | 42 |
16,008 | public static int readInt ( byte [ ] bytes , int start ) { return ( ( ( bytes [ start ] & 0xff ) << 24 ) + ( ( bytes [ start + 1 ] & 0xff ) << 16 ) + ( ( bytes [ start + 2 ] & 0xff ) << 8 ) + ( ( bytes [ start + 3 ] & 0xff ) ) ) ; } | Parse an integer from a byte array . | 79 | 9 |
16,009 | public static long readLong ( byte [ ] bytes , int start ) { return ( ( long ) ( readInt ( bytes , start ) ) << 32 ) + ( readInt ( bytes , start + 4 ) & 0xFFFFFFFF L ) ; } | Parse a long from a byte array . | 52 | 9 |
16,010 | public static long readVLong ( byte [ ] bytes , int start ) throws IOException { int len = bytes [ start ] ; if ( len >= - 112 ) { return len ; } boolean isNegative = ( len < - 120 ) ; len = isNegative ? - ( len + 120 ) : - ( len + 112 ) ; if ( start + 1 + len > bytes . length ) { throw new IOException ( "Not enough number of bytes for a zero-compressed integer" ) ; } long i = 0 ; for ( int idx = 0 ; idx < len ; idx ++ ) { i = i << 8 ; i = i | ( bytes [ start + 1 + idx ] & 0xFF ) ; } return ( isNegative ? ( i ^ - 1L ) : i ) ; } | Reads a zero - compressed encoded long from a byte array and returns it . | 174 | 16 |
16,011 | public static String getVertexId ( Value value ) { byte [ ] buffer = value . get ( ) ; int offset = 0 ; // skip label int strLen = readInt ( buffer , offset ) ; offset += 4 ; if ( strLen > 0 ) { offset += strLen ; } strLen = readInt ( buffer , offset ) ; return readString ( buffer , offset , strLen ) ; } | fast access method to avoid creating a new instance of an EdgeInfo | 85 | 13 |
16,012 | public static < T > boolean intersectsAll ( T [ ] a1 , T [ ] a2 ) { for ( T anA1 : a1 ) { if ( ! contains ( a2 , anA1 ) ) { return false ; } } for ( T anA2 : a2 ) { if ( ! contains ( a1 , anA2 ) ) { return false ; } } return true ; } | Determines if all values in a1 appear in a2 and that all values in a2 appear in a2 . | 87 | 25 |
16,013 | public static byte [ ] decode ( String chars ) { if ( chars == null || chars . length ( ) == 0 ) { throw new IllegalArgumentException ( "You must provide a non-zero length input" ) ; } //By using five ASCII characters to represent four bytes of binary data the encoded size ¹⁄₄ is larger than the original BigDecimal decodedLength = BigDecimal . valueOf ( chars . length ( ) ) . multiply ( BigDecimal . valueOf ( 4 ) ) . divide ( BigDecimal . valueOf ( 5 ) ) ; ByteBuffer bytebuff = ByteBuffer . allocate ( decodedLength . intValue ( ) ) ; //1. Whitespace characters may occur anywhere to accommodate line length limitations. So lets strip it. chars = REMOVE_WHITESPACE . matcher ( chars ) . replaceAll ( "" ) ; //Since Base85 is an ascii encoder, we don't need to get the bytes as UTF-8. byte [ ] payload = chars . getBytes ( StandardCharsets . US_ASCII ) ; byte [ ] chunk = new byte [ 5 ] ; int chunkIndex = 0 ; for ( int i = 0 ; i < payload . length ; i ++ ) { byte currByte = payload [ i ] ; //Because all-zero data is quite common, an exception is made for the sake of data compression, //and an all-zero group is encoded as a single character "z" instead of "!!!!!". if ( currByte == ' ' ) { if ( chunkIndex > 0 ) { throw new IllegalArgumentException ( "The payload is not base 85 encoded." ) ; } chunk [ chunkIndex ++ ] = ' ' ; chunk [ chunkIndex ++ ] = ' ' ; chunk [ chunkIndex ++ ] = ' ' ; chunk [ chunkIndex ++ ] = ' ' ; chunk [ chunkIndex ++ ] = ' ' ; } else { chunk [ chunkIndex ++ ] = currByte ; } if ( chunkIndex == 5 ) { bytebuff . put ( decodeChunk ( chunk ) ) ; Arrays . fill ( chunk , ( byte ) 0 ) ; chunkIndex = 0 ; } } //If we didn't end on 0, then we need some padding if ( chunkIndex > 0 ) { int numPadded = chunk . length - chunkIndex ; Arrays . fill ( chunk , chunkIndex , chunk . length , ( byte ) ' ' ) ; byte [ ] paddedDecode = decodeChunk ( chunk ) ; for ( int i = 0 ; i < paddedDecode . length - numPadded ; i ++ ) { bytebuff . put ( paddedDecode [ i ] ) ; } } bytebuff . flip ( ) ; return Arrays . copyOf ( bytebuff . array ( ) , bytebuff . limit ( ) ) ; } | This is a very simple base85 decoder . It respects the z optimization for empty chunks and strips whitespace between characters to respect line limits . | 598 | 29 |
16,014 | public int compareTo ( ByteSequence obs ) { if ( isBackedByArray ( ) && obs . isBackedByArray ( ) ) { return WritableComparator . compareBytes ( getBackingArray ( ) , offset ( ) , length ( ) , obs . getBackingArray ( ) , obs . offset ( ) , obs . length ( ) ) ; } return compareBytes ( this , obs ) ; } | Compares this byte sequence to another . | 89 | 8 |
16,015 | public static GeoPoint calculateCenter ( List < GeoPoint > geoPoints ) { checkNotNull ( geoPoints , "geoPoints cannot be null" ) ; checkArgument ( geoPoints . size ( ) > 0 , "must have at least 1 geoPoints" ) ; if ( geoPoints . size ( ) == 1 ) { return geoPoints . get ( 0 ) ; } double x = 0.0 ; double y = 0.0 ; double z = 0.0 ; double totalAlt = 0.0 ; int altitudeCount = 0 ; for ( GeoPoint geoPoint : geoPoints ) { double latRad = Math . toRadians ( geoPoint . getLatitude ( ) ) ; double lonRad = Math . toRadians ( geoPoint . getLongitude ( ) ) ; x += Math . cos ( latRad ) * Math . cos ( lonRad ) ; y += Math . cos ( latRad ) * Math . sin ( lonRad ) ; z += Math . sin ( latRad ) ; if ( geoPoint . getAltitude ( ) != null ) { totalAlt += geoPoint . getAltitude ( ) ; altitudeCount ++ ; } } x = x / ( double ) geoPoints . size ( ) ; y = y / ( double ) geoPoints . size ( ) ; z = z / ( double ) geoPoints . size ( ) ; return new GeoPoint ( Math . toDegrees ( Math . atan2 ( z , Math . sqrt ( x * x + y * y ) ) ) , Math . toDegrees ( Math . atan2 ( y , x ) ) , altitudeCount == geoPoints . size ( ) ? ( totalAlt / ( double ) altitudeCount ) : null ) ; } | For large distances center point calculation has rounding errors | 368 | 9 |
16,016 | public static byte [ ] escape ( byte [ ] auth , boolean quote ) { int escapeCount = 0 ; for ( int i = 0 ; i < auth . length ; i ++ ) { if ( auth [ i ] == ' ' || auth [ i ] == ' ' ) { escapeCount ++ ; } } if ( escapeCount > 0 || quote ) { byte [ ] escapedAuth = new byte [ auth . length + escapeCount + ( quote ? 2 : 0 ) ] ; int index = quote ? 1 : 0 ; for ( int i = 0 ; i < auth . length ; i ++ ) { if ( auth [ i ] == ' ' || auth [ i ] == ' ' ) { escapedAuth [ index ++ ] = ' ' ; } escapedAuth [ index ++ ] = auth [ i ] ; } if ( quote ) { escapedAuth [ 0 ] = ' ' ; escapedAuth [ escapedAuth . length - 1 ] = ' ' ; } auth = escapedAuth ; } return auth ; } | Properly escapes an authorization string . The string can be quoted if desired . | 207 | 16 |
16,017 | public static byte [ ] quote ( byte [ ] term ) { boolean needsQuote = false ; for ( int i = 0 ; i < term . length ; i ++ ) { if ( ! Authorizations . isValidAuthChar ( term [ i ] ) ) { needsQuote = true ; break ; } } if ( ! needsQuote ) { return term ; } return VisibilityEvaluator . escape ( term , true ) ; } | Properly quotes terms in a column visibility expression . If no quoting is needed then nothing is done . | 90 | 21 |
16,018 | public static int hash32 ( byte [ ] data , int length , int seed ) { int hash = seed ; final int nblocks = length >> 2 ; // body for ( int i = 0 ; i < nblocks ; i ++ ) { int i_4 = i << 2 ; int k = ( data [ i_4 ] & 0xff ) | ( ( data [ i_4 + 1 ] & 0xff ) << 8 ) | ( ( data [ i_4 + 2 ] & 0xff ) << 16 ) | ( ( data [ i_4 + 3 ] & 0xff ) << 24 ) ; // mix functions k *= C1_32 ; k = Integer . rotateLeft ( k , R1_32 ) ; k *= C2_32 ; hash ^= k ; hash = Integer . rotateLeft ( hash , R2_32 ) * M_32 + N_32 ; } // tail int idx = nblocks << 2 ; int k1 = 0 ; switch ( length - idx ) { case 3 : k1 ^= data [ idx + 2 ] << 16 ; case 2 : k1 ^= data [ idx + 1 ] << 8 ; case 1 : k1 ^= data [ idx ] ; // mix functions k1 *= C1_32 ; k1 = Integer . rotateLeft ( k1 , R1_32 ) ; k1 *= C2_32 ; hash ^= k1 ; } // finalization hash ^= length ; hash ^= ( hash >>> 16 ) ; hash *= 0x85ebca6b ; hash ^= ( hash >>> 13 ) ; hash *= 0xc2b2ae35 ; hash ^= ( hash >>> 16 ) ; return hash ; } | Murmur3 32 - bit variant . | 369 | 8 |
16,019 | public static long hash64 ( byte [ ] data , int offset , int length , int seed ) { long hash = seed ; final int nblocks = length >> 3 ; // body for ( int i = 0 ; i < nblocks ; i ++ ) { final int i8 = i << 3 ; long k = ( ( long ) data [ offset + i8 ] & 0xff ) | ( ( ( long ) data [ offset + i8 + 1 ] & 0xff ) << 8 ) | ( ( ( long ) data [ offset + i8 + 2 ] & 0xff ) << 16 ) | ( ( ( long ) data [ offset + i8 + 3 ] & 0xff ) << 24 ) | ( ( ( long ) data [ offset + i8 + 4 ] & 0xff ) << 32 ) | ( ( ( long ) data [ offset + i8 + 5 ] & 0xff ) << 40 ) | ( ( ( long ) data [ offset + i8 + 6 ] & 0xff ) << 48 ) | ( ( ( long ) data [ offset + i8 + 7 ] & 0xff ) << 56 ) ; // mix functions k *= C1 ; k = Long . rotateLeft ( k , R1 ) ; k *= C2 ; hash ^= k ; hash = Long . rotateLeft ( hash , R2 ) * M + N1 ; } // tail long k1 = 0 ; int tailStart = nblocks << 3 ; switch ( length - tailStart ) { case 7 : k1 ^= ( ( long ) data [ offset + tailStart + 6 ] & 0xff ) << 48 ; case 6 : k1 ^= ( ( long ) data [ offset + tailStart + 5 ] & 0xff ) << 40 ; case 5 : k1 ^= ( ( long ) data [ offset + tailStart + 4 ] & 0xff ) << 32 ; case 4 : k1 ^= ( ( long ) data [ offset + tailStart + 3 ] & 0xff ) << 24 ; case 3 : k1 ^= ( ( long ) data [ offset + tailStart + 2 ] & 0xff ) << 16 ; case 2 : k1 ^= ( ( long ) data [ offset + tailStart + 1 ] & 0xff ) << 8 ; case 1 : k1 ^= ( ( long ) data [ offset + tailStart ] & 0xff ) ; k1 *= C1 ; k1 = Long . rotateLeft ( k1 , R1 ) ; k1 *= C2 ; hash ^= k1 ; } // finalization hash ^= length ; hash = fmix64 ( hash ) ; return hash ; } | Murmur3 64 - bit variant . This is essentially MSB 8 bytes of Murmur3 128 - bit variant . | 554 | 24 |
16,020 | protected boolean hasValidFile ( Artifact artifact ) { // Make sure the file exists. boolean hasValidFile = artifact != null && artifact . getFile ( ) != null && artifact . getFile ( ) . exists ( ) ; // Exclude project POM file. hasValidFile = hasValidFile && ! artifact . getFile ( ) . getPath ( ) . equals ( project . getFile ( ) . getPath ( ) ) ; // Exclude files outside of build directory. hasValidFile = hasValidFile && artifact . getFile ( ) . getPath ( ) . startsWith ( project . getBuild ( ) . getDirectory ( ) ) ; return hasValidFile ; } | Decide whether the artifact file should be processed . | 141 | 10 |
16,021 | private Map < String , Map < String , String > > readSummaryFile ( File outputFile ) throws ExecutionException { List < String > algorithms = new ArrayList < String > ( ) ; Map < String , Map < String , String > > filesHashcodes = new HashMap < String , Map < String , String > > ( ) ; BufferedReader reader = null ; try { reader = new BufferedReader ( new FileReader ( outputFile ) ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { // Read the CVS file header if ( isFileHeader ( line ) ) { readFileHeader ( line , algorithms ) ; } else { // Read the dependencies checksums readDependenciesChecksums ( line , algorithms , filesHashcodes ) ; } } } catch ( IOException e ) { throw new ExecutionException ( e . getMessage ( ) ) ; } finally { IOUtil . close ( reader ) ; } return filesHashcodes ; } | Read the summary file | 208 | 4 |
16,022 | private void sync ( final DirContext ctx , final AlpineQueryManager qm , final LdapConnectionWrapper ldap , LdapUser user ) throws NamingException { LOGGER . debug ( "Syncing: " + user . getUsername ( ) ) ; final SearchResult result = ldap . searchForSingleUsername ( ctx , user . getUsername ( ) ) ; if ( result != null ) { user . setDN ( result . getNameInNamespace ( ) ) ; user . setEmail ( ldap . getAttribute ( result , LdapConnectionWrapper . ATTRIBUTE_MAIL ) ) ; user = qm . updateLdapUser ( user ) ; // Dynamically assign team membership (if enabled) if ( LdapConnectionWrapper . TEAM_SYNCHRONIZATION ) { final List < String > groupDNs = ldap . getGroups ( ctx , user ) ; qm . synchronizeTeamMembership ( user , groupDNs ) ; } } else { // This is an invalid user - a username that exists in the database that does not exist in LDAP user . setDN ( "INVALID" ) ; user . setEmail ( null ) ; user = qm . updateLdapUser ( user ) ; if ( LdapConnectionWrapper . TEAM_SYNCHRONIZATION ) { qm . synchronizeTeamMembership ( user , new ArrayList <> ( ) ) ; } } } | Performs the actual sync of the specified user . | 323 | 10 |
16,023 | public static int determineNumberOfWorkerThreads ( ) { final int threads = Config . getInstance ( ) . getPropertyAsInt ( Config . AlpineKey . WORKER_THREADS ) ; if ( threads > 0 ) { return threads ; } else if ( threads == 0 ) { final int cores = SystemUtil . getCpuCores ( ) ; final int multiplier = Config . getInstance ( ) . getPropertyAsInt ( Config . AlpineKey . WORKER_THREAD_MULTIPLIER ) ; if ( multiplier > 0 ) { return cores * multiplier ; } else { return cores ; } } return 1 ; // We have to have a minimum of 1 thread } | Calculates the number of worker threads to use . Minimum return value is 1 . | 145 | 17 |
16,024 | @ SafeVarargs protected final List < ValidationError > contOnValidationError ( final Set < ConstraintViolation < Object > > ... violationsArray ) { final List < ValidationError > errors = new ArrayList <> ( ) ; for ( final Set < ConstraintViolation < Object > > violations : violationsArray ) { for ( final ConstraintViolation violation : violations ) { if ( violation . getPropertyPath ( ) . iterator ( ) . next ( ) . getName ( ) != null ) { final String path = violation . getPropertyPath ( ) != null ? violation . getPropertyPath ( ) . toString ( ) : null ; final String message = violation . getMessage ( ) != null ? StringUtils . removeStart ( violation . getMessage ( ) , path + "." ) : null ; final String messageTemplate = violation . getMessageTemplate ( ) ; final String invalidValue = violation . getInvalidValue ( ) != null ? violation . getInvalidValue ( ) . toString ( ) : null ; final ValidationError error = new ValidationError ( message , messageTemplate , path , invalidValue ) ; errors . add ( error ) ; } } } return errors ; } | Accepts the result from one of the many validation methods available and returns a List of ValidationErrors . If the size of the List is 0 no errors were encounter during validation . | 254 | 37 |
16,025 | protected final List < ValidationException > contOnValidationError ( final ValidationTask ... validationTasks ) { final List < ValidationException > errors = new ArrayList <> ( ) ; for ( final ValidationTask validationTask : validationTasks ) { if ( ! validationTask . isRequired ( ) && validationTask . getInput ( ) == null ) { continue ; } if ( ! validationTask . getPattern ( ) . matcher ( validationTask . getInput ( ) ) . matches ( ) ) { errors . add ( new ValidationException ( validationTask . getInput ( ) , validationTask . getErrorMessage ( ) ) ) ; } } return errors ; } | Given one or mote ValidationTasks this method will return a List of ValidationErrors . If the size of the List is 0 no errors were encountered during validation . | 142 | 36 |
16,026 | @ PostConstruct private void initialize ( ) { final MultivaluedMap < String , String > queryParams = uriInfo . getQueryParameters ( ) ; final String offset = multiParam ( queryParams , "offset" ) ; final String page = multiParam ( queryParams , "page" , "pageNumber" ) ; final String size = multiParam ( queryParams , "size" , "pageSize" , "limit" ) ; final String filter = multiParam ( queryParams , "filter" , "searchText" ) ; final String sort = multiParam ( queryParams , "sort" , "sortOrder" ) ; final OrderDirection orderDirection ; String orderBy = multiParam ( queryParams , "orderBy" , "sortName" ) ; if ( StringUtils . isBlank ( orderBy ) || ! RegexSequence . Pattern . ALPHA_NUMERIC . matcher ( orderBy ) . matches ( ) ) { orderBy = null ; } if ( "asc" . equalsIgnoreCase ( sort ) ) { orderDirection = OrderDirection . ASCENDING ; } else if ( "desc" . equalsIgnoreCase ( sort ) ) { orderDirection = OrderDirection . DESCENDING ; } else { orderDirection = OrderDirection . UNSPECIFIED ; } final Pagination pagination ; if ( StringUtils . isNotBlank ( offset ) ) { pagination = new Pagination ( Pagination . Strategy . OFFSET , offset , size ) ; } else if ( StringUtils . isNotBlank ( page ) && StringUtils . isNotBlank ( size ) ) { pagination = new Pagination ( Pagination . Strategy . PAGES , page , size ) ; } else { pagination = new Pagination ( Pagination . Strategy . OFFSET , 0 , 100 ) ; // Always paginate queries from resources } this . alpineRequest = new AlpineRequest ( getPrincipal ( ) , pagination , filter , orderBy , orderDirection ) ; } | Initializes this resource instance by populating some of the features of this class | 440 | 15 |
16,027 | protected Principal getPrincipal ( ) { final Object principal = requestContext . getProperty ( "Principal" ) ; if ( principal != null ) { return ( Principal ) principal ; } else { return null ; } } | Returns the principal for who initiated the request . | 45 | 9 |
16,028 | protected boolean hasPermission ( final String permission ) { if ( getPrincipal ( ) == null ) { return false ; } try ( AlpineQueryManager qm = new AlpineQueryManager ( ) ) { boolean hasPermission = false ; if ( getPrincipal ( ) instanceof ApiKey ) { hasPermission = qm . hasPermission ( ( ApiKey ) getPrincipal ( ) , permission ) ; } else if ( getPrincipal ( ) instanceof UserPrincipal ) { hasPermission = qm . hasPermission ( ( UserPrincipal ) getPrincipal ( ) , permission , true ) ; } return hasPermission ; } } | Convenience method that returns true if the principal has the specified permission or false if not . | 139 | 19 |
16,029 | public static boolean matches ( final char [ ] assertedPassword , final ManagedUser user ) { final char [ ] prehash = createSha512Hash ( assertedPassword ) ; // Todo: remove String when Jbcrypt supports char[] return BCrypt . checkpw ( new String ( prehash ) , user . getPassword ( ) ) ; } | Checks the validity of the asserted password against a ManagedUsers actual hashed password . | 73 | 18 |
16,030 | private static char [ ] createSha512Hash ( final char [ ] password ) { try { final MessageDigest digest = MessageDigest . getInstance ( "SHA-512" ) ; digest . update ( ByteUtil . toBytes ( password ) ) ; final byte [ ] byteData = digest . digest ( ) ; final StringBuilder sb = new StringBuilder ( ) ; for ( final byte data : byteData ) { sb . append ( Integer . toString ( ( data & 0xff ) + 0x100 , 16 ) . substring ( 1 ) ) ; } final char [ ] hash = new char [ 128 ] ; sb . getChars ( 0 , sb . length ( ) , hash , 0 ) ; return hash ; } catch ( NoSuchAlgorithmException e ) { throw new UnsupportedOperationException ( e ) ; } } | Creates a SHA - 512 hash of the specified password and returns a HEX representation of the hash . This method should NOT be used solely for password hashing but in conjunction with password - specific hashing functions . | 181 | 41 |
16,031 | public void init ( final FilterConfig filterConfig ) { final String host = filterConfig . getInitParameter ( "host" ) ; if ( StringUtils . isNotBlank ( host ) ) { this . host = host ; } } | Initialize host parameter from web . xml . | 50 | 9 |
16,032 | private void startDbServer ( ) { final String mode = Config . getInstance ( ) . getProperty ( Config . AlpineKey . DATABASE_MODE ) ; final int port = Config . getInstance ( ) . getPropertyAsInt ( Config . AlpineKey . DATABASE_PORT ) ; if ( StringUtils . isEmpty ( mode ) || ! ( "server" . equals ( mode ) || "embedded" . equals ( mode ) || "external" . equals ( mode ) ) ) { LOGGER . error ( "Database mode not specified. Expected values are 'server', 'embedded', or 'external'" ) ; } if ( dbServer != null || "embedded" . equals ( mode ) || "external" . equals ( mode ) ) { return ; } final String [ ] args = new String [ ] { "-tcp" , "-tcpPort" , String . valueOf ( port ) , "-tcpAllowOthers" , } ; try { LOGGER . info ( "Attempting to start database service" ) ; dbServer = Server . createTcpServer ( args ) . start ( ) ; LOGGER . info ( "Database service started" ) ; } catch ( SQLException e ) { LOGGER . error ( "Unable to start database service: " + e . getMessage ( ) ) ; stopDbServer ( ) ; } } | Starts the H2 database engine if the database mode is set to server | 293 | 15 |
16,033 | private void init ( ) { if ( properties != null ) { return ; } LOGGER . info ( "Initializing Configuration" ) ; properties = new Properties ( ) ; final String alpineAppProp = PathUtil . resolve ( System . getProperty ( ALPINE_APP_PROP ) ) ; if ( StringUtils . isNotBlank ( alpineAppProp ) ) { LOGGER . info ( "Loading application properties from " + alpineAppProp ) ; try ( InputStream fileInputStream = Files . newInputStream ( ( new File ( alpineAppProp ) ) . toPath ( ) ) ) { properties . load ( fileInputStream ) ; } catch ( FileNotFoundException e ) { LOGGER . error ( "Could not find property file " + alpineAppProp ) ; } catch ( IOException e ) { LOGGER . error ( "Unable to load " + alpineAppProp ) ; } } else { LOGGER . info ( "System property " + ALPINE_APP_PROP + " not specified" ) ; LOGGER . info ( "Loading " + PROP_FILE + " from classpath" ) ; try ( InputStream in = Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( PROP_FILE ) ) { properties . load ( in ) ; } catch ( IOException e ) { LOGGER . error ( "Unable to load " + PROP_FILE ) ; } } if ( properties . size ( ) == 0 ) { LOGGER . error ( "A fatal error occurred loading application properties. Please correct the issue and restart the application." ) ; } alpineVersionProperties = new Properties ( ) ; try ( InputStream in = Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( ALPINE_VERSION_PROP_FILE ) ) { alpineVersionProperties . load ( in ) ; } catch ( IOException e ) { LOGGER . error ( "Unable to load " + ALPINE_VERSION_PROP_FILE ) ; } if ( alpineVersionProperties . size ( ) == 0 ) { LOGGER . error ( "A fatal error occurred loading Alpine version information. Please correct the issue and restart the application." ) ; } applicationVersionProperties = new Properties ( ) ; try ( InputStream in = Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( APPLICATION_VERSION_PROP_FILE ) ) { applicationVersionProperties . load ( in ) ; } catch ( IOException e ) { LOGGER . error ( "Unable to load " + APPLICATION_VERSION_PROP_FILE ) ; } if ( applicationVersionProperties . size ( ) == 0 ) { LOGGER . error ( "A fatal error occurred loading application version information. Please correct the issue and restart the application." ) ; } } | Initialize the Config object . This method should only be called once . | 612 | 14 |
16,034 | private String getPropertyFromEnvironment ( Key key ) { final String envVariable = key . getPropertyName ( ) . toUpperCase ( ) . replace ( "." , "_" ) ; try { return StringUtils . trimToNull ( System . getenv ( envVariable ) ) ; } catch ( SecurityException e ) { LOGGER . warn ( "A security exception prevented access to the environment variable. Using defaults." ) ; } catch ( NullPointerException e ) { // Do nothing. The key was not specified in an environment variable. Continue along. } return null ; } | Attempts to retrieve the key via environment variable . Property names are always upper case with periods replaced with underscores . | 122 | 21 |
16,035 | public boolean hasUpgradeRan ( final Class < ? extends UpgradeItem > upgradeClass ) throws SQLException { PreparedStatement statement = null ; ResultSet results = null ; try { statement = connection . prepareStatement ( "SELECT \"UPGRADECLASS\" FROM \"INSTALLEDUPGRADES\" WHERE \"UPGRADECLASS\" = ?" ) ; statement . setString ( 1 , upgradeClass . getCanonicalName ( ) ) ; results = statement . executeQuery ( ) ; return results . next ( ) ; } finally { DbUtil . close ( results ) ; DbUtil . close ( statement ) ; //DbUtil.close(connection); // do not close connection } } | Determines if the specified upgrade already has a record of being executed previously or not . | 157 | 18 |
16,036 | public void installUpgrade ( final Class < ? extends UpgradeItem > upgradeClass , final long startTime , final long endTime ) throws SQLException { PreparedStatement statement = null ; try { statement = connection . prepareStatement ( "INSERT INTO \"INSTALLEDUPGRADES\" (\"UPGRADECLASS\", \"STARTTIME\", \"ENDTIME\") VALUES (?, ?, ?)" ) ; statement . setString ( 1 , upgradeClass . getCanonicalName ( ) ) ; statement . setTimestamp ( 2 , new Timestamp ( startTime ) ) ; statement . setTimestamp ( 3 , new Timestamp ( endTime ) ) ; statement . executeUpdate ( ) ; connection . commit ( ) ; LOGGER . debug ( "Added: " + upgradeClass . getCanonicalName ( ) + " to UpgradeMetaProcessor table (Starttime: " + startTime + "; Endtime: " + endTime + ")" ) ; } finally { DbUtil . close ( statement ) ; //DbUtil.close(connection); // do not close connection } } | Documents a record in the database for the specified class indicating it has been executed . | 237 | 16 |
16,037 | public VersionComparator getSchemaVersion ( ) { PreparedStatement statement = null ; ResultSet results = null ; try { statement = connection . prepareStatement ( "SELECT \"VERSION\" FROM \"SCHEMAVERSION\"" ) ; results = statement . executeQuery ( ) ; if ( results . next ( ) ) { return new VersionComparator ( results . getString ( 1 ) ) ; } } catch ( SQLException e ) { // throw it away } finally { DbUtil . close ( results ) ; DbUtil . close ( statement ) ; //DbUtil.close(connection); // do not close connection } return null ; } | Retrieves the current schema version documented in the database . | 140 | 12 |
16,038 | public void updateSchemaVersion ( VersionComparator version ) throws SQLException { PreparedStatement statement = null ; PreparedStatement updateStatement = null ; ResultSet results = null ; try { statement = connection . prepareStatement ( "SELECT \"VERSION\" FROM \"SCHEMAVERSION\"" ) ; results = statement . executeQuery ( ) ; if ( results . next ( ) ) { final VersionComparator currentVersion = new VersionComparator ( results . getString ( 1 ) ) ; if ( version == null || currentVersion . isNewerThan ( version ) ) { return ; } updateStatement = connection . prepareStatement ( "UPDATE \"SCHEMAVERSION\" SET \"VERSION\" = ?" ) ; } else { // Does not exist. Populate schema table with current running version version = new VersionComparator ( Config . getInstance ( ) . getApplicationVersion ( ) ) ; updateStatement = connection . prepareStatement ( "INSERT INTO \"SCHEMAVERSION\" (\"VERSION\") VALUES (?)" ) ; } LOGGER . debug ( "Updating database schema to: " + version . toString ( ) ) ; updateStatement . setString ( 1 , version . toString ( ) ) ; updateStatement . executeUpdate ( ) ; connection . commit ( ) ; } finally { DbUtil . close ( results ) ; DbUtil . close ( updateStatement ) ; DbUtil . close ( statement ) ; //DbUtil.close(connection); // do not close connection } } | Updates the schema version in the database . | 325 | 9 |
16,039 | private String getValue ( FilterConfig filterConfig , String initParam , String variable ) { final String value = filterConfig . getInitParameter ( initParam ) ; if ( StringUtils . isNotBlank ( value ) ) { return value ; } else { return variable ; } } | Returns the value of the initParam . | 59 | 8 |
16,040 | private String formatHeader ( ) { final StringBuilder sb = new StringBuilder ( ) ; getStringFromValue ( sb , "default-src" , defaultSrc ) ; getStringFromValue ( sb , "script-src" , scriptSrc ) ; getStringFromValue ( sb , "style-src" , styleSrc ) ; getStringFromValue ( sb , "img-src" , imgSrc ) ; getStringFromValue ( sb , "connect-src" , connectSrc ) ; getStringFromValue ( sb , "font-src" , fontSrc ) ; getStringFromValue ( sb , "object-src" , objectSrc ) ; getStringFromValue ( sb , "media-src" , mediaSrc ) ; getStringFromValue ( sb , "frame-src" , frameSrc ) ; getStringFromValue ( sb , "sandbox" , sandbox ) ; getStringFromValue ( sb , "report-uri" , reportUri ) ; getStringFromValue ( sb , "child-src" , childSrc ) ; getStringFromValue ( sb , "form-action" , formAction ) ; getStringFromValue ( sb , "frame-ancestors" , frameAncestors ) ; getStringFromValue ( sb , "plugin-types" , pluginTypes ) ; return sb . toString ( ) . replaceAll ( "(\\[|\\])" , "" ) . trim ( ) ; } | Formats a CSP header | 330 | 6 |
16,041 | private void getStringFromValue ( final StringBuilder builder , final String directive , final String value ) { if ( value != null ) { builder . append ( directive ) . append ( " " ) . append ( value ) . append ( ";" ) ; } } | Assists in the formatting of a single CSP directive . | 54 | 12 |
16,042 | public Principal authenticate ( ) throws AlpineAuthenticationException { LOGGER . debug ( "Attempting to authenticate user: " + username ) ; final ManagedUserAuthenticationService userService = new ManagedUserAuthenticationService ( username , password ) ; try { final Principal principal = userService . authenticate ( ) ; if ( principal != null ) { return principal ; } } catch ( AlpineAuthenticationException e ) { // If LDAP is enabled, a second attempt to authenticate the credentials will be // made against LDAP so we skip this validation exception. However, if the ManagedUser does exist, // return the correct error if ( ! LDAP_ENABLED || e . getCauseType ( ) != AlpineAuthenticationException . CauseType . INVALID_CREDENTIALS ) { throw e ; } } if ( LDAP_ENABLED ) { final LdapAuthenticationService ldapService = new LdapAuthenticationService ( username , password ) ; return ldapService . authenticate ( ) ; } // This should never happen, but do not want to return null throw new AlpineAuthenticationException ( AlpineAuthenticationException . CauseType . OTHER ) ; } | Attempts to authenticate the credentials internally first and if not successful checks to see if LDAP is enabled or not . If enabled a second attempt to authenticate the credentials will be made but this time against the directory service . | 253 | 44 |
16,043 | private static void init ( ) { if ( hasInitialized ) { return ; } final String osName = System . getProperty ( "os.name" ) ; if ( osName != null ) { final String osNameLower = osName . toLowerCase ( ) ; isWindows = osNameLower . contains ( "windows" ) ; isMac = osNameLower . contains ( "mac os x" ) || osNameLower . contains ( "darwin" ) ; isLinux = osNameLower . contains ( "nux" ) ; isUnix = osNameLower . contains ( "nix" ) || osNameLower . contains ( "nux" ) ; isSolaris = osNameLower . contains ( "sunos" ) || osNameLower . contains ( "solaris" ) ; } lineEnder = isWindows ? "\r\n" : "\n" ; final String model = System . getProperty ( "sun.arch.data.model" ) ; // sun.arch.data.model=32 // 32 bit JVM // sun.arch.data.model=64 // 64 bit JVM if ( StringUtils . isBlank ( model ) ) { bit32 = true ; bit64 = false ; } else if ( "64" . equals ( model ) ) { bit32 = false ; bit64 = true ; } else { bit32 = true ; bit64 = false ; } } | Initialize static variables . | 300 | 5 |
16,044 | public void advancePagination ( ) { if ( pagination . isPaginated ( ) ) { pagination = new Pagination ( pagination . getStrategy ( ) , pagination . getOffset ( ) + pagination . getLimit ( ) , pagination . getLimit ( ) ) ; } } | Advances the pagination based on the previous pagination settings . This is purely a convenience method as the method by itself is not aware of the query being executed the result count etc . | 65 | 37 |
16,045 | public Query decorate ( final Query query ) { // Clear the result to fetch if previously specified (i.e. by getting count) query . setResult ( null ) ; if ( pagination != null && pagination . isPaginated ( ) ) { final long begin = pagination . getOffset ( ) ; final long end = begin + pagination . getLimit ( ) ; query . setRange ( begin , end ) ; } if ( orderBy != null && RegexSequence . Pattern . ALPHA_NUMERIC . matcher ( orderBy ) . matches ( ) && orderDirection != OrderDirection . UNSPECIFIED ) { // Check to see if the specified orderBy field is defined in the class being queried. boolean found = false ; final org . datanucleus . store . query . Query iq = ( ( JDOQuery ) query ) . getInternalQuery ( ) ; for ( final Field field : iq . getCandidateClass ( ) . getDeclaredFields ( ) ) { if ( orderBy . equals ( field . getName ( ) ) ) { found = true ; break ; } } if ( found ) { query . setOrdering ( orderBy + " " + orderDirection . name ( ) . toLowerCase ( ) ) ; } } return query ; } | Given a query this method will decorate that query with pagination ordering and sorting direction . Specific checks are performed to ensure the execution of the query is capable of being paged and that ordering can be securely performed . | 278 | 43 |
16,046 | @ SuppressWarnings ( "unchecked" ) public < T > T persist ( T object ) { pm . currentTransaction ( ) . begin ( ) ; pm . makePersistent ( object ) ; pm . currentTransaction ( ) . commit ( ) ; pm . getFetchPlan ( ) . setDetachmentOptions ( FetchPlan . DETACH_LOAD_FIELDS ) ; pm . refresh ( object ) ; return object ; } | Persists the specified PersistenceCapable object . | 93 | 10 |
16,047 | @ SuppressWarnings ( "unchecked" ) public < T > T [ ] persist ( T ... pcs ) { pm . currentTransaction ( ) . begin ( ) ; pm . makePersistentAll ( pcs ) ; pm . currentTransaction ( ) . commit ( ) ; pm . getFetchPlan ( ) . setDetachmentOptions ( FetchPlan . DETACH_LOAD_FIELDS ) ; pm . refreshAll ( pcs ) ; return pcs ; } | Persists the specified PersistenceCapable objects . | 102 | 10 |
16,048 | public < T > T detach ( Class < T > clazz , Object id ) { pm . getFetchPlan ( ) . setDetachmentOptions ( FetchPlan . DETACH_LOAD_FIELDS ) ; return pm . detachCopy ( pm . getObjectById ( clazz , id ) ) ; } | Refreshes and detaches an object by its ID . | 66 | 12 |
16,049 | public < T > T getObjectById ( Class < T > clazz , Object id ) { return pm . getObjectById ( clazz , id ) ; } | Retrieves an object by its ID . | 34 | 9 |
16,050 | public void init ( final FilterConfig filterConfig ) { final String allowParam = filterConfig . getInitParameter ( "allowUrls" ) ; if ( StringUtils . isNotBlank ( allowParam ) ) { this . allowUrls = allowParam . split ( "," ) ; } } | Initialize allowUrls parameter from web . xml . | 63 | 11 |
16,051 | public void doFilter ( final ServletRequest request , final ServletResponse response , final FilterChain chain ) throws IOException , ServletException { final HttpServletRequest req = ( HttpServletRequest ) request ; final HttpServletResponse res = ( HttpServletResponse ) response ; final String requestUri = req . getRequestURI ( ) ; if ( requestUri != null ) { boolean allowed = false ; for ( final String url : allowUrls ) { if ( requestUri . equals ( "/" ) ) { if ( url . trim ( ) . equals ( "/" ) ) { allowed = true ; } } else if ( requestUri . startsWith ( url . trim ( ) ) ) { allowed = true ; } } if ( ! allowed ) { res . setStatus ( HttpServletResponse . SC_NOT_FOUND ) ; return ; } } chain . doFilter ( request , response ) ; } | Check for allowed URLs being requested . | 201 | 7 |
16,052 | @ POST @ Produces ( MediaType . TEXT_PLAIN ) @ ApiOperation ( value = "Assert login credentials" , notes = "Upon a successful login, a JWT will be returned in the response. This functionality requires authentication to be enabled." , response = String . class ) @ ApiResponses ( value = { @ ApiResponse ( code = 200 , message = "Success" ) , @ ApiResponse ( code = 401 , message = "Unauthorized" ) } ) @ AuthenticationNotRequired public Response validateCredentials ( @ FormParam ( "username" ) String username , @ FormParam ( "password" ) String password ) { final Authenticator auth = new Authenticator ( username , password ) ; try { final Principal principal = auth . authenticate ( ) ; if ( principal != null ) { LOGGER . info ( SecurityMarkers . SECURITY_AUDIT , "Login succeeded (username: " + username + " / ip address: " + super . getRemoteAddress ( ) + " / agent: " + super . getUserAgent ( ) + ")" ) ; final JsonWebToken jwt = new JsonWebToken ( ) ; final String token = jwt . createToken ( principal ) ; return Response . ok ( token ) . build ( ) ; } } catch ( AuthenticationException e ) { LOGGER . warn ( SecurityMarkers . SECURITY_AUDIT , "Unauthorized login attempt (username: " + username + " / ip address: " + super . getRemoteAddress ( ) + " / agent: " + super . getUserAgent ( ) + ")" ) ; } return Response . status ( Response . Status . UNAUTHORIZED ) . build ( ) ; } | Processes login requests . | 370 | 5 |
16,053 | public static byte [ ] toBytes ( char [ ] chars ) { final CharBuffer charBuffer = CharBuffer . wrap ( chars ) ; final ByteBuffer byteBuffer = Charset . forName ( "UTF-8" ) . encode ( charBuffer ) ; final byte [ ] bytes = Arrays . copyOfRange ( byteBuffer . array ( ) , byteBuffer . position ( ) , byteBuffer . limit ( ) ) ; Arrays . fill ( charBuffer . array ( ) , ' ' ) ; // clear sensitive data Arrays . fill ( byteBuffer . array ( ) , ( byte ) 0 ) ; // clear sensitive data return bytes ; } | Converts a char array to a byte array without the use of Strings . | 135 | 16 |
16,054 | public void init ( final FilterConfig filterConfig ) { final String denyParam = filterConfig . getInitParameter ( "denyUrls" ) ; if ( StringUtils . isNotBlank ( denyParam ) ) { this . denyUrls = denyParam . split ( "," ) ; } final String ignoreParam = filterConfig . getInitParameter ( "ignoreUrls" ) ; if ( StringUtils . isNotBlank ( ignoreParam ) ) { this . ignoreUrls = ignoreParam . split ( "," ) ; } } | Initialize deny parameter from web . xml . | 115 | 9 |
16,055 | public void doFilter ( final ServletRequest request , final ServletResponse response , final FilterChain chain ) throws IOException , ServletException { final HttpServletRequest req = ( HttpServletRequest ) request ; final HttpServletResponse res = ( HttpServletResponse ) response ; final String requestUri = req . getRequestURI ( ) ; if ( requestUri != null ) { for ( final String url : denyUrls ) { if ( requestUri . startsWith ( url . trim ( ) ) ) { res . setStatus ( HttpServletResponse . SC_FORBIDDEN ) ; return ; } } for ( final String url : ignoreUrls ) { if ( requestUri . startsWith ( url . trim ( ) ) ) { res . setStatus ( HttpServletResponse . SC_NOT_FOUND ) ; return ; } } } chain . doFilter ( request , response ) ; } | Check for denied or ignored URLs being requested . | 201 | 9 |
16,056 | protected void scheduleEvent ( final Event event , final long delay , final long period ) { final Timer timer = new Timer ( ) ; timer . schedule ( new ScheduleEvent ( ) . event ( event ) , delay , period ) ; timers . add ( timer ) ; } | Schedules a repeating Event . | 57 | 7 |
16,057 | private void calculateStrategy ( final Strategy strategy , final int o1 , final int o2 ) { if ( Strategy . OFFSET == strategy ) { this . offset = o1 ; this . limit = o2 ; } else if ( Strategy . PAGES == strategy ) { this . offset = ( o1 * o2 ) - o2 ; this . limit = o2 ; } } | Determines the offset and limit based on pagination strategy . | 82 | 13 |
16,058 | private Integer parseIntegerFromParam ( final String value , final int defaultValue ) { try { return Integer . valueOf ( value ) ; } catch ( NumberFormatException | NullPointerException e ) { return defaultValue ; } } | Parses a parameter to an Integer defaulting to 0 upon any errors encountered . | 48 | 17 |
16,059 | public static String generate ( final int chars ) { final SecureRandom secureRandom = new SecureRandom ( ) ; final char [ ] buff = new char [ chars ] ; for ( int i = 0 ; i < chars ; ++ i ) { if ( i % 10 == 0 ) { secureRandom . setSeed ( secureRandom . nextLong ( ) ) ; } buff [ i ] = VALID_CHARACTERS [ secureRandom . nextInt ( VALID_CHARACTERS . length ) ] ; } return new String ( buff ) ; } | Generates a cryptographically secure API key of the specified length . | 113 | 13 |
16,060 | private int [ ] parse ( String version ) { final Matcher m = Pattern . compile ( "(\\d+)\\.(\\d+)\\.(\\d+)-?(SNAPSHOT)?\\.?(\\d*)?" ) . matcher ( version ) ; if ( ! m . matches ( ) ) { throw new IllegalArgumentException ( "Malformed version string: " + version ) ; } return new int [ ] { Integer . parseInt ( m . group ( 1 ) ) , // major Integer . parseInt ( m . group ( 2 ) ) , // minor Integer . parseInt ( m . group ( 3 ) ) , // revision m . group ( 4 ) == null ? 0 // no SNAPSHOT suffix : m . group ( 5 ) . isEmpty ( ) ? 0 // "SNAPSHOT" : Integer . parseInt ( m . group ( 5 ) ) , // "SNAPSHOT.123" } ; } | Parses the version . | 199 | 6 |
16,061 | public boolean isNewerThan ( VersionComparator comparator ) { if ( this . major > comparator . getMajor ( ) ) { return true ; } else if ( this . major == comparator . getMajor ( ) && this . minor > comparator . getMinor ( ) ) { return true ; } else if ( this . major == comparator . getMajor ( ) && this . minor == comparator . getMinor ( ) && this . revision > comparator . getRevision ( ) ) { return true ; } else if ( this . major == comparator . getMajor ( ) && this . minor == comparator . getMinor ( ) && this . revision == comparator . getRevision ( ) && this . prereleaseNumber > comparator . getPrereleaseNumber ( ) ) { return true ; } return false ; } | Determines if the specified VersionComparator is newer than this instance . | 176 | 15 |
16,062 | private void initialize ( ) { createKeysIfNotExist ( ) ; if ( keyPair == null ) { try { loadKeyPair ( ) ; } catch ( IOException | NoSuchAlgorithmException | InvalidKeySpecException e ) { LOGGER . error ( "An error occurred loading key pair" ) ; LOGGER . error ( e . getMessage ( ) ) ; } } if ( secretKey == null ) { try { loadSecretKey ( ) ; } catch ( IOException | ClassNotFoundException e ) { LOGGER . error ( "An error occurred loading secret key" ) ; LOGGER . error ( e . getMessage ( ) ) ; } } } | Initializes the KeyManager | 142 | 5 |
16,063 | private void createKeysIfNotExist ( ) { if ( ! keyPairExists ( ) ) { try { final KeyPair keyPair = generateKeyPair ( ) ; save ( keyPair ) ; } catch ( NoSuchAlgorithmException e ) { LOGGER . error ( "An error occurred generating new keypair" ) ; LOGGER . error ( e . getMessage ( ) ) ; } catch ( IOException e ) { LOGGER . error ( "An error occurred saving newly generated keypair" ) ; LOGGER . error ( e . getMessage ( ) ) ; } } if ( ! secretKeyExists ( ) ) { try { final SecretKey secretKey = generateSecretKey ( ) ; save ( secretKey ) ; } catch ( NoSuchAlgorithmException e ) { LOGGER . error ( "An error occurred generating new secret key" ) ; LOGGER . error ( e . getMessage ( ) ) ; } catch ( IOException e ) { LOGGER . error ( "An error occurred saving newly generated secret key" ) ; LOGGER . error ( e . getMessage ( ) ) ; } } } | Checks if the keys exists . If not they will be created . | 239 | 14 |
16,064 | public KeyPair generateKeyPair ( ) throws NoSuchAlgorithmException { LOGGER . info ( "Generating new key pair" ) ; final KeyPairGenerator keyGen = KeyPairGenerator . getInstance ( "RSA" ) ; final SecureRandom random = SecureRandom . getInstance ( "SHA1PRNG" ) ; keyGen . initialize ( 4096 , random ) ; return this . keyPair = keyGen . generateKeyPair ( ) ; } | Generates a key pair . | 102 | 6 |
16,065 | private File getKeyPath ( final KeyType keyType ) { return new File ( Config . getInstance ( ) . getDataDirectorty ( ) + File . separator + "keys" + File . separator + keyType . name ( ) . toLowerCase ( ) + ".key" ) ; } | Retrieves the path where the keys should be stored . | 65 | 12 |
16,066 | private File getKeyPath ( final Key key ) { KeyType keyType = null ; if ( key instanceof PrivateKey ) { keyType = KeyType . PRIVATE ; } else if ( key instanceof PublicKey ) { keyType = KeyType . PUBLIC ; } else if ( key instanceof SecretKey ) { keyType = KeyType . SECRET ; } return getKeyPath ( keyType ) ; } | Given the type of key this method will return the File path to that key . | 87 | 16 |
16,067 | public void save ( final KeyPair keyPair ) throws IOException { LOGGER . info ( "Saving key pair" ) ; final PrivateKey privateKey = keyPair . getPrivate ( ) ; final PublicKey publicKey = keyPair . getPublic ( ) ; // Store Public Key final File publicKeyFile = getKeyPath ( publicKey ) ; publicKeyFile . getParentFile ( ) . mkdirs ( ) ; // make directories if they do not exist final X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec ( publicKey . getEncoded ( ) ) ; try ( OutputStream fos = Files . newOutputStream ( publicKeyFile . toPath ( ) ) ) { fos . write ( x509EncodedKeySpec . getEncoded ( ) ) ; } // Store Private Key. final File privateKeyFile = getKeyPath ( privateKey ) ; privateKeyFile . getParentFile ( ) . mkdirs ( ) ; // make directories if they do not exist final PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec ( privateKey . getEncoded ( ) ) ; try ( OutputStream fos = Files . newOutputStream ( privateKeyFile . toPath ( ) ) ) { fos . write ( pkcs8EncodedKeySpec . getEncoded ( ) ) ; } } | Saves a key pair . | 303 | 6 |
16,068 | public void save ( final SecretKey key ) throws IOException { final File keyFile = getKeyPath ( key ) ; keyFile . getParentFile ( ) . mkdirs ( ) ; // make directories if they do not exist try ( OutputStream fos = Files . newOutputStream ( keyFile . toPath ( ) ) ; ObjectOutputStream oout = new ObjectOutputStream ( fos ) ) { oout . writeObject ( key ) ; } } | Saves a secret key . | 97 | 6 |
16,069 | private KeyPair loadKeyPair ( ) throws IOException , NoSuchAlgorithmException , InvalidKeySpecException { // Read Private Key final File filePrivateKey = getKeyPath ( KeyType . PRIVATE ) ; // Read Public Key final File filePublicKey = getKeyPath ( KeyType . PUBLIC ) ; byte [ ] encodedPrivateKey ; byte [ ] encodedPublicKey ; try ( InputStream pvtfis = Files . newInputStream ( filePrivateKey . toPath ( ) ) ; InputStream pubfis = Files . newInputStream ( filePublicKey . toPath ( ) ) ) { encodedPrivateKey = new byte [ ( int ) filePrivateKey . length ( ) ] ; pvtfis . read ( encodedPrivateKey ) ; encodedPublicKey = new byte [ ( int ) filePublicKey . length ( ) ] ; pubfis . read ( encodedPublicKey ) ; } // Generate KeyPair final KeyFactory keyFactory = KeyFactory . getInstance ( "RSA" ) ; final X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec ( encodedPublicKey ) ; final PublicKey publicKey = keyFactory . generatePublic ( publicKeySpec ) ; final PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec ( encodedPrivateKey ) ; final PrivateKey privateKey = keyFactory . generatePrivate ( privateKeySpec ) ; return this . keyPair = new KeyPair ( publicKey , privateKey ) ; } | Loads a key pair . | 319 | 6 |
16,070 | private SecretKey loadSecretKey ( ) throws IOException , ClassNotFoundException { final File file = getKeyPath ( KeyType . SECRET ) ; SecretKey key ; try ( InputStream fis = Files . newInputStream ( file . toPath ( ) ) ; ObjectInputStream ois = new ObjectInputStream ( fis ) ) { key = ( SecretKey ) ois . readObject ( ) ; } return this . secretKey = key ; } | Loads the secret key . | 97 | 6 |
16,071 | public static boolean valueOf ( String value ) { return ( value != null ) && ( value . trim ( ) . equalsIgnoreCase ( "true" ) || value . trim ( ) . equals ( "1" ) ) ; } | Determines if the specified string contains true or 1 | 49 | 11 |
16,072 | public static byte [ ] encryptAsBytes ( final SecretKey secretKey , final String plainText ) throws Exception { final byte [ ] clean = plainText . getBytes ( ) ; // Generating IV int ivSize = 16 ; final byte [ ] iv = new byte [ ivSize ] ; final SecureRandom random = new SecureRandom ( ) ; random . nextBytes ( iv ) ; final IvParameterSpec ivParameterSpec = new IvParameterSpec ( iv ) ; // Encrypt final Cipher cipher = Cipher . getInstance ( "AES/CBC/PKCS5Padding" ) ; cipher . init ( Cipher . ENCRYPT_MODE , secretKey , ivParameterSpec ) ; final byte [ ] encrypted = cipher . doFinal ( clean ) ; // Combine IV and encrypted parts final byte [ ] encryptedIVAndText = new byte [ ivSize + encrypted . length ] ; System . arraycopy ( iv , 0 , encryptedIVAndText , 0 , ivSize ) ; System . arraycopy ( encrypted , 0 , encryptedIVAndText , ivSize , encrypted . length ) ; return encryptedIVAndText ; } | Encrypts the specified plainText using AES - 256 . | 231 | 12 |
16,073 | public static byte [ ] encryptAsBytes ( final String plainText ) throws Exception { final SecretKey secretKey = KeyManager . getInstance ( ) . getSecretKey ( ) ; return encryptAsBytes ( secretKey , plainText ) ; } | Encrypts the specified plainText using AES - 256 . This method uses the default secret key . | 50 | 20 |
16,074 | public static String encryptAsString ( final SecretKey secretKey , final String plainText ) throws Exception { return Base64 . getEncoder ( ) . encodeToString ( encryptAsBytes ( secretKey , plainText ) ) ; } | Encrypts the specified plainText using AES - 256 and returns a Base64 encoded representation of the encrypted bytes . | 48 | 23 |
16,075 | public static byte [ ] decryptAsBytes ( final SecretKey secretKey , final byte [ ] encryptedIvTextBytes ) throws Exception { int ivSize = 16 ; // Extract IV final byte [ ] iv = new byte [ ivSize ] ; System . arraycopy ( encryptedIvTextBytes , 0 , iv , 0 , iv . length ) ; final IvParameterSpec ivParameterSpec = new IvParameterSpec ( iv ) ; // Extract encrypted bytes final int encryptedSize = encryptedIvTextBytes . length - ivSize ; final byte [ ] encryptedBytes = new byte [ encryptedSize ] ; System . arraycopy ( encryptedIvTextBytes , ivSize , encryptedBytes , 0 , encryptedSize ) ; // Decrypt final Cipher cipherDecrypt = Cipher . getInstance ( "AES/CBC/PKCS5Padding" ) ; cipherDecrypt . init ( Cipher . DECRYPT_MODE , secretKey , ivParameterSpec ) ; return cipherDecrypt . doFinal ( encryptedBytes ) ; } | Decrypts the specified bytes using AES - 256 . | 204 | 11 |
16,076 | public static byte [ ] decryptAsBytes ( final byte [ ] encryptedIvTextBytes ) throws Exception { final SecretKey secretKey = KeyManager . getInstance ( ) . getSecretKey ( ) ; return decryptAsBytes ( secretKey , encryptedIvTextBytes ) ; } | Decrypts the specified bytes using AES - 256 . This method uses the default secret key . | 56 | 19 |
16,077 | private void setCurrentPage ( int page ) { if ( page >= totalPages ) { this . currentPage = totalPages ; } else if ( page <= 1 ) { this . currentPage = 1 ; } else { this . currentPage = page ; } // now work out where the sub-list should start and end startingIndex = pageSize * ( currentPage - 1 ) ; if ( startingIndex < 0 ) { startingIndex = 0 ; } endingIndex = startingIndex + pageSize ; if ( endingIndex > list . size ( ) ) { endingIndex = list . size ( ) ; } } | Specifies a specific page to jump to . | 125 | 9 |
16,078 | @ SuppressWarnings ( "unchecked" ) public static < T > T getSessionAttribute ( final HttpSession session , final String key ) { if ( session != null ) { return ( T ) session . getAttribute ( key ) ; } return null ; } | Returns a session attribute as the type of object stored . | 57 | 11 |
16,079 | @ SuppressWarnings ( "unchecked" ) public static < T > T getRequestAttribute ( final HttpServletRequest request , final String key ) { if ( request != null ) { return ( T ) request . getAttribute ( key ) ; } return null ; } | Returns a request attribute as the type of object stored . | 59 | 11 |
16,080 | public static < T > T readAsObjectOf ( Class < T > clazz , String value ) { final ObjectMapper mapper = new ObjectMapper ( ) ; try { return mapper . readValue ( value , clazz ) ; } catch ( IOException e ) { LOGGER . error ( e . getMessage ( ) , e . fillInStackTrace ( ) ) ; } return null ; } | Reads in a String value and returns the object for which it represents . | 87 | 15 |
16,081 | public boolean validateToken ( final String token ) { try { final JwtParser jwtParser = Jwts . parser ( ) . setSigningKey ( key ) ; jwtParser . parse ( token ) ; this . subject = jwtParser . parseClaimsJws ( token ) . getBody ( ) . getSubject ( ) ; this . expiration = jwtParser . parseClaimsJws ( token ) . getBody ( ) . getExpiration ( ) ; return true ; } catch ( SignatureException e ) { LOGGER . info ( SecurityMarkers . SECURITY_FAILURE , "Received token that did not pass signature verification" ) ; } catch ( ExpiredJwtException e ) { LOGGER . debug ( SecurityMarkers . SECURITY_FAILURE , "Received expired token" ) ; } catch ( MalformedJwtException e ) { LOGGER . debug ( SecurityMarkers . SECURITY_FAILURE , "Received malformed token" ) ; LOGGER . debug ( SecurityMarkers . SECURITY_FAILURE , e . getMessage ( ) ) ; } catch ( UnsupportedJwtException | IllegalArgumentException e ) { LOGGER . error ( SecurityMarkers . SECURITY_FAILURE , e . getMessage ( ) ) ; } return false ; } | Validates a JWT by ensuring the signature matches and validates against the SecretKey and checks the expiration date . | 285 | 23 |
16,082 | private Date addDays ( final Date date , final int days ) { final Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( date ) ; cal . add ( Calendar . DATE , days ) ; //minus number would decrement the days return cal . getTime ( ) ; } | Create a new future Date from the specified Date . | 62 | 10 |
16,083 | private Event linkChainIdentifier ( Event event ) { if ( event instanceof ChainableEvent ) { ChainableEvent chainableEvent = ( ChainableEvent ) event ; chainableEvent . setChainIdentifier ( this . getChainIdentifier ( ) ) ; return chainableEvent ; } return event ; } | Assigns the chain identifier for the specified event to the chain identifier value of this instance . This requires the specified event to be an instance of ChainableEvent . | 64 | 33 |
16,084 | public void executeUpgrades ( final List < Class < ? extends UpgradeItem > > classes ) throws UpgradeException { final Connection connection = getConnection ( qm ) ; final UpgradeMetaProcessor installedUpgrades = new UpgradeMetaProcessor ( connection ) ; DbUtil . initPlatformName ( connection ) ; // Initialize DbUtil // First, we need to ensure the schema table is populated on a clean install // But we do so without passing any version. try { installedUpgrades . updateSchemaVersion ( null ) ; } catch ( SQLException e ) { LOGGER . error ( "Failed to update schema version" , e ) ; return ; } for ( final Class < ? extends UpgradeItem > upgradeClass : classes ) { try { @ SuppressWarnings ( "unchecked" ) final Constructor constructor = upgradeClass . getConstructor ( ) ; final UpgradeItem upgradeItem = ( UpgradeItem ) constructor . newInstance ( ) ; if ( upgradeItem . shouldUpgrade ( qm , connection ) ) { if ( ! installedUpgrades . hasUpgradeRan ( upgradeClass ) ) { LOGGER . info ( "Upgrade class " + upgradeClass . getName ( ) + " about to run." ) ; final long startTime = System . currentTimeMillis ( ) ; upgradeItem . executeUpgrade ( qm , connection ) ; final long endTime = System . currentTimeMillis ( ) ; installedUpgrades . installUpgrade ( upgradeClass , startTime , endTime ) ; installedUpgrades . updateSchemaVersion ( new VersionComparator ( upgradeItem . getSchemaVersion ( ) ) ) ; LOGGER . info ( "Completed running upgrade class " + upgradeClass . getName ( ) + " in " + ( endTime - startTime ) + " ms." ) ; } else { LOGGER . debug ( "Upgrade class " + upgradeClass . getName ( ) + " has already ran, skipping." ) ; } } else { LOGGER . debug ( "Upgrade class " + upgradeClass . getName ( ) + " does not need to run." ) ; } } catch ( Exception e ) { DbUtil . rollback ( connection ) ; LOGGER . error ( "Error in executing upgrade class: " + upgradeClass . getName ( ) , e ) ; throw new UpgradeException ( e ) ; } } } | Performs the execution of upgrades in the order defined by the specified array . | 495 | 15 |
16,085 | private Connection getConnection ( AlpineQueryManager aqm ) { final JDOConnection jdoConnection = aqm . getPersistenceManager ( ) . getDataStoreConnection ( ) ; if ( jdoConnection != null ) { if ( jdoConnection . getNativeConnection ( ) instanceof Connection ) { return ( Connection ) jdoConnection . getNativeConnection ( ) ; } } return null ; } | This connection should never be closed . | 84 | 7 |
16,086 | public static boolean isValidUUID ( String uuid ) { return ! StringUtils . isEmpty ( uuid ) && UUID_PATTERN . matcher ( uuid ) . matches ( ) ; } | Determines if the specified string is a valid UUID . | 45 | 13 |
16,087 | private LdapUser autoProvision ( final AlpineQueryManager qm ) throws AlpineAuthenticationException { LOGGER . debug ( "Provisioning: " + username ) ; LdapUser user = null ; final LdapConnectionWrapper ldap = new LdapConnectionWrapper ( ) ; DirContext dirContext = null ; try { dirContext = ldap . createDirContext ( ) ; final SearchResult result = ldap . searchForSingleUsername ( dirContext , username ) ; if ( result != null ) { user = new LdapUser ( ) ; user . setUsername ( username ) ; user . setDN ( result . getNameInNamespace ( ) ) ; user . setEmail ( ldap . getAttribute ( result , LdapConnectionWrapper . ATTRIBUTE_MAIL ) ) ; user = qm . persist ( user ) ; // Dynamically assign team membership (if enabled) if ( LdapConnectionWrapper . TEAM_SYNCHRONIZATION ) { final List < String > groupDNs = ldap . getGroups ( dirContext , user ) ; user = qm . synchronizeTeamMembership ( user , groupDNs ) ; } } else { LOGGER . warn ( "Could not find '" + username + "' in the directory while provisioning the user. Ensure '" + Config . AlpineKey . LDAP_ATTRIBUTE_NAME . getPropertyName ( ) + "' is defined correctly" ) ; throw new AlpineAuthenticationException ( AlpineAuthenticationException . CauseType . UNMAPPED_ACCOUNT ) ; } } catch ( NamingException e ) { LOGGER . error ( "An error occurred while auto-provisioning an authenticated user" , e ) ; throw new AlpineAuthenticationException ( AlpineAuthenticationException . CauseType . OTHER ) ; } finally { ldap . closeQuietly ( dirContext ) ; } return user ; } | Automatically creates an LdapUser sets the value of various LDAP attributes and persists the user to the database . | 418 | 24 |
16,088 | private boolean validateCredentials ( ) { LOGGER . debug ( "Validating credentials for: " + username ) ; final LdapConnectionWrapper ldap = new LdapConnectionWrapper ( ) ; DirContext dirContext = null ; LdapContext ldapContext = null ; try ( AlpineQueryManager qm = new AlpineQueryManager ( ) ) { final LdapUser ldapUser = qm . getLdapUser ( username ) ; if ( ldapUser != null && ldapUser . getDN ( ) != null && ldapUser . getDN ( ) . contains ( "=" ) ) { ldapContext = ldap . createLdapContext ( ldapUser . getDN ( ) , password ) ; LOGGER . debug ( "The supplied credentials are valid for: " + username ) ; return true ; } else { dirContext = ldap . createDirContext ( ) ; final SearchResult result = ldap . searchForSingleUsername ( dirContext , username ) ; if ( result != null ) { ldapContext = ldap . createLdapContext ( result . getNameInNamespace ( ) , password ) ; LOGGER . debug ( "The supplied credentials are invalid for: " + username ) ; return true ; } } } catch ( NamingException e ) { LOGGER . debug ( "An error occurred while attempting to validate credentials" , e ) ; } finally { ldap . closeQuietly ( ldapContext ) ; ldap . closeQuietly ( dirContext ) ; } return false ; } | Asserts a users credentials . Returns a boolean value indicating if assertion was successful or not . | 348 | 19 |
16,089 | public static PersistenceManager createPersistenceManager ( ) { if ( Config . isUnitTestsEnabled ( ) ) { pmf = ( JDOPersistenceManagerFactory ) JDOHelper . getPersistenceManagerFactory ( JdoProperties . unit ( ) , "Alpine" ) ; } if ( pmf == null ) { throw new IllegalStateException ( "Context is not initialized yet." ) ; } return pmf . getPersistenceManager ( ) ; } | Creates a new JDO PersistenceManager . | 99 | 10 |
16,090 | public LdapContext createLdapContext ( final String userDn , final String password ) throws NamingException { LOGGER . debug ( "Creating LDAP context for: " + userDn ) ; if ( StringUtils . isEmpty ( userDn ) || StringUtils . isEmpty ( password ) ) { throw new NamingException ( "Username or password cannot be empty or null" ) ; } final Hashtable < String , String > env = new Hashtable <> ( ) ; if ( StringUtils . isNotBlank ( LDAP_SECURITY_AUTH ) ) { env . put ( Context . SECURITY_AUTHENTICATION , LDAP_SECURITY_AUTH ) ; } env . put ( Context . SECURITY_PRINCIPAL , userDn ) ; env . put ( Context . SECURITY_CREDENTIALS , password ) ; env . put ( Context . INITIAL_CONTEXT_FACTORY , "com.sun.jndi.ldap.LdapCtxFactory" ) ; env . put ( Context . PROVIDER_URL , LDAP_URL ) ; if ( IS_LDAP_SSLTLS ) { env . put ( "java.naming.ldap.factory.socket" , "alpine.crypto.RelaxedSSLSocketFactory" ) ; } try { return new InitialLdapContext ( env , null ) ; } catch ( CommunicationException e ) { LOGGER . error ( "Failed to connect to directory server" , e ) ; throw ( e ) ; } catch ( NamingException e ) { throw new NamingException ( "Failed to authenticate user" ) ; } } | Asserts a users credentials . Returns an LdapContext if assertion is successful or an exception for any other reason . | 375 | 25 |
16,091 | public DirContext createDirContext ( ) throws NamingException { LOGGER . debug ( "Creating directory service context (DirContext)" ) ; final Hashtable < String , String > env = new Hashtable <> ( ) ; env . put ( Context . SECURITY_PRINCIPAL , BIND_USERNAME ) ; env . put ( Context . SECURITY_CREDENTIALS , BIND_PASSWORD ) ; env . put ( Context . INITIAL_CONTEXT_FACTORY , "com.sun.jndi.ldap.LdapCtxFactory" ) ; env . put ( Context . PROVIDER_URL , LDAP_URL ) ; if ( IS_LDAP_SSLTLS ) { env . put ( "java.naming.ldap.factory.socket" , "alpine.crypto.RelaxedSSLSocketFactory" ) ; } return new InitialDirContext ( env ) ; } | Creates a DirContext with the applications configuration settings . | 207 | 11 |
16,092 | public List < String > getGroups ( final DirContext dirContext , final LdapUser ldapUser ) throws NamingException { LOGGER . debug ( "Retrieving groups for: " + ldapUser . getDN ( ) ) ; final List < String > groupDns = new ArrayList <> ( ) ; final String searchFilter = variableSubstitution ( USER_GROUPS_FILTER , ldapUser ) ; final SearchControls sc = new SearchControls ( ) ; sc . setSearchScope ( SearchControls . SUBTREE_SCOPE ) ; final NamingEnumeration < SearchResult > ne = dirContext . search ( BASE_DN , searchFilter , sc ) ; while ( hasMoreEnum ( ne ) ) { final SearchResult result = ne . next ( ) ; groupDns . add ( result . getNameInNamespace ( ) ) ; LOGGER . debug ( "Found group: " + result . getNameInNamespace ( ) + " for user: " + ldapUser . getDN ( ) ) ; } closeQuietly ( ne ) ; return groupDns ; } | Retrieves a list of all groups the user is a member of . | 247 | 15 |
16,093 | public List < String > getGroups ( final DirContext dirContext ) throws NamingException { LOGGER . debug ( "Retrieving all groups" ) ; final List < String > groupDns = new ArrayList <> ( ) ; final SearchControls sc = new SearchControls ( ) ; sc . setSearchScope ( SearchControls . SUBTREE_SCOPE ) ; final NamingEnumeration < SearchResult > ne = dirContext . search ( BASE_DN , GROUPS_FILTER , sc ) ; while ( hasMoreEnum ( ne ) ) { final SearchResult result = ne . next ( ) ; groupDns . add ( result . getNameInNamespace ( ) ) ; LOGGER . debug ( "Found group: " + result . getNameInNamespace ( ) ) ; } closeQuietly ( ne ) ; return groupDns ; } | Retrieves a list of all the groups in the directory . | 188 | 13 |
16,094 | public String getAttribute ( final DirContext ctx , final String dn , final String attributeName ) throws NamingException { final Attributes attributes = ctx . getAttributes ( dn ) ; return getAttribute ( attributes , attributeName ) ; } | Retrieves an attribute by its name for the specified dn . | 51 | 14 |
16,095 | public String getAttribute ( final SearchResult result , final String attributeName ) throws NamingException { return getAttribute ( result . getAttributes ( ) , attributeName ) ; } | Retrieves an attribute by its name for the specified search result . | 36 | 14 |
16,096 | public String getAttribute ( final Attributes attributes , final String attributeName ) throws NamingException { if ( attributes == null || attributes . size ( ) == 0 ) { return null ; } else { final Attribute attribute = attributes . get ( attributeName ) ; if ( attribute != null ) { final Object o = attribute . get ( ) ; if ( o instanceof String ) { return ( String ) attribute . get ( ) ; } } } return null ; } | Retrieves an attribute by its name . | 95 | 9 |
16,097 | private static String formatPrincipal ( final String username ) { if ( StringUtils . isNotBlank ( LDAP_AUTH_USERNAME_FMT ) ) { return String . format ( LDAP_AUTH_USERNAME_FMT , username ) ; } return username ; } | Formats the principal in username | 62 | 6 |
16,098 | public static String generateHash ( String emailAddress ) { if ( StringUtils . isBlank ( emailAddress ) ) { return null ; } return DigestUtils . md5Hex ( emailAddress . trim ( ) . toLowerCase ( ) ) . toLowerCase ( ) ; } | Generates a hash value from the specified email address . Returns null if emailAddress is empty or null . | 61 | 21 |
16,099 | public static String getGravatarUrl ( String emailAddress ) { String hash = generateHash ( emailAddress ) ; if ( hash == null ) { return "https://www.gravatar.com/avatar/00000000000000000000000000000000" + ".jpg?d=mm" ; } else { return "https://www.gravatar.com/avatar/" + hash + ".jpg?d=mm" ; } } | Generates a Gravatar URL for the specified email address . If the email address is blank or does not have a Gravatar will fallback to usingthe mystery - man image . | 89 | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.