idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
17,500
protected Person getPersonById ( String id ) { Person person = null ; try { Long personId = Long . valueOf ( id ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Retrieving Person with id=[{}]" , personId ) ; } person = entityManager . find ( Person . class , personId ) ; } catch ( NumberFormatException e ) { if ( logger . isWarnEnabled ( ) ) { logger . warn ( "Invalid number format: {}" , id ) ; } } if ( person == null ) { throw new IllegalArgumentException ( ) ; } return person ; }
Retrieves the person with the given id . Throwing an IllegalArgumentException if there is no such person .
17,501
public static BackoffStrategy fixedBackoff ( long sleepTime , TimeUnit timeUnit ) throws IllegalStateException { Preconditions . checkNotNull ( timeUnit , "The time unit may not be null" ) ; return new FixedBackoffStrategy ( timeUnit . toMillis ( sleepTime ) ) ; }
Returns a backoff strategy that waits a fixed amount of time before retrying .
17,502
public static BackoffStrategy linearBackoff ( long initialSleepTime , TimeUnit initialSleepTimeUnit , long increment , TimeUnit incrementTimeUnit ) { Preconditions . checkNotNull ( initialSleepTimeUnit , "The initial wait time unit may not be null" ) ; Preconditions . checkNotNull ( incrementTimeUnit , "The increment time unit may not be null" ) ; return new LinearBackoffStrategy ( initialSleepTimeUnit . toMillis ( initialSleepTime ) , incrementTimeUnit . toMillis ( increment ) ) ; }
Returns a strategy that waits a fixed amount of time after the first failed attempt and in incrementing amounts of time after each additional failed attempt .
17,503
public static BackoffStrategy exponentialBackoff ( long maximumTime , TimeUnit maximumTimeUnit ) { Preconditions . checkNotNull ( maximumTimeUnit , "The maximum time unit may not be null" ) ; return new ExponentialBackoffStrategy ( 1 , maximumTimeUnit . toMillis ( maximumTime ) ) ; }
Returns a strategy which waits for an exponential amount of time after the first failed attempt and in exponentially incrementing amounts after each failed attempt up to the maximumTime .
17,504
public static BackoffStrategy join ( BackoffStrategy ... backoffStrategies ) { Preconditions . checkState ( backoffStrategies . length > 0 , "Must have at least one backoff strategy" ) ; List < BackoffStrategy > waitStrategyList = Lists . newArrayList ( backoffStrategies ) ; Preconditions . checkState ( ! waitStrategyList . contains ( null ) , "Cannot have a null backoff strategy" ) ; return new CompositeBackoffStrategy ( waitStrategyList ) ; }
Joins one or more wait strategies to derive a composite backoff strategy . The new joined strategy will have a wait time which is total of all wait times computed one after another in order .
17,505
public static < T > T fromJson ( Class < T > type , String value ) throws JsonMappingException , JsonParseException , IOException { if ( value == null ) return null ; return _mapper . readValue ( value , type ) ; }
Converts JSON string into a value of type specified by Class type .
17,506
public static String toJson ( Object value ) throws JsonProcessingException { if ( value == null ) return null ; return _mapper . writeValueAsString ( value ) ; }
Converts value into JSON string .
17,507
public static Map < String , Object > toNullableMap ( String value ) { if ( value == null ) return null ; try { Map < String , Object > map = _mapper . readValue ( ( String ) value , typeRef ) ; return RecursiveMapConverter . toNullableMap ( map ) ; } catch ( Exception ex ) { return null ; } }
Converts JSON string into map object or returns null when conversion is not possible .
17,508
public static Map < String , Object > toMap ( String value ) { Map < String , Object > result = toNullableMap ( value ) ; return result != null ? result : new HashMap < String , Object > ( ) ; }
Converts JSON string into map object or returns empty map when conversion is not possible .
17,509
public static Map < String , Object > toMapWithDefault ( String value , Map < String , Object > defaultValue ) { Map < String , Object > result = toNullableMap ( value ) ; return result != null ? result : defaultValue ; }
Converts JSON string into map object or returns default value when conversion is not possible .
17,510
public < N extends Number > NumberSummaryStatistics addAll ( Stream < N > numberStream ) { return addAll ( numberStream . collect ( toList ( ) ) ) ; }
Add all number summary statistics .
17,511
public Map < StatsField , Number > getStatsFieldMap ( ) { return Arrays . stream ( StatsField . values ( ) ) . collect ( toMap ( Function . identity ( ) , this :: getStats ) ) ; }
Gets stats field map .
17,512
private void sortMethodList ( ) { final List < Class < ? > > hierarchy = new ArrayList < Class < ? > > ( ) ; if ( initialisationClasses != null ) { for ( int i = initialisationClasses . length ; i > 0 ; i -- ) { hierarchy . addAll ( classHierarchyFor ( initialisationClasses [ i - 1 ] ) ) ; } } sortMethodLists ( hierarchy ) ; }
from the previous base class
17,513
public short expectShort ( ) throws IOException { int b1 = in . read ( ) ; if ( b1 < 0 ) { throw new IOException ( "Missing byte 1 to expected short" ) ; } int b2 = in . read ( ) ; if ( b2 < 0 ) { throw new IOException ( "Missing byte 2 to expected short" ) ; } return ( short ) unshift2bytes ( b1 , b2 ) ; }
Read a short from the input stream .
17,514
public int expectInt ( ) throws IOException { int b1 = in . read ( ) ; if ( b1 < 0 ) { throw new IOException ( "Missing byte 1 to expected int" ) ; } int b2 = in . read ( ) ; if ( b2 < 0 ) { throw new IOException ( "Missing byte 2 to expected int" ) ; } int b3 = in . read ( ) ; if ( b3 < 0 ) { throw new IOException ( "Missing byte 3 to expected int" ) ; } int b4 = in . read ( ) ; if ( b4 < 0 ) { throw new IOException ( "Missing byte 4 to expected int" ) ; } return unshift4bytes ( b1 , b2 , b3 , b4 ) ; }
Read an int from the input stream .
17,515
public long expectLong ( ) throws IOException { int b1 = in . read ( ) ; if ( b1 < 0 ) { throw new IOException ( "Missing byte 1 to expected long" ) ; } int b2 = in . read ( ) ; if ( b2 < 0 ) { throw new IOException ( "Missing byte 2 to expected long" ) ; } int b3 = in . read ( ) ; if ( b3 < 0 ) { throw new IOException ( "Missing byte 3 to expected long" ) ; } long b4 = in . read ( ) ; if ( b4 < 0 ) { throw new IOException ( "Missing byte 4 to expected long" ) ; } long b5 = in . read ( ) ; if ( b5 < 0 ) { throw new IOException ( "Missing byte 5 to expected long" ) ; } long b6 = in . read ( ) ; if ( b6 < 0 ) { throw new IOException ( "Missing byte 6 to expected long" ) ; } long b7 = in . read ( ) ; if ( b7 < 0 ) { throw new IOException ( "Missing byte 7 to expected long" ) ; } long b8 = in . read ( ) ; if ( b8 < 0 ) { throw new IOException ( "Missing byte 8 to expected long" ) ; } return unshift8bytes ( b1 , b2 , b3 , b4 , b5 , b6 , b7 , b8 ) ; }
Read a long int from the input stream .
17,516
public int expectUnsigned ( int bytes ) throws IOException { switch ( bytes ) { case 4 : return expectUInt32 ( ) ; case 3 : return expectUInt24 ( ) ; case 2 : return expectUInt16 ( ) ; case 1 : return expectUInt8 ( ) ; } throw new IllegalArgumentException ( "Unsupported byte count for unsigned: " + bytes ) ; }
Read an unsigned number from the input stream .
17,517
public long expectSigned ( int bytes ) throws IOException { switch ( bytes ) { case 8 : return expectLong ( ) ; case 4 : return expectInt ( ) ; case 2 : return expectShort ( ) ; case 1 : return expectByte ( ) ; } throw new IllegalArgumentException ( "Unsupported byte count for signed: " + bytes ) ; }
Read an signed number from the input stream .
17,518
public boolean clear ( ) { boolean result = false ; for ( File file : base . listFiles ( ) ) { result = result | FileUtils . deleteRecursive ( file ) ; } return result ; }
Deletes all children of this directory
17,519
public static Path appendAndClose ( String filePath , Charset charset , String writingString ) { return new JMFileAppender ( filePath , charset ) . append ( writingString ) . closeAndGetFilePath ( ) ; }
Append and close path .
17,520
private void addFinishToStart ( ) { follow . get ( grammar . getProductions ( ) . get ( 0 ) . getName ( ) ) . add ( FinishTerminal . getInstance ( ) ) ; }
This method ass the finish construction to the start symbol . If a start symbol is defined by StartProduction this construction is used . If the there is no such production the fist production is used .
17,521
public static ProtocolSerializer getProtocolSerializer ( ProtocolHeader header , Protocol protocol ) throws JsonGenerationException , JsonMappingException , IOException { final String s = serializeProtocol ( header , protocol ) ; return new ProtocolSerializer ( ) { public String serializerAsString ( ) { return s ; } } ; }
Serialize the Protocol .
17,522
public static ProtocolDeserializer getProtocolDeserializer ( String jsonStr ) throws JsonParseException , JsonMappingException , IOException { final ProtocolPair p = mapper . readValue ( jsonStr , ProtocolPair . class ) ; Protocol pp = null ; if ( p . getType ( ) != null ) { pp = ( Protocol ) mapper . readValue ( p . getProtocol ( ) , p . getType ( ) ) ; } final Protocol resp = pp ; return new ProtocolDeserializer ( ) { public ProtocolHeader deserializerProtocolHeader ( ) { return p . getProtocolHeader ( ) ; } public Protocol deserializerProtocol ( ) { return resp ; } } ; }
Deserialize the Protocol Json String .
17,523
public static ResponseDeserializer getResponseDeserializer ( String jsonStr ) throws JsonParseException , JsonMappingException , IOException { final ResponsePair p = mapper . readValue ( jsonStr , ResponsePair . class ) ; Response rr = null ; if ( p . getType ( ) != null ) { rr = ( Response ) mapper . readValue ( p . getResponse ( ) , p . getType ( ) ) ; } final Response resp = rr ; return new ResponseDeserializer ( ) { public ResponseHeader deserializerResponseHeader ( ) { return p . getResponseHeader ( ) ; } public Response deserializerResponse ( ) { return resp ; } } ; }
Deserialize the Response Json String .
17,524
private static String serializeProtocol ( ProtocolHeader header , Protocol protocol ) throws JsonGenerationException , JsonMappingException , IOException { ProtocolPair p = new ProtocolPair ( ) ; p . setProtocolHeader ( header ) ; if ( protocol == null ) { p . setType ( null ) ; } else { p . setType ( protocol . getClass ( ) ) ; } p . setProtocol ( toJsonStr ( protocol ) ) ; return toJsonStr ( p ) ; }
Serialize the Protocol to JSON String .
17,525
private static String toJsonStr ( Object object ) throws JsonGenerationException , JsonMappingException , IOException { return mapper . writeValueAsString ( object ) ; }
Transfer Object to JSON String .
17,526
public static String combine ( String left , String right , int minOverlap ) { if ( left . length ( ) < minOverlap ) return null ; if ( right . length ( ) < minOverlap ) return null ; int bestOffset = Integer . MAX_VALUE ; for ( int offset = minOverlap - left . length ( ) ; offset < right . length ( ) - minOverlap ; offset ++ ) { boolean match = true ; for ( int posLeft = Math . max ( 0 , - offset ) ; posLeft < Math . min ( left . length ( ) , right . length ( ) - offset ) ; posLeft ++ ) { if ( left . charAt ( posLeft ) != right . charAt ( posLeft + offset ) ) { match = false ; break ; } } if ( match ) { if ( Math . abs ( bestOffset ) > Math . abs ( offset ) ) bestOffset = offset ; } } if ( bestOffset < Integer . MAX_VALUE ) { String combined = left ; if ( bestOffset > 0 ) { combined = right . substring ( 0 , bestOffset ) + combined ; } if ( left . length ( ) + bestOffset < right . length ( ) ) { combined = combined + right . substring ( left . length ( ) + bestOffset ) ; } return combined ; } else { return null ; } }
Combine string .
17,527
public List < String > keywords ( final String source ) { Map < String , Long > wordCounts = splitChars ( source , DEFAULT_THRESHOLD ) . stream ( ) . collect ( Collectors . groupingBy ( x -> x , Collectors . counting ( ) ) ) ; wordCounts = aggregateKeywords ( wordCounts ) ; return wordCounts . entrySet ( ) . stream ( ) . filter ( x -> x . getValue ( ) > 1 ) . sorted ( Comparator . comparing ( x -> - entropy ( x . getKey ( ) ) * Math . pow ( x . getValue ( ) , 0.3 ) ) ) . map ( e -> { if ( isVerbose ( ) ) { verbose . println ( String . format ( "KEYWORD: \"%s\" - %s * %.3f / %s" , e . getKey ( ) , e . getValue ( ) , entropy ( e . getKey ( ) ) , e . getKey ( ) . length ( ) ) ) ; } return e . getKey ( ) ; } ) . collect ( Collectors . toList ( ) ) ; }
Keywords list .
17,528
public double spelling ( final String source ) { assert ( source . startsWith ( "|" ) ) ; assert ( source . endsWith ( "|" ) ) ; WordSpelling original = new WordSpelling ( source ) ; WordSpelling corrected = IntStream . range ( 0 , 1 ) . mapToObj ( i -> buildCorrection ( original ) ) . min ( Comparator . comparingDouble ( x -> x . sum ) ) . get ( ) ; return corrected . sum ; }
Spelling double .
17,529
public List < String > splitMatches ( String text , int minSize ) { TrieNode node = inner . root ( ) ; List < String > matches = new ArrayList < > ( ) ; String accumulator = "" ; for ( int i = 0 ; i < text . length ( ) ; i ++ ) { short prevDepth = node . getDepth ( ) ; TrieNode prevNode = node ; node = node . getContinuation ( text . charAt ( i ) ) ; if ( null == node ) node = inner . root ( ) ; if ( ! accumulator . isEmpty ( ) && ( node . getDepth ( ) < prevDepth || ( prevNode . hasChildren ( ) && node . getDepth ( ) == prevDepth ) ) ) { if ( accumulator . length ( ) > minSize ) { matches . add ( accumulator ) ; node = ( ( Optional < TrieNode > ) inner . root ( ) . getChild ( text . charAt ( i ) ) ) . orElse ( inner . root ( ) ) ; } accumulator = "" ; } else if ( ! accumulator . isEmpty ( ) ) { accumulator += text . charAt ( i ) ; } else if ( accumulator . isEmpty ( ) && node . getDepth ( ) > prevDepth ) { accumulator = node . getString ( ) ; } } List < String > tokenization = new ArrayList < > ( ) ; for ( String match : matches ) { int index = text . indexOf ( match ) ; assert ( index >= 0 ) ; if ( index > 0 ) tokenization . add ( text . substring ( 0 , index ) ) ; tokenization . add ( text . substring ( index , index + match . length ( ) ) ) ; text = text . substring ( index + match . length ( ) ) ; } tokenization . add ( text ) ; return tokenization ; }
Split matches list .
17,530
public List < String > splitChars ( final String source , double threshold ) { List < String > output = new ArrayList < > ( ) ; int wordStart = 0 ; double aposterioriNatsPrev = 0 ; boolean isIncreasing = false ; double prevLink = 0 ; for ( int i = 1 ; i < source . length ( ) ; i ++ ) { String priorText = source . substring ( 0 , i ) ; TrieNode priorNode = getMaxentPrior ( priorText ) ; double aprioriNats = entropy ( priorNode , priorNode . getParent ( ) ) ; String followingText = source . substring ( i - 1 , source . length ( ) ) ; TrieNode followingNode = getMaxentPost ( followingText ) ; TrieNode godparent = followingNode . godparent ( ) ; double aposterioriNats = entropy ( followingNode , godparent ) ; double linkNats = aprioriNats + aposterioriNatsPrev ; if ( isVerbose ( ) ) { verbose . println ( String . format ( "%10s\t%10s\t%s" , '"' + priorNode . getString ( ) . replaceAll ( "\n" , "\\n" ) + '"' , '"' + followingNode . getString ( ) . replaceAll ( "\n" , "\\n" ) + '"' , Arrays . asList ( aprioriNats , aposterioriNats , linkNats ) . stream ( ) . map ( x -> String . format ( "%.4f" , x ) ) . collect ( Collectors . joining ( "\t" ) ) ) ) ; } String word = i < 2 ? "" : source . substring ( wordStart , i - 2 ) ; if ( isIncreasing && linkNats < prevLink && prevLink > threshold && word . length ( ) > 2 ) { wordStart = i - 2 ; output . add ( word ) ; if ( isVerbose ( ) ) verbose . println ( String . format ( "Recognized token \"%s\"" , word ) ) ; prevLink = linkNats ; aposterioriNatsPrev = aposterioriNats ; isIncreasing = false ; } else { if ( linkNats > prevLink ) isIncreasing = true ; prevLink = linkNats ; aposterioriNatsPrev = aposterioriNats ; } } return output ; }
Split chars list .
17,531
public double entropy ( final String source ) { double output = 0 ; for ( int i = 1 ; i < source . length ( ) ; i ++ ) { TrieNode node = this . inner . matchEnd ( source . substring ( 0 , i ) ) ; Optional < ? extends TrieNode > child = node . getChild ( source . charAt ( i ) ) ; while ( ! child . isPresent ( ) ) { output += Math . log ( 1.0 / node . getCursorCount ( ) ) ; node = node . godparent ( ) ; child = node . getChild ( source . charAt ( i ) ) ; } output += Math . log ( child . get ( ) . getCursorCount ( ) * 1.0 / node . getCursorCount ( ) ) ; } return - output / Math . log ( 2 ) ; }
Entropy double .
17,532
public static InetAddress anonymize ( final InetAddress inetAddress ) throws UnknownHostException { if ( inetAddress . isAnyLocalAddress ( ) || inetAddress . isLoopbackAddress ( ) ) { return inetAddress ; } final int mask = inetAddress instanceof Inet4Address ? 24 : 48 ; return truncate ( inetAddress , mask ) ; }
IPv4 addresses have their length truncated to 24 bits IPv6 to 48 bits
17,533
public ApiPreprocessingContext process ( Object object ) throws ApiErrorsException { if ( result != null ) { throw new IllegalStateException ( "This preprocessing context has already been used; create another one." ) ; } result = preprocessor . process ( object , this ) ; if ( failOnErrors && apiErrorResponse . hasErrors ( ) ) { throw new ApiErrorsException ( apiErrorResponse ) ; } return this ; }
Runs preprocessing on the specified object .
17,534
public ApiPreprocessingContext validateWith ( IValidator ... apiValidators ) { for ( IValidator apiValidator : apiValidators ) { if ( apiValidator == null ) { throw new IllegalArgumentException ( "Validator cannot be null" ) ; } this . validators . add ( apiValidator ) ; } return this ; }
Adds the specified validators to be run on the preprocessed object after bean validations .
17,535
public static String getHeader ( HttpServletRequest request , String header ) { if ( request == null || StringUtils . isNullOrEmptyTrimmed ( header ) ) { return null ; } return request . getHeader ( header ) ; }
Returns header from given request
17,536
public static String getDomain ( HttpServletRequest request ) { if ( request == null ) { return null ; } return UrlUtils . resolveDomain ( request . getServerName ( ) ) ; }
Resolves domain name from given URL
17,537
public static boolean isIpAddressAllowed ( String ipAddress , String ... whitelist ) { if ( StringUtils . isNullOrEmpty ( ipAddress ) || whitelist == null || whitelist . length == 0 ) { return false ; } for ( String address : whitelist ) { if ( ipAddress . equals ( address ) ) { return true ; } if ( address . contains ( "/" ) ) { SubnetUtils utils = new SubnetUtils ( address ) ; utils . setInclusiveHostCount ( true ) ; if ( utils . getInfo ( ) . isInRange ( ipAddress ) ) { return true ; } } } return false ; }
Compares ipAddress with one of the ip addresses listed
17,538
public static boolean checkBasicAuth ( HttpServletRequest servletRequest , String username , String password ) { String basicAuth = servletRequest . getHeader ( "Authorization" ) ; if ( StringUtils . isNullOrEmptyTrimmed ( basicAuth ) || ! basicAuth . startsWith ( "Basic " ) ) { return false ; } String base64Credentials = basicAuth . substring ( "Basic" . length ( ) ) . trim ( ) ; String credentials = new String ( Base64 . getDecoder ( ) . decode ( base64Credentials ) , Charset . forName ( "UTF-8" ) ) ; final String [ ] values = credentials . split ( ":" , 2 ) ; if ( values . length != 2 ) { return false ; } return StringUtils . equals ( values [ 0 ] , username ) && StringUtils . equals ( values [ 1 ] , password ) ; }
Checks if request is made by cron job
17,539
public StatsMap merge ( StatsMap statsMap ) { synchronized ( statsFieldNumberMap ) { statsFieldNumberMap . put ( count , statsFieldNumberMap . get ( count ) . longValue ( ) + statsMap . get ( count ) . longValue ( ) ) ; statsFieldNumberMap . put ( sum , statsFieldNumberMap . get ( sum ) . doubleValue ( ) + statsMap . get ( sum ) . doubleValue ( ) ) ; statsFieldNumberMap . put ( min , statsFieldNumberMap . get ( min ) . doubleValue ( ) < statsMap . get ( min ) . doubleValue ( ) ? statsFieldNumberMap . get ( min ) . doubleValue ( ) : statsMap . get ( min ) . doubleValue ( ) ) ; statsFieldNumberMap . put ( max , statsFieldNumberMap . get ( max ) . doubleValue ( ) > statsMap . get ( max ) . doubleValue ( ) ? statsFieldNumberMap . get ( max ) . doubleValue ( ) : statsMap . get ( max ) . doubleValue ( ) ) ; statsFieldNumberMap . put ( avg , statsFieldNumberMap . get ( sum ) . doubleValue ( ) / statsFieldNumberMap . get ( count ) . doubleValue ( ) ) ; return this ; } }
Merge stats map .
17,540
public static Map < String , Number > changeIntoStatsFieldStringMap ( StatsMap statsMap ) { return JMMap . newChangedKeyMap ( statsMap , StatsField :: name ) ; }
Change into stats field string map map .
17,541
public static StatsMap changeIntoStatsMap ( Map < String , Number > statsFieldStringMap ) { return new StatsMap ( JMMap . newChangedKeyMap ( statsFieldStringMap , StatsField :: valueOf ) ) ; }
Change into stats map stats map .
17,542
public String toTempFile ( ) throws IOException { File file = File . createTempFile ( UUID . randomUUID ( ) . toString ( ) , ".binary.tmp" ) ; file . deleteOnExit ( ) ; toFile ( file ) ; return file . getAbsolutePath ( ) ; }
Creates new temporary file with random name and returns full path to the file
17,543
public int toByteArray ( byte [ ] target , int targetOffset ) throws IOException { long length = length ( ) ; if ( ( long ) targetOffset + length > Integer . MAX_VALUE ) { throw new IOException ( "Unable to write - too big data" ) ; } if ( target . length < targetOffset + length ) { throw new IOException ( "Insufficient target byte array size" ) ; } if ( length < 0 ) { length = 0 ; int curOffset = targetOffset ; InputStream in = asStream ( ) ; try { int readbyte ; while ( ( readbyte = in . read ( ) ) != EOF ) { target [ curOffset ] = ( byte ) readbyte ; curOffset ++ ; length ++ ; } } finally { in . close ( ) ; } } else { System . arraycopy ( asByteArray ( false ) , 0 , target , targetOffset , ( int ) length ) ; } return ( int ) length ; }
Writes data to some existing byte array starting from specific offset
17,544
public String asBase64 ( ) throws IOException { return asBase64 ( BaseEncoding . Dialect . STANDARD , BaseEncoding . Padding . STANDARD ) ; }
Represent as Base 64 with standard dialect and standard padding
17,545
public String asBase64 ( BaseEncoding . Dialect dialect , BaseEncoding . Padding padding ) throws IOException { String standardBase64 = DatatypeConverter . printBase64Binary ( asByteArray ( false ) ) ; if ( dialect == BaseEncoding . Dialect . STANDARD && padding == BaseEncoding . Padding . STANDARD ) { return standardBase64 ; } StringBuilder safeBase64 = new StringBuilder ( standardBase64 . length ( ) ) ; for ( int i = 0 ; i < standardBase64 . length ( ) ; i ++ ) { char c = standardBase64 . charAt ( i ) ; if ( dialect == BaseEncoding . Dialect . SAFE ) { if ( c == '+' ) c = '-' ; else if ( c == '/' ) c = '_' ; } if ( c == '=' ) { if ( padding == BaseEncoding . Padding . STANDARD ) { safeBase64 . append ( '=' ) ; } else if ( padding == BaseEncoding . Padding . SAFE ) { safeBase64 . append ( '.' ) ; } } else { safeBase64 . append ( c ) ; } } return safeBase64 . toString ( ) ; }
Represent as Base 64 with customized dialect and padding
17,546
public static String serialize ( QueryCriterion queryCriterion ) { if ( queryCriterion instanceof EqualQueryCriterion ) { EqualQueryCriterion criterion = ( EqualQueryCriterion ) queryCriterion ; return criterion . getMetadataKey ( ) + " equals " + escapeString ( criterion . getCriterion ( ) ) ; } else if ( queryCriterion instanceof NotEqualQueryCriterion ) { NotEqualQueryCriterion criterion = ( NotEqualQueryCriterion ) queryCriterion ; return criterion . getMetadataKey ( ) + " not equals " + escapeString ( criterion . getCriterion ( ) ) ; } else if ( queryCriterion instanceof ContainQueryCriterion ) { ContainQueryCriterion criterion = ( ContainQueryCriterion ) queryCriterion ; return criterion . getMetadataKey ( ) ; } else if ( queryCriterion instanceof NotContainQueryCriterion ) { NotContainQueryCriterion criterion = ( NotContainQueryCriterion ) queryCriterion ; return "not " + criterion . getMetadataKey ( ) ; } else if ( queryCriterion instanceof InQueryCriterion ) { InQueryCriterion criterion = ( InQueryCriterion ) queryCriterion ; StringBuilder sb = new StringBuilder ( criterion . getMetadataKey ( ) ) ; sb . append ( " in [ " ) ; for ( String s : criterion . getCriterion ( ) ) { sb . append ( escapeString ( s ) ) . append ( ", " ) ; } sb . append ( "]" ) ; return sb . toString ( ) ; } else if ( queryCriterion instanceof NotInQueryCriterion ) { NotInQueryCriterion criterion = ( NotInQueryCriterion ) queryCriterion ; StringBuilder sb = new StringBuilder ( criterion . getMetadataKey ( ) ) ; sb . append ( " not in [ " ) ; for ( String s : criterion . getCriterion ( ) ) { sb . append ( escapeString ( s ) ) . append ( ", " ) ; } sb . append ( "]" ) ; return sb . toString ( ) ; } else if ( queryCriterion instanceof PatternQueryCriterion ) { PatternQueryCriterion criterion = ( PatternQueryCriterion ) queryCriterion ; return criterion . getMetadataKey ( ) + " matches " + escapeString ( criterion . getCriterion ( ) ) ; } return "" ; }
serialize the QueryCriterion to a String expression .
17,547
public static ServiceInstanceQuery deserializeServiceInstanceQuery ( String cli ) { char [ ] delimeter = { ';' } ; ServiceInstanceQuery query = new ServiceInstanceQuery ( ) ; for ( String statement : splitStringByDelimeters ( cli , delimeter , false ) ) { QueryCriterion criterion = deserialize ( statement ) ; if ( criterion != null ) { query . addQueryCriterion ( criterion ) ; } } ; return query ; }
Deserialize the ServiceInstanceQuery command line String expression .
17,548
public static String serializeServiceInstanceQuery ( ServiceInstanceQuery query ) { List < QueryCriterion > criteria = query . getCriteria ( ) ; StringBuilder sb = new StringBuilder ( ) ; for ( QueryCriterion criterion : criteria ) { String statement = serialize ( criterion ) ; if ( statement != null && ! statement . isEmpty ( ) ) { sb . append ( statement ) . append ( ";" ) ; } } return sb . toString ( ) ; }
Serialze the ServiceInstanceQuery to the command line string expression .
17,549
private static String unescapeString ( String str ) { if ( str . startsWith ( "\"" ) && str . endsWith ( "\"" ) ) { String s = str . replaceAll ( "\\\\\"" , "\"" ) ; return s . substring ( 1 , s . length ( ) - 1 ) ; } return null ; }
Unescape the QueryCriterion String .
17,550
private static List < String > filterDelimeterElement ( List < String > arr , char [ ] delimeter ) { List < String > list = new ArrayList < String > ( ) ; for ( String s : arr ) { if ( s == null || s . isEmpty ( ) ) { continue ; } if ( s . length ( ) > 1 ) { list . add ( s ) ; continue ; } char strChar = s . charAt ( 0 ) ; boolean find = false ; for ( char c : delimeter ) { if ( c == strChar ) { find = true ; break ; } } if ( find == false ) { list . add ( s ) ; } } return list ; }
Filter the delimeter from the String array .
17,551
private static List < String > splitStringByDelimeters ( String str , char [ ] delimeter , boolean includeDeli ) { List < String > arr = new ArrayList < String > ( ) ; int i = 0 , start = 0 , quota = 0 ; char pre = 0 ; for ( char c : str . toCharArray ( ) ) { if ( c == '"' && pre != '\\' ) { quota ++ ; } if ( quota % 2 == 0 ) { for ( char deli : delimeter ) { if ( c == deli ) { if ( includeDeli ) { arr . add ( str . substring ( start , i ) . trim ( ) ) ; start = i ; } else if ( i > start ) { arr . add ( str . substring ( start , i ) . trim ( ) ) ; start = i + 1 ; } } } } i ++ ; pre = c ; } if ( includeDeli ) { arr . add ( str . substring ( start , i ) . trim ( ) ) ; start = i ; } else if ( i > start ) { arr . add ( str . substring ( start , i ) . trim ( ) ) ; } return arr ; }
Split a complete String to String array by the delimeter array .
17,552
public CharTrie deserialize ( byte [ ] bytes ) { CharTrie trie = new CharTrie ( ) ; BitInputStream in = new BitInputStream ( new ByteArrayInputStream ( bytes ) ) ; int level = 0 ; while ( deserialize ( trie . root ( ) , in , level ++ ) > 0 ) { } trie . recomputeCursorDetails ( ) ; return trie ; }
Deserialize char trie .
17,553
private String getFileName ( MultivaluedMap < String , String > header ) { String [ ] contentDisposition = header . getFirst ( "Content-Disposition" ) . split ( ";" ) ; for ( String filename : contentDisposition ) { if ( ( filename . trim ( ) . startsWith ( "filename" ) ) ) { String [ ] name = filename . split ( "=" ) ; String finalFileName = name [ 1 ] . trim ( ) . replaceAll ( "\"" , "" ) ; return finalFileName ; } } return "unknown" ; }
get uploaded filename is there a easy way in RESTEasy?
17,554
private void checkVersion ( final Future < Boolean > aFuture ) { final String versionFilePath = getVersionFilePath ( ) ; myFileSystem . exists ( versionFilePath , result -> { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( MessageCodes . PT_DEBUG_007 , versionFilePath ) ; } if ( result . succeeded ( ) ) { if ( result . result ( ) ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( MessageCodes . PT_DEBUG_008 , versionFilePath ) ; } checkPrefix ( aFuture ) ; } else { aFuture . complete ( ! result . result ( ) ) ; } } else { aFuture . fail ( result . cause ( ) ) ; } } ) ; }
Checks that Pairtree version file exists .
17,555
private void checkPrefix ( final Future < Boolean > aFuture ) { final String prefixFilePath = getPrefixFilePath ( ) ; myFileSystem . exists ( prefixFilePath , result -> { if ( result . succeeded ( ) ) { if ( hasPrefix ( ) ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( MessageCodes . PT_DEBUG_035 , prefixFilePath ) ; } if ( result . result ( ) ) { aFuture . complete ( result . result ( ) ) ; } else { aFuture . fail ( new PairtreeException ( MessageCodes . PT_013 , prefixFilePath ) ) ; } } else { LOGGER . debug ( MessageCodes . PT_DEBUG_009 , prefixFilePath ) ; if ( result . result ( ) ) { aFuture . fail ( new PairtreeException ( MessageCodes . PT_014 , prefixFilePath ) ) ; } else { aFuture . complete ( ! result . result ( ) ) ; } } } else { aFuture . fail ( result . cause ( ) ) ; } } ) ; }
Checks whether a Pairtree prefix file exists .
17,556
private void deleteVersion ( final Future < Void > aFuture ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( MessageCodes . PT_DEBUG_006 , myPath ) ; } myFileSystem . delete ( getVersionFilePath ( ) , result -> { if ( result . succeeded ( ) ) { if ( hasPrefix ( ) ) { deletePrefix ( aFuture ) ; } else { aFuture . complete ( ) ; } } else { aFuture . fail ( result . cause ( ) ) ; } } ) ; }
Deletes a Pairtree version file .
17,557
private void deletePrefix ( final Future < Void > aFuture ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( MessageCodes . PT_DEBUG_034 , myPath ) ; } myFileSystem . delete ( getPrefixFilePath ( ) , result -> { if ( result . succeeded ( ) ) { aFuture . complete ( ) ; } else { aFuture . fail ( result . cause ( ) ) ; } } ) ; }
Deletes a Pairtree prefix file .
17,558
private void setVersion ( final Future < Void > aFuture ) { final StringBuilder specNote = new StringBuilder ( ) ; final String ptVersion = LOGGER . getMessage ( MessageCodes . PT_011 , PT_VERSION_NUM ) ; final String urlString = LOGGER . getMessage ( MessageCodes . PT_012 ) ; specNote . append ( ptVersion ) . append ( System . lineSeparator ( ) ) . append ( urlString ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( MessageCodes . PT_DEBUG_005 , myPath ) ; } myFileSystem . writeFile ( getVersionFilePath ( ) , Buffer . buffer ( specNote . toString ( ) ) , result -> { if ( result . succeeded ( ) ) { if ( hasPrefix ( ) ) { setPrefix ( aFuture ) ; } else { aFuture . complete ( ) ; } } else { aFuture . fail ( result . cause ( ) ) ; } } ) ; }
Creates a Pairtree version file .
17,559
private void setPrefix ( final Future < Void > aFuture ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( MessageCodes . PT_DEBUG_033 , myPath ) ; } myFileSystem . writeFile ( getPrefixFilePath ( ) , Buffer . buffer ( myPrefix . get ( ) ) , result -> { if ( result . succeeded ( ) ) { aFuture . complete ( ) ; } else { aFuture . fail ( result . cause ( ) ) ; } } ) ; }
Creates a Pairtree prefix file .
17,560
public void weakAddWatcher ( Listener watcher ) { if ( watcher == null ) { throw new IllegalArgumentException ( "Null watcher added" ) ; } synchronized ( mutex ) { if ( watcherExecutor . isShutdown ( ) ) { throw new IllegalStateException ( "Adding watcher on closed FileWatcher" ) ; } watchers . add ( new WeakReference < > ( watcher ) :: get ) ; } }
Add a non - persistent file watcher .
17,561
public boolean removeWatcher ( Listener watcher ) { if ( watcher == null ) { throw new IllegalArgumentException ( "Null watcher removed" ) ; } synchronized ( mutex ) { AtomicBoolean removed = new AtomicBoolean ( removeFromListeners ( watchers , watcher ) ) ; watchedFiles . forEach ( ( path , suppliers ) -> { if ( removeFromListeners ( suppliers , watcher ) ) { removed . set ( true ) ; } } ) ; return removed . get ( ) ; } }
Remove a watcher from the list of listeners .
17,562
public void startWatching ( File file ) { if ( file == null ) { throw new IllegalArgumentException ( "Null file argument" ) ; } synchronized ( mutex ) { startWatchingInternal ( file . toPath ( ) ) ; } }
Start watching a specific file . Note that this will watch the file as seen in the directory as it is pointed to . This means that if the file itself is a symlink then change events will notify changes to the symlink definition not the content of the file .
17,563
public void stopWatching ( File file ) { if ( file == null ) { throw new IllegalArgumentException ( "Null file argument" ) ; } synchronized ( mutex ) { stopWatchingInternal ( file . toPath ( ) ) ; } }
Stop watching a specific file .
17,564
public static String phrase ( int minSize , int maxSize ) { maxSize = Math . max ( minSize , maxSize ) ; int size = RandomInteger . nextInteger ( minSize , maxSize ) ; if ( size <= 0 ) return "" ; StringBuilder result = new StringBuilder ( ) ; result . append ( RandomString . pick ( _allWords ) ) ; while ( result . length ( ) < size ) { result . append ( " " ) . append ( RandomString . pick ( _allWords ) . toLowerCase ( ) ) ; } return result . toString ( ) ; }
Generates a random phrase which consists of few words separated by spaces . The first word is capitalized others are not .
17,565
public static String fullName ( ) { StringBuilder result = new StringBuilder ( ) ; if ( RandomBoolean . chance ( 3 , 5 ) ) result . append ( RandomString . pick ( _namePrefixes ) ) . append ( " " ) ; result . append ( RandomString . pick ( _firstNames ) ) . append ( " " ) . append ( RandomString . pick ( _lastNames ) ) ; if ( RandomBoolean . chance ( 5 , 10 ) ) result . append ( " " ) . append ( RandomString . pick ( _nameSuffixes ) ) ; return result . toString ( ) ; }
Generates a random person s name which has the following structure optional prefix - first name - second name - optional suffix
17,566
public static String words ( int min , int max ) { StringBuilder result = new StringBuilder ( ) ; int count = RandomInteger . nextInteger ( min , max ) ; for ( int i = 0 ; i < count ; i ++ ) result . append ( RandomString . pick ( _allWords ) ) ; return result . toString ( ) ; }
Generates a random text that consists of random number of random words separated by spaces .
17,567
public static String text ( int minSize , int maxSize ) { maxSize = Math . max ( minSize , maxSize ) ; int size = RandomInteger . nextInteger ( minSize , maxSize ) ; StringBuilder result = new StringBuilder ( ) ; result . append ( RandomString . pick ( _allWords ) ) ; while ( result . length ( ) < size ) { String next = RandomString . pick ( _allWords ) ; if ( RandomBoolean . chance ( 4 , 6 ) ) next = " " + next . toLowerCase ( ) ; else if ( RandomBoolean . chance ( 2 , 5 ) ) next = RandomString . pickChar ( ":,-" ) + next . toLowerCase ( ) ; else if ( RandomBoolean . chance ( 3 , 5 ) ) next = RandomString . pickChar ( ":,-" ) + " " + next . toLowerCase ( ) ; else next = RandomString . pickChar ( ".!?" ) + " " + next ; result . append ( next ) ; } return result . toString ( ) ; }
Generates a random text consisting of first names last names colors stuffs adjectives verbs and punctuation marks .
17,568
public StringGrabber set ( String str ) { if ( str == null ) { str = "" ; } return set ( new StringBuilder ( str ) ) ; }
set new source of string to this class
17,569
public StringGrabber set ( StringBuilder stringBuilder ) { if ( stringBuilder == null ) { stringBuilder = new StringBuilder ( ) ; } sb = stringBuilder ; return StringGrabber . this ; }
set new source of stringbuilder to this class
17,570
public StringGrabber removeHead ( int cnt ) { try { sb . delete ( 0 , cnt ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return StringGrabber . this ; }
remove N chars from head
17,571
public StringGrabber removeTail ( int cnt ) { int leng = sb . length ( ) ; try { sb . delete ( leng - cnt , leng ) ; } catch ( Exception e ) { } return StringGrabber . this ; }
remove N chars from tail
17,572
public StringGrabber removeHeadConsecutiveChars ( char charToRemove ) { boolean loop = true ; if ( sb . length ( ) > 0 ) { while ( loop ) { if ( sb . charAt ( 0 ) == charToRemove ) { removeHead ( 1 ) ; } else { loop = false ; } } } return StringGrabber . this ; }
remove consecutive chars placed at the head
17,573
public StringGrabber removeTailConsecutiveChars ( char charToRemove ) { boolean loop = true ; if ( sb . length ( ) > 0 ) { while ( loop ) { if ( sb . charAt ( sb . length ( ) - 1 ) == charToRemove ) { removeTail ( 1 ) ; } else { loop = false ; } } } return StringGrabber . this ; }
remove consecutive chars placed at tail end .
17,574
public StringGrabber insertIntoHead ( String str ) { if ( str != null ) { try { sb . insert ( 0 , str ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } return StringGrabber . this ; }
Insert string into the first
17,575
public StringGrabber left ( int charCount ) { String str = getCropper ( ) . getLeftOf ( sb . toString ( ) , charCount ) ; sb = new StringBuilder ( str ) ; return StringGrabber . this ; }
returns a new string that is a substring of this string from left .
17,576
public StringGrabber right ( int charCount ) { String str = getCropper ( ) . getRightOf ( sb . toString ( ) , charCount ) ; sb = new StringBuilder ( str ) ; return StringGrabber . this ; }
returns a new string that is a substring of this string from right .
17,577
public StringGrabber replace ( String target , String replacement ) { sb = new StringBuilder ( sb . toString ( ) . replace ( target , replacement ) ) ; return StringGrabber . this ; }
replace specified string
17,578
public StringGrabber replaceEnclosedIn ( String startToken , String endToken , String replacement ) { StringCropper cropper = getCropper ( ) ; final List < StrPosition > stringEnclosedInWithDetails = cropper . getStringEnclosedInWithDetails ( sb . toString ( ) , startToken , endToken ) ; final List < Integer > splitList = new ArrayList < Integer > ( ) ; for ( StrPosition sp : stringEnclosedInWithDetails ) { int splitPointFirst = sp . startIndex - 1 ; int splitPointSecond = sp . endIndex ; splitList . add ( splitPointFirst ) ; splitList . add ( splitPointSecond ) ; } final Integer [ ] splitIndexes = splitList . toArray ( new Integer [ ] { } ) ; List < String > splitStringList = cropper . splitByIndex ( sb . toString ( ) , splitIndexes ) ; final StringBuilder tempSb = new StringBuilder ( ) ; final int strNum = splitStringList . size ( ) ; boolean nextIsValue = false ; int countOfReplacement = 0 ; for ( int i = 0 ; i < strNum ; i ++ ) { String strPart = splitStringList . get ( i ) ; if ( nextIsValue ) { tempSb . append ( replacement ) ; countOfReplacement ++ ; if ( strPart . startsWith ( endToken ) ) { tempSb . append ( strPart ) ; } } else { tempSb . append ( strPart ) ; } if ( strPart . endsWith ( startToken ) ) { nextIsValue = true ; } else { nextIsValue = false ; } } sb = tempSb ; return StringGrabber . this ; }
replace specified string enclosed in speficied token
17,579
public StringGrabber substring ( int startIdx , int endIndex ) { if ( startIdx < 0 ) { startIdx = 0 ; } if ( endIndex > length ( ) - 1 ) { endIndex = length ( ) - 1 ; } sb = new StringBuilder ( substringInternally ( startIdx , endIndex ) ) ; return StringGrabber . this ; }
returns substring specified with start index and endIndex
17,580
public int toInt ( int defaultValue ) { try { return Integer . parseInt ( sb . toString ( ) ) ; } catch ( java . lang . NumberFormatException e ) { e . printStackTrace ( ) ; } return defaultValue ; }
returns int value when format error occurred returns default value
17,581
public double toDouble ( double defaultValue ) { try { return Double . parseDouble ( sb . toString ( ) ) ; } catch ( java . lang . NumberFormatException e ) { } return defaultValue ; }
returns double value when format error occurred returns default value
17,582
public float toFloat ( float defaultValue ) { try { return Float . parseFloat ( sb . toString ( ) ) ; } catch ( java . lang . NumberFormatException e ) { } return defaultValue ; }
returns float value when format error occurred returns default value
17,583
public StringGrabber appendRepeat ( String str , int repeatCount ) { for ( int i = 0 ; i < repeatCount ; i ++ ) { if ( str != null ) { sb . append ( str ) ; } } return StringGrabber . this ; }
Append a string to be repeated
17,584
public StringGrabber insertRepeat ( String str , int repeatCount ) { for ( int i = 0 ; i < repeatCount ; i ++ ) { insertIntoHead ( str ) ; } return StringGrabber . this ; }
Append a string to be repeated into head
17,585
public StringGrabberList split ( String regexp ) { final StringGrabberList retList = new StringGrabberList ( ) ; final String string = sb . toString ( ) ; String [ ] splitedStrings = string . split ( regexp ) ; for ( String str : splitedStrings ) { retList . add ( new StringGrabber ( str ) ) ; } return retList ; }
Splits this string around matches of the given regular expression .
17,586
public static < T > void dump ( Iterable < Difference < T > > diffs ) { for ( Difference < T > diff : diffs ) { System . out . println ( diff ) ; } }
prints to stdout all differences on a new line
17,587
public static < T > void dumpUnchanged ( Iterable < Difference < T > > diffs ) { for ( Difference < T > diff : diffs ) { if ( Difference . Type . UNCHANGED . equals ( diff . getType ( ) ) ) { System . out . println ( diff ) ; } } }
prints to stdout all UNCHANGED differences on a new line
17,588
public static Map < String , Long > getCountMap ( Collection < String > stringCollection ) { return unmodifiableMap ( countBy ( stringCollection ) ) ; }
Gets count map .
17,589
public static List < String > getSortedStringList ( Collection < String > stringCollection ) { return unmodifiableList ( sort ( new ArrayList < > ( stringCollection ) ) ) ; }
Gets sorted string list .
17,590
public boolean exactMatch ( Descriptor descriptor ) { return exactMatchField ( _group , descriptor . getGroup ( ) ) && exactMatchField ( _type , descriptor . getType ( ) ) && exactMatchField ( _kind , descriptor . getKind ( ) ) && exactMatchField ( _name , descriptor . getName ( ) ) && exactMatchField ( _version , descriptor . getVersion ( ) ) ; }
Matches this descriptor to another descriptor by all fields . No exceptions are made .
17,591
public static Descriptor fromString ( String value ) throws ConfigException { if ( value == null || value . length ( ) == 0 ) return null ; String [ ] tokens = value . split ( ":" ) ; if ( tokens . length != 5 ) { throw ( ConfigException ) new ConfigException ( null , "BAD_DESCRIPTOR" , "Descriptor " + value + " is in wrong format" ) . withDetails ( "descriptor" , value ) ; } return new Descriptor ( tokens [ 0 ] . trim ( ) , tokens [ 1 ] . trim ( ) , tokens [ 2 ] . trim ( ) , tokens [ 3 ] . trim ( ) , tokens [ 4 ] . trim ( ) ) ; }
Parses colon - separated list of descriptor fields and returns them as a Descriptor .
17,592
public static void infoAndDebug ( Logger log , String methodName , Object ... params ) { if ( ! log . isInfoEnabled ( ) ) return ; int length = params . length ; Object [ ] newParams = new Object [ length ] ; boolean hasCollection = false ; for ( int i = 0 ; i < length ; i ++ ) { if ( params [ i ] instanceof Collection ) { newParams [ i ] = ( ( ( Collection < ? > ) params [ i ] ) . size ( ) ) ; hasCollection = true ; } else newParams [ i ] = params [ i ] ; } if ( hasCollection ) log . info ( buildMethodLogString ( methodName , newParams ) ) ; log . debug ( buildMethodLogString ( methodName , params ) ) ; }
Info and debug .
17,593
public static void errorForException ( Logger log , Throwable throwable , String methodName ) { log . error ( buildMethodLogString ( methodName ) , throwable ) ; }
Error for exception .
17,594
public Object addToListOption ( String key , Object value ) { if ( key != null && ! key . equals ( "" ) ) { if ( this . containsKey ( key ) && this . get ( key ) != null ) { if ( ! ( this . get ( key ) instanceof List ) ) { this . put ( key , new ArrayList < > ( this . getAsList ( key ) ) ) ; } try { this . getList ( key ) . add ( value ) ; } catch ( UnsupportedOperationException e ) { List < Object > list = new ArrayList < > ( this . getList ( key ) ) ; list . add ( value ) ; this . put ( key , list ) ; } } else { List < Object > list = new ArrayList < > ( ) ; list . add ( value ) ; this . put ( key , list ) ; } return this . getList ( key ) ; } return null ; }
This method safely add a new Object to an exiting option which type is List .
17,595
public void setScreenshotFolder ( final File folder ) { this . directory = folder ; boolean created = directory . mkdirs ( ) ; LOG . info ( "Screenshot folder created succsessfully: " + created ) ; }
Set the folder where we save screenshots .
17,596
private File filenameFor ( final Description method ) { String className = method . getClassName ( ) ; String methodName = method . getMethodName ( ) ; return new File ( directory , className + "_" + methodName + ".png" ) ; }
Gets the name of the image file with the screenshot .
17,597
private void silentlySaveScreenshotTo ( final File file ) { try { saveScreenshotTo ( file ) ; LOG . info ( "Screenshot saved: " + file . getAbsolutePath ( ) ) ; } catch ( Exception e ) { LOG . warn ( "Error while taking screenshot " + file . getName ( ) + ": " + e ) ; } }
Saves the actual screenshot without interrupting the running of the tests . It will log an error if unable to store take the screenshot .
17,598
private void saveScreenshotTo ( final File file ) throws IOException { byte [ ] bytes = null ; try { bytes = ( ( TakesScreenshot ) driver ) . getScreenshotAs ( OutputType . BYTES ) ; } catch ( ClassCastException e ) { WebDriver augmentedDriver = new Augmenter ( ) . augment ( driver ) ; bytes = ( ( TakesScreenshot ) augmentedDriver ) . getScreenshotAs ( OutputType . BYTES ) ; } Files . write ( bytes , file ) ; }
Saves the screenshot to the file .
17,599
public static void prepareForLogging ( HttpServletRequest request ) { MDC . put ( "timestamp" , System . currentTimeMillis ( ) + "" ) ; MDC . put ( "request_id" , UUID . randomUUID ( ) . toString ( ) ) ; MDC . put ( "request" , request . getRequestURI ( ) ) ; MDC . put ( "ip" , RequestUtils . getClientIpAddress ( request ) ) ; MDC . put ( "user_agent" , RequestUtils . getUserAgent ( request ) ) ; MDC . put ( "method" , request . getMethod ( ) ) ; MDC . put ( "host" , request . getServerName ( ) ) ; MDC . put ( "scheme" , RequestUtils . getScheme ( request ) ) ; MDC . put ( "domain" , UrlUtils . resolveDomain ( request . getServerName ( ) ) ) ; MDC . put ( "port" , request . getServerPort ( ) + "" ) ; MDC . put ( "path" , request . getContextPath ( ) + request . getPathInfo ( ) ) ; if ( request . getUserPrincipal ( ) != null ) { MDC . put ( "user" , request . getUserPrincipal ( ) != null ? request . getUserPrincipal ( ) . getName ( ) : null ) ; } if ( ! StringUtils . isNullOrEmptyTrimmed ( request . getQueryString ( ) ) ) { MDC . put ( "query" , request . getQueryString ( ) ) ; } }
Fills up MDC with request info