idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
138,200
public SmartHandle returnValue ( Class < ? > type , Object value ) { return new SmartHandle ( signature . changeReturn ( type ) , MethodHandles . filterReturnValue ( handle , MethodHandles . constant ( type , value ) ) ) ; }
Replace the return value with the given value performing no other processing of the original value .
53
18
138,201
public static String toJSON ( Object value , ObjectMapper mapper ) { try { return mapper . writeValueAsString ( value ) ; } catch ( IOException ex ) { throw new FacebookException ( ex ) ; } }
Converts the object to a JSON string using the mapper
48
12
138,202
public static JsonNode toNode ( String value , ObjectMapper mapper ) { try { return mapper . readTree ( value ) ; } catch ( IOException ex ) { throw new FacebookException ( ex ) ; } }
Parses a string into a JsonNode using the mapper
48
14
138,203
public static String stringifyValue ( Param param , ObjectMapper mapper ) { assert ! ( param instanceof BinaryParam ) ; if ( param . value instanceof String ) return ( String ) param . value ; if ( param . value instanceof Date ) return Long . toString ( ( ( Date ) param . value ) . getTime ( ) / 1000 ) ; else if ( param . value instanceof Number ) return param . value . toString ( ) ; else return JSONUtils . toJSON ( param . value , mapper ) ; }
Stringify the parameter value in an appropriate way . Note that Facebook fucks up dates by using unix time - since - epoch some places and ISO - 8601 others . However maybe unix times always work as parameters?
114
45
138,204
public static String read ( InputStream input ) { try { StringBuilder bld = new StringBuilder ( ) ; Reader reader = new InputStreamReader ( input , "utf-8" ) ; int ch ; while ( ( ch = reader . read ( ) ) >= 0 ) bld . append ( ( char ) ch ) ; return bld . toString ( ) ; } catch ( IOException ex ) { throw new RuntimeException ( ex ) ; } }
Reads an input stream into a String encoding with UTF - 8
95
13
138,205
public static Binder from ( MethodHandles . Lookup lookup , Binder start ) { return new Binder ( lookup , start ) ; }
Construct a new Binder starting from a given invokebinder .
30
13
138,206
public Binder to ( Binder other ) { assert type ( ) . equals ( other . start ) ; Binder newBinder = new Binder ( this ) ; for ( ListIterator < Transform > iter = other . transforms . listIterator ( other . transforms . size ( ) ) ; iter . hasPrevious ( ) ; ) { Transform t = iter . previous ( ) ; newBinder . add ( t ) ; } return newBinder ; }
Join this binder to an existing one by applying its transformations after this one .
94
16
138,207
private void add ( Transform transform , MethodType target ) { types . add ( 0 , target ) ; transforms . add ( 0 , transform ) ; }
Add a Transform with an associated MethodType target to the chain .
31
13
138,208
public Binder insert ( int index , Class < ? > type , Object value ) { return new Binder ( this , new Insert ( index , new Class [ ] { type } , value ) ) ; }
Insert at the given index the given argument value .
43
10
138,209
public Binder append ( Class < ? > type , Object value ) { return new Binder ( this , new Insert ( type ( ) . parameterCount ( ) , new Class [ ] { type } , value ) ) ; }
Append to the argument list the given argument value with the specified type .
47
15
138,210
public Binder append ( Class < ? > [ ] types , Object ... values ) { return new Binder ( this , new Insert ( type ( ) . parameterCount ( ) , types , values ) ) ; }
Append to the argument list the given argument values with the specified types .
44
15
138,211
public Binder prepend ( Class < ? > type , Object value ) { return new Binder ( this , new Insert ( 0 , new Class [ ] { type } , value ) ) ; }
Prepend to the argument list the given argument value with the specified type
41
14
138,212
public Binder prepend ( Class < ? > [ ] types , Object ... values ) { return new Binder ( this , new Insert ( 0 , types , values ) ) ; }
Prepend to the argument list the given argument values with the specified types .
38
15
138,213
public Binder drop ( int index , int count ) { return new Binder ( this , new Drop ( index , Arrays . copyOfRange ( type ( ) . parameterArray ( ) , index , index + count ) ) ) ; }
Drop from the given index a number of arguments .
50
10
138,214
public Binder dropLast ( int count ) { assert count <= type ( ) . parameterCount ( ) ; return drop ( type ( ) . parameterCount ( ) - count , count ) ; }
Drop from the end of the argument list a number of arguments .
40
13
138,215
public Binder spread ( Class < ? > ... spreadTypes ) { if ( spreadTypes . length == 0 ) { return dropLast ( ) ; } return new Binder ( this , new Spread ( type ( ) , spreadTypes ) ) ; }
Spread a trailing array argument into the specified argument types .
51
11
138,216
public Binder spread ( int count ) { if ( count == 0 ) { return dropLast ( ) ; } Class < ? > aryType = type ( ) . parameterType ( type ( ) . parameterCount ( ) - 1 ) ; assert aryType . isArray ( ) ; Class < ? > [ ] spreadTypes = new Class [ count ] ; Arrays . fill ( spreadTypes , aryType . getComponentType ( ) ) ; return spread ( spreadTypes ) ; }
Spread a trailing array argument into the given number of arguments of the type of the array .
102
18
138,217
public Binder collect ( int index , Class < ? > type ) { return new Binder ( this , new Collect ( type ( ) , index , type ) ) ; }
Box all incoming arguments from the given position onward into the given array type .
36
15
138,218
public Binder varargs ( int index , Class < ? > type ) { return new Binder ( this , new Varargs ( type ( ) , index , type ) ) ; }
Box all incoming arguments from the given position onward into the given array type . This version accepts a variable number of incoming arguments .
38
25
138,219
public Binder foldVoid ( MethodHandle function ) { if ( type ( ) . returnType ( ) == void . class ) { return fold ( function ) ; } else { return fold ( function . asType ( function . type ( ) . changeReturnType ( void . class ) ) ) ; } }
Process the incoming arguments using the given handle leaving the argument list unmodified .
64
15
138,220
public Binder foldVirtual ( MethodHandles . Lookup lookup , String method ) { return fold ( Binder . from ( type ( ) ) . invokeVirtualQuiet ( lookup , method ) ) ; }
Process the incoming arguments by calling the given method on the first argument inserting the result as the first argument .
43
21
138,221
public Binder filterForward ( int index , MethodHandle ... functions ) { Binder filtered = this ; for ( int i = 0 ; i < functions . length ; i ++ ) { filtered = filtered . filter ( index + i , functions [ i ] ) ; } return filtered ; }
Filter incoming arguments from the given index replacing each with the result of calling the associated function in the given list . This version guarantees left - to - right evaluation of filter functions potentially at the cost of a more complex handle tree .
59
45
138,222
public Binder catchException ( Class < ? extends Throwable > throwable , MethodHandle function ) { return new Binder ( this , new Catch ( throwable , function ) ) ; }
Catch the given exception type from the downstream chain and handle it with the given function .
39
18
138,223
public MethodHandle nop ( ) { if ( type ( ) . returnType ( ) != void . class ) { throw new InvalidTransformException ( "must have void return type to nop: " + type ( ) ) ; } return invoke ( Binder . from ( type ( ) ) . drop ( 0 , type ( ) . parameterCount ( ) ) . cast ( Object . class ) . constant ( null ) ) ; }
Apply all transforms to an endpoint that does absolutely nothing . Useful for creating exception handlers in void methods that simply ignore the exception .
89
25
138,224
public MethodHandle throwException ( ) { if ( type ( ) . parameterCount ( ) != 1 || ! Throwable . class . isAssignableFrom ( type ( ) . parameterType ( 0 ) ) ) { throw new InvalidTransformException ( "incoming signature must have one Throwable type as its sole argument: " + type ( ) ) ; } return invoke ( MethodHandles . throwException ( type ( ) . returnType ( ) , type ( ) . parameterType ( 0 ) . asSubclass ( Throwable . class ) ) ) ; }
Throw the current signature s sole Throwable argument . Return type does not matter since it will never return .
116
21
138,225
public MethodHandle constant ( Object value ) { return invoke ( MethodHandles . constant ( type ( ) . returnType ( ) , value ) ) ; }
Apply the tranforms binding them to a constant value that will propagate back through the chain . The chain s expected return type at that point must be compatible with the given value s type .
32
38
138,226
public MethodHandle invoke ( MethodHandle target ) { MethodHandle current = target ; for ( Transform t : transforms ) { current = t . up ( current ) ; } // if resulting handle's type does not match start, attempt one more cast current = MethodHandles . explicitCastArguments ( current , start ) ; return current ; }
Apply the chain of transforms with the target method handle as the final endpoint . Produces a handle that has the transforms in given sequence .
69
27
138,227
public MethodHandle arrayAccess ( VarHandle . AccessMode mode ) { return invoke ( MethodHandles . arrayElementVarHandle ( type ( ) . parameterType ( 0 ) ) . toMethodHandle ( mode ) ) ; }
Apply the chain of transforms and bind them to an array varhandle operation . The signature at the endpoint must match the VarHandle access type passed in .
46
30
138,228
public MethodHandle branch ( MethodHandle test , MethodHandle truePath , MethodHandle falsePath ) { return invoke ( MethodHandles . guardWithTest ( test , truePath , falsePath ) ) ; }
Apply the chain of transforms and bind them to a boolean branch as from java . lang . invoke . MethodHandles . guardWithTest . As with GWT the current endpoint signature must match the given target and fallback signatures .
42
46
138,229
public String toJava ( MethodType incoming ) { StringBuilder builder = new StringBuilder ( ) ; boolean second = false ; for ( Transform transform : transforms ) { if ( second ) builder . append ( ' ' ) ; second = true ; builder . append ( transform . toJava ( incoming ) ) ; } return builder . toString ( ) ; }
Produce Java code that would perform equivalent operations to this binder .
72
14
138,230
@ Override public HttpResponse execute ( ) throws IOException { if ( this . method == HttpMethod . GET ) { String url = this . toString ( ) ; if ( url . length ( ) > this . cutoff ) { if ( log . isLoggable ( Level . FINER ) ) log . finer ( "URL length " + url . length ( ) + " too long, converting GET to POST: " + url ) ; String rebase = this . baseURL + "?method=GET" ; return this . execute ( HttpMethod . POST , rebase ) ; } } return super . execute ( ) ; }
Replace excessively - long GET requests with a POST .
135
11
138,231
private < T > GraphRequest < T > graph ( String object , JavaType type , Param ... params ) { this . checkForBatchExecution ( ) ; // The data is transformed through a chain of wrappers GraphRequest < T > req = new GraphRequest < T > ( object , params , this . mapper , this . < T > createMappingChain ( type ) ) ; this . graphRequests . add ( req ) ; return req ; }
The actual implementation of this after we ve converted to proper Jackson JavaType
97
14
138,232
private < T > QueryRequest < T > query ( String fql , JavaType type ) { this . checkForBatchExecution ( ) ; if ( this . multiqueryRequest == null ) { this . multiqueryRequest = new MultiqueryRequest ( mapper , this . createUnmappedChain ( ) ) ; this . graphRequests . add ( this . multiqueryRequest ) ; } // There is a circular reference between the extractor and request, so construction of the chain // is a little complicated QueryNodeExtractor extractor = new QueryNodeExtractor ( this . multiqueryRequest ) ; String name = "__q" + this . generatedQueryNameIndex ++ ; QueryRequest < T > q = new QueryRequest < T > ( fql , name , new MapperWrapper < T > ( type , this . mapper , extractor ) ) ; extractor . setRequest ( q ) ; this . multiqueryRequest . addQuery ( q ) ; return q ; }
Implementation now that we have chosen a Jackson JavaType for the return value
213
15
138,233
private < T > MapperWrapper < T > createMappingChain ( JavaType type ) { return new MapperWrapper < T > ( type , this . mapper , this . createUnmappedChain ( ) ) ; }
Adds mapping to the basic unmapped chain .
50
9
138,234
private ErrorDetectingWrapper createUnmappedChain ( ) { int nextIndex = this . graphRequests . size ( ) ; return new ErrorDetectingWrapper ( new GraphNodeExtractor ( nextIndex , this . mapper , new ErrorDetectingWrapper ( this ) ) ) ; }
Creates the common chain of wrappers that will select out one graph request from the batch and error check it both at the batch level and at the individual request level . Result will be an unmapped JsonNode .
63
44
138,235
private Later < JsonNode > getRawBatchResult ( ) { if ( this . rawBatchResult == null ) { // Use LaterWrapper to cache the result so we don't fetch over and over this . rawBatchResult = new LaterWrapper < JsonNode , JsonNode > ( this . createFetcher ( ) ) ; // Also let the master know it's time to kick off any other batches and // remove us as a valid batch to add to. // This must be called *after* the rawBatchResult is set otherwise we // will have endless recursion when the master tries to execute us. this . master . execute ( ) ; } return this . rawBatchResult ; }
Get the batch result firing it off if necessary
151
9
138,236
private Later < JsonNode > createFetcher ( ) { final RequestBuilder call = new GraphRequestBuilder ( getGraphEndpoint ( ) , HttpMethod . POST , this . timeout , this . retries ) ; // This actually creates the correct JSON structure as an array String batchValue = JSONUtils . toJSON ( this . graphRequests , this . mapper ) ; if ( log . isLoggable ( Level . FINEST ) ) log . finest ( "Batch request is: " + batchValue ) ; this . addParams ( call , new Param [ ] { new Param ( "batch" , batchValue ) } ) ; final HttpResponse response ; try { response = call . execute ( ) ; } catch ( IOException ex ) { throw new IOFacebookException ( ex ) ; } return new Later < JsonNode > ( ) { @ Override public JsonNode get ( ) throws FacebookException { try { if ( response . getResponseCode ( ) == HttpURLConnection . HTTP_OK || response . getResponseCode ( ) == HttpURLConnection . HTTP_BAD_REQUEST || response . getResponseCode ( ) == HttpURLConnection . HTTP_UNAUTHORIZED ) { // If it was an error, we will recognize it in the content later. // It's possible we should capture all 4XX codes here. JsonNode result = mapper . readTree ( response . getContentStream ( ) ) ; if ( log . isLoggable ( Level . FINEST ) ) log . finest ( "Response is: " + result ) ; return result ; } else { throw new IOFacebookException ( "Unrecognized error " + response . getResponseCode ( ) + " from " + call + " :: " + StringUtils . read ( response . getContentStream ( ) ) ) ; } } catch ( IOException e ) { throw new IOFacebookException ( "Error calling " + call , e ) ; } } } ; }
Constructs the batch query and executes it possibly asynchronously .
422
13
138,237
private void throwPageMigratedException ( String msg , int code , int subcode , String userTitle , String userMsg ) { // This SUCKS ASS. Messages look like: // (#21) Page ID 114267748588304 was migrated to page ID 111013272313096. Please update your API calls to the new ID Matcher matcher = ID_PATTERN . matcher ( msg ) ; long oldId = this . extractNextId ( matcher , msg ) ; long newId = this . extractNextId ( matcher , msg ) ; throw new PageMigratedException ( msg , code , subcode , userTitle , userMsg , oldId , newId ) ; }
Builds the proper exception and throws it .
148
9
138,238
private long extractNextId ( Matcher matcher , String msg ) { if ( ! matcher . find ( ) ) throw new IllegalStateException ( "Facebook changed the error msg for page migration to something unfamiliar. The new msg is: " + msg ) ; String idStr = matcher . group ( ) . substring ( "ID " . length ( ) ) ; return Long . parseLong ( idStr ) ; }
Gets the next id out of the matcher
88
10
138,239
protected void throwCodeAndMessage ( int code , String msg ) { switch ( code ) { case 0 : case 101 : case 102 : case 190 : throw new OAuthException ( msg , "OAuthException" , code , null , null , null ) ; default : throw new ErrorFacebookException ( msg + " (code " + code + ")" , null , code , null , null , null ) ; } }
Throw the appropriate exception for the given legacy code and message . Always throws never returns .
87
17
138,240
protected ListSetItem < T > newItem ( IModel < T > itemModel ) { ListSetItem < T > item = new ListSetItem < T > ( Integer . toString ( counter ++ ) , itemModel ) ; populateItem ( item ) ; return item ; }
Create a new ListSetItem for list item .
58
10
138,241
public DateTextField getDateTextField ( ) { DateTextField component = visitChildren ( DateTextField . class , new IVisitor < DateTextField , DateTextField > ( ) { @ Override public void component ( DateTextField arg0 , IVisit < DateTextField > arg1 ) { arg1 . stop ( arg0 ) ; } } ) ; if ( component == null ) throw new WicketRuntimeException ( "BootstrapDatepicker didn't have any DateTextField child!" ) ; return component ; }
Gets the DateTextField inside this datepicker wrapper .
113
13
138,242
private boolean typesAreCompatible ( Class < ? > [ ] paramTypes , Class < ? > [ ] constructorParamTypes ) { boolean matches = true ; for ( int i = 0 ; i < paramTypes . length ; i ++ ) { Class < ? > paramType = paramTypes [ i ] ; if ( paramType != null ) { Class < ? > inputParamType = translateFromPrimitive ( paramType ) ; Class < ? > constructorParamType = translateFromPrimitive ( constructorParamTypes [ i ] ) ; if ( inputParamType . isArray ( ) && Collection . class . isAssignableFrom ( constructorParamType ) ) { continue ; } if ( ! constructorParamType . isAssignableFrom ( inputParamType ) ) { matches = false ; break ; } } } return matches ; }
Checks if a set of types are compatible with the given set of constructor parameter types . If an input type is null then it is considered as a wildcard for matching purposes and always matches .
171
39
138,243
public V action ( Callable < V > callable ) throws Exception { Exception re ; RetryState retryState = retryStrategy . getRetryState ( ) ; do { try { return callable . call ( ) ; } catch ( Exception e ) { re = e ; if ( Thread . interrupted ( ) || isInterruptTransitively ( e ) ) { re = new InterruptedException ( e . getMessage ( ) ) ; break ; } if ( ! transientExceptionDetector . isTransient ( e ) ) { break ; } } enqueueRetryEvent ( new RetryEvent ( this , retryState , re ) ) ; retryState . delayRetry ( ) ; } while ( retryState . hasRetries ( ) ) ; throw re ; }
Perform the specified action under the defined retry semantics .
166
12
138,244
private boolean isInterruptTransitively ( Throwable e ) { do { if ( e instanceof InterruptedException ) { return true ; } e = e . getCause ( ) ; } while ( e != null ) ; return false ; }
Special case during shutdown .
51
5
138,245
public Object getSet ( String key , Object value , Integer expiration ) throws Exception { Jedis jedis = null ; try { jedis = this . jedisPool . getResource ( ) ; long begin = System . currentTimeMillis ( ) ; // 操作expire成功返回1,失败返回0,仅当均返回1时,实际操作成功 byte [ ] val = jedis . getSet ( SafeEncoder . encode ( key ) , serialize ( value ) ) ; Object result = deserialize ( val ) ; boolean success = true ; if ( expiration > 0 ) { Long res = jedis . expire ( key , expiration ) ; if ( res == 0L ) { success = false ; } } long end = System . currentTimeMillis ( ) ; if ( success ) { logger . info ( "getset key:" + key + ", spends: " + ( end - begin ) + "ms" ) ; } else { logger . info ( "getset key: " + key + " failed, key has already exists! " ) ; } return result ; } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; this . jedisPool . returnBrokenResource ( jedis ) ; throw e ; } finally { if ( jedis != null ) { this . jedisPool . returnResource ( jedis ) ; } } }
get old value and set new value
342
7
138,246
public boolean add ( String key , Object value , Integer expiration ) throws Exception { Jedis jedis = null ; try { jedis = this . jedisPool . getResource ( ) ; long begin = System . currentTimeMillis ( ) ; // 操作setnx与expire成功返回1,失败返回0,仅当均返回1时,实际操作成功 Long result = jedis . setnx ( SafeEncoder . encode ( key ) , serialize ( value ) ) ; if ( expiration > 0 ) { result = result & jedis . expire ( key , expiration ) ; } long end = System . currentTimeMillis ( ) ; if ( result == 1L ) { logger . info ( "add key:" + key + ", spends: " + ( end - begin ) + "ms" ) ; } else { logger . info ( "add key: " + key + " failed, key has already exists! " ) ; } return result == 1L ; } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; this . jedisPool . returnBrokenResource ( jedis ) ; throw e ; } finally { if ( jedis != null ) { this . jedisPool . returnResource ( jedis ) ; } } }
add if not exists
322
4
138,247
public boolean exists ( String key ) throws Exception { boolean isExist = false ; Jedis jedis = null ; try { jedis = this . jedisPool . getResource ( ) ; isExist = jedis . exists ( SafeEncoder . encode ( key ) ) ; } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; this . jedisPool . returnBrokenResource ( jedis ) ; throw e ; } finally { if ( jedis != null ) { this . jedisPool . returnResource ( jedis ) ; } } return isExist ; }
Test if the specified key exists .
139
7
138,248
public boolean delete ( String key ) { Jedis jedis = null ; try { jedis = this . jedisPool . getResource ( ) ; jedis . del ( SafeEncoder . encode ( key ) ) ; logger . info ( "delete key:" + key ) ; return true ; } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; this . jedisPool . returnBrokenResource ( jedis ) ; } finally { if ( jedis != null ) { this . jedisPool . returnResource ( jedis ) ; } } return false ; }
Remove the specified keys .
136
5
138,249
public boolean flushall ( ) { String result = "" ; Jedis jedis = null ; try { jedis = this . jedisPool . getResource ( ) ; result = jedis . flushAll ( ) ; logger . info ( "redis client name: " + this . getCacheName ( ) + " flushall." ) ; } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; this . jedisPool . returnBrokenResource ( jedis ) ; } finally { if ( jedis != null ) { this . jedisPool . returnResource ( jedis ) ; } } return "OK" . equalsIgnoreCase ( result ) ; }
Delete all the keys of all the existing databases not just the currently selected one .
156
16
138,250
public Object get ( Object obj ) throws ReflectionException { try { if ( isPublic ( readMethod ) ) { return readMethod . invoke ( obj ) ; } else { throw new ReflectionException ( "Cannot get the value of " + this + ", as it is write-only." ) ; } } catch ( Exception e ) { throw new ReflectionException ( "Cannot get the value of " + this + " in object " + obj , e ) ; } }
Returns the value of the representation of this property from the specified object .
100
14
138,251
public void set ( Object obj , Object value ) throws ReflectionException { try { if ( isPublic ( writeMethod ) ) { writeMethod . invoke ( obj , value ) ; } else { throw new ReflectionException ( "Cannot set the value of " + this + ", as it is read-only." ) ; } } catch ( Exception e ) { throw new ReflectionException ( "Cannot set the value of " + this + " to object " + obj , e ) ; } }
Sets a new value to the representation of this property on the specified object .
104
16
138,252
@ SuppressWarnings ( "unchecked" ) @ Override public < C > IConverter < C > getConverter ( final Class < C > type ) { if ( Temporal . class . isAssignableFrom ( type ) ) { return ( IConverter < C > ) converter ; } else { return super . getConverter ( type ) ; } }
Returns the default converter if created without pattern ; otherwise it returns a pattern - specific converter .
84
18
138,253
public static boolean isSqlStateDuplicateValueInUniqueIndex ( SQLException se ) { String sqlState = se . getSQLState ( ) ; return sqlState != null && ( sqlState . equals ( "23505" ) || se . getMessage ( ) . contains ( "duplicate value in unique index" ) ) ; }
Determines if the SQL exception a duplicate value in unique index .
74
14
138,254
public static boolean isSqlStateConnectionException ( SQLException se ) { String sqlState = se . getSQLState ( ) ; return sqlState != null && sqlState . startsWith ( "08" ) ; }
Determines if the SQL exception is a connection exception
47
11
138,255
public static boolean isSqlStateRollbackException ( SQLException se ) { String sqlState = se . getSQLState ( ) ; return sqlState != null && sqlState . startsWith ( "40" ) ; }
Determines if the SQL exception is a rollback exception
48
12
138,256
public static Date getPreviousDay ( Date dt ) { if ( dt == null ) { return dt ; } Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( dt ) ; cal . add ( Calendar . DAY_OF_YEAR , - 1 ) ; return cal . getTime ( ) ; }
added by zhuqian 2009 - 03 - 25
70
11
138,257
public static synchronized void cancel ( TimerTask task ) { if ( task == null ) { return ; } task . cancel ( ) ; usageCount . decrementAndGet ( ) ; if ( usageCount . get ( ) == 0 ) { timer . cancel ( ) ; timer = null ; } }
Remove the specified eviction task from the timer .
62
9
138,258
public void push ( AbstractDrawer drawer , AjaxRequestTarget target , String cssClass ) { ListItem item = new ListItem ( "next" , drawer , this , cssClass ) ; drawers . push ( item ) ; if ( first == null ) { first = item ; addOrReplace ( first ) ; } else { ListItem iter = first ; while ( iter . next != null ) { iter = iter . next ; } iter . add ( item ) ; } if ( target != null ) { target . add ( item ) ; target . appendJavaScript ( "$('#" + item . item . getMarkupId ( ) + "').modaldrawer('show');" ) ; if ( item . previous != null ) { target . appendJavaScript ( "$('#" + item . previous . item . getMarkupId ( ) + "').removeClass('shown-modal');" ) ; target . appendJavaScript ( "$('#" + item . previous . item . getMarkupId ( ) + "').addClass('hidden-modal');" ) ; } } drawer . setManager ( this ) ; }
Push and display a drawer on the page during an AJAX request and inject an optional CSS class onto the drawer s immediate container .
243
26
138,259
public void replaceLast ( AbstractDrawer newDrawer , AjaxRequestTarget target ) { if ( ! drawers . isEmpty ( ) ) { ListItem last = drawers . getFirst ( ) ; last . drawer . replaceWith ( newDrawer ) ; last . drawer = newDrawer ; newDrawer . setManager ( this ) ; target . add ( newDrawer ) ; } }
Replaces the topmost open drawer with a new one . If there is no open drawer this method does nothing . This method requires an AJAX request . DrawerManager does not support swapping drawers during page construction .
83
44
138,260
@ Override public void renderHead ( IHeaderResponse response ) { super . renderHead ( response ) ; response . render ( JavaScriptHeaderItem . forReference ( DRAWER_JAVASCRIPT ) ) ; response . render ( JavaScriptHeaderItem . forReference ( MANAGER_JAVASCRIPT ) ) ; response . render ( CssHeaderItem . forReference ( DRAWER_CSS ) ) ; Iterator < ListItem > iter = drawers . descendingIterator ( ) ; WebMarkupContainer drawer ; while ( iter . hasNext ( ) ) { drawer = iter . next ( ) . item ; response . render ( OnDomReadyHeaderItem . forScript ( "$('#" + drawer . getMarkupId ( ) + "').modaldrawer('show');" ) ) ; if ( drawers . getFirst ( ) . item . equals ( drawer ) ) { response . render ( OnDomReadyHeaderItem . forScript ( "$('#" + drawer . getMarkupId ( ) + "').addClass('shown-modal');" ) ) ; response . render ( OnDomReadyHeaderItem . forScript ( "$('#" + drawer . getMarkupId ( ) + "').removeClass('hidden-modal');" ) ) ; } else { response . render ( OnDomReadyHeaderItem . forScript ( "$('#" + drawer . getMarkupId ( ) + "').removeClass('shown-modal');" ) ) ; response . render ( OnDomReadyHeaderItem . forScript ( "$('#" + drawer . getMarkupId ( ) + "').addClass('hidden-modal');" ) ) ; } } }
pressing the Back button and landing on a page with open drawers .
358
15
138,261
public void setWrappedObject ( Object obj ) { if ( obj == null ) { throw new IllegalArgumentException ( "Cannot warp a 'null' object." ) ; } this . object = obj ; this . bean = Bean . forClass ( obj . getClass ( ) ) ; }
Changes at any time the wrapped object with a new object .
62
12
138,262
public Object getIndexedValue ( String propertyName , int index ) { return getIndexedValue ( object , getPropertyOrThrow ( bean , propertyName ) , index , this ) ; }
Returns the value of the specified indexed property from the wrapped object .
40
13
138,263
public void setSimpleValue ( String propertyName , Object value ) { setSimpleValue ( object , getPropertyOrThrow ( bean , propertyName ) , value ) ; }
Sets the value of the specified property in the wrapped object .
35
13
138,264
public static Class < ? > translateFromPrimitive ( Class < ? > paramType ) { if ( paramType == int . class ) { return Integer . class ; } else if ( paramType == char . class ) { return Character . class ; } else if ( paramType == byte . class ) { return Byte . class ; } else if ( paramType == long . class ) { return Long . class ; } else if ( paramType == short . class ) { return Short . class ; } else if ( paramType == boolean . class ) { return Boolean . class ; } else if ( paramType == double . class ) { return Double . class ; } else if ( paramType == float . class ) { return Float . class ; } else { return paramType ; } }
From a primitive type class tries to return the corresponding wrapper class .
162
13
138,265
@ Override protected final void onRender ( ) { Iterator < ? extends Component > it = renderIterator ( ) ; while ( it . hasNext ( ) ) { Component child = it . next ( ) ; if ( child == null ) { throw new IllegalStateException ( "The render iterator returned null for a child. Container: " + this . toString ( ) + "; Iterator=" + it . toString ( ) ) ; } renderChild ( child ) ; } }
Renders all child items in no specified order
101
9
138,266
private static int metadata_end_cmp_ ( MetaData x , MetaData y ) { return x . getEnd ( ) . compareTo ( y . getEnd ( ) ) ; }
Comparator in order to sort MetaData based on the end timestamp .
39
14
138,267
private static List < Path > file_listing_ ( Path dir ) throws IOException { try ( Stream < Path > files = Files . list ( dir ) ) { return files . collect ( Collectors . toList ( ) ) ; } }
Scan a directory for files . This method reads the entire stream and closes it immediately .
51
17
138,268
public TSDataScanDir filterUpgradable ( ) { return new TSDataScanDir ( getDir ( ) , getFiles ( ) . stream ( ) . filter ( MetaData :: isUpgradable ) . collect ( Collectors . toList ( ) ) ) ; }
Filter the list of files to contain only upgradable files .
57
13
138,269
protected void init ( ExplodeInfo info , int x , int y , int width , int height ) { _info = info ; _ox = x ; _oy = y ; _owid = width ; _ohei = height ; _info . rvel = ( float ) ( ( 2.0f * Math . PI ) * _info . rvel ) ; _chunkcount = ( _info . xchunk * _info . ychunk ) ; _cxpos = new int [ _chunkcount ] ; _cypos = new int [ _chunkcount ] ; _sxvel = new float [ _chunkcount ] ; _syvel = new float [ _chunkcount ] ; // determine chunk dimensions _cwid = _owid / _info . xchunk ; _chei = _ohei / _info . ychunk ; _hcwid = _cwid / 2 ; _hchei = _chei / 2 ; // initialize all chunks for ( int ii = 0 ; ii < _chunkcount ; ii ++ ) { // initialize chunk position int xpos = ii % _info . xchunk ; int ypos = ii / _info . xchunk ; _cxpos [ ii ] = _ox + ( xpos * _cwid ) ; _cypos [ ii ] = _oy + ( ypos * _chei ) ; // initialize chunk velocity _sxvel [ ii ] = RandomUtil . getFloat ( _info . xvel ) * ( ( xpos < ( _info . xchunk / 2 ) ) ? - 1.0f : 1.0f ) ; _syvel [ ii ] = - ( RandomUtil . getFloat ( _info . yvel ) ) ; } // initialize the chunk rotation angle _angle = 0.0f ; }
Initializes the animation with the attributes of the given explode info object .
394
14
138,270
public static MetricValue fromNumberValue ( Number number ) { if ( number == null ) { return EMPTY ; } else if ( number instanceof Float || number instanceof Double ) { return fromDblValue ( number . doubleValue ( ) ) ; } else if ( number instanceof Byte || number instanceof Short || number instanceof Integer || number instanceof Long ) { return fromIntValue ( number . longValue ( ) ) ; } else { throw new IllegalArgumentException ( "Unrecognized number type: " + number . getClass ( ) ) ; } }
Construct a metric value from a Number implementation .
120
9
138,271
public void positionAvoidAnimation ( Animation anim , Rectangle viewBounds ) { Rectangle abounds = new Rectangle ( anim . getBounds ( ) ) ; @ SuppressWarnings ( "unchecked" ) ArrayList < Animation > avoidables = ( ArrayList < Animation > ) _avoidAnims . clone ( ) ; // if we are able to place it somewhere, do so if ( SwingUtil . positionRect ( abounds , viewBounds , avoidables ) ) { anim . setLocation ( abounds . x , abounds . y ) ; } // add the animation to the list of avoidables _avoidAnims . add ( anim ) ; // keep an eye on it so that we can remove it when it's finished anim . addAnimationObserver ( _avoidAnimObs ) ; }
Position the specified animation so that it is not overlapping any still - running animations previously passed to this method .
170
21
138,272
public void invalidateRegion ( int x , int y , int width , int height ) { if ( isValidSize ( width , height ) ) { addDirtyRegion ( new Rectangle ( x , y , width , height ) ) ; } }
Invalidates the specified region .
52
6
138,273
protected final boolean isValidSize ( int width , int height ) { if ( width < 0 || height < 0 ) { log . warning ( "Attempt to add invalid dirty region?!" , "size" , ( width + "x" + height ) , new Exception ( ) ) ; return false ; } else if ( width == 0 || height == 0 ) { // no need to complain about zero sized rectangles, just ignore them return false ; } else { return true ; } }
Used to ensure our dirty regions are not invalid .
99
10
138,274
public Rectangle [ ] getDirtyRegions ( ) { List < Rectangle > merged = Lists . newArrayList ( ) ; for ( int ii = _dirty . size ( ) - 1 ; ii >= 0 ; ii -- ) { // pop the next rectangle from the dirty list Rectangle mr = _dirty . remove ( ii ) ; // merge in any overlapping rectangles for ( int jj = ii - 1 ; jj >= 0 ; jj -- ) { Rectangle r = _dirty . get ( jj ) ; if ( mr . intersects ( r ) ) { // remove the overlapping rectangle from the list _dirty . remove ( jj ) ; ii -- ; // grow the merged dirty rectangle mr . add ( r ) ; } } // add the merged rectangle to the list merged . add ( mr ) ; } return merged . toArray ( new Rectangle [ merged . size ( ) ] ) ; }
Merges all outstanding dirty regions into a single list of rectangles and returns that to the caller . Internally the list of accumulated dirty regions is cleared out and prepared for the next frame .
196
38
138,275
public List < Any2 < Integer , String > > getArguments ( ) { final List < Any2 < Integer , String > > result = new ArrayList <> ( ) ; elements_ . forEach ( elem -> elem . keys ( result :: add ) ) ; return result ; }
Retrieve the variables used to render this string .
62
10
138,276
public boolean hasConstraint ( int tileIdx , String constraint ) { return ( _bits == null || _bits [ tileIdx ] . constraints == null ) ? false : ListUtil . contains ( _bits [ tileIdx ] . constraints , constraint ) ; }
Checks whether the tile at the specified index has the given constraint .
58
14
138,277
public static TrimmedObjectTileSet trimObjectTileSet ( ObjectTileSet source , OutputStream destImage ) throws IOException { return trimObjectTileSet ( source , destImage , FastImageIO . FILE_SUFFIX ) ; }
Convenience function to trim the tile set to a file using FastImageIO .
50
17
138,278
public int renderCompareTo ( AbstractMedia other ) { int result = Ints . compare ( _renderOrder , other . _renderOrder ) ; return ( result != 0 ) ? result : naturalCompareTo ( other ) ; }
Compares this media to the specified media by render order .
47
12
138,279
public void queueNotification ( ObserverList . ObserverOp < Object > amop ) { if ( _observers != null ) { if ( _mgr != null ) { _mgr . queueNotification ( _observers , amop ) ; } else { log . warning ( "Have no manager, dropping notification" , "media" , this , "op" , amop ) ; } } }
Queues the supplied notification up to be dispatched to this abstract media s observers .
87
16
138,280
protected void addObserver ( Object obs ) { if ( _observers == null ) { _observers = ObserverList . newFastUnsafe ( ) ; } _observers . add ( obs ) ; }
Add the specified observer to this media element .
47
9
138,281
private void dispatchEvent ( XoaEvent event ) { LOG . entering ( CLASS_NAME , "dispatchEvent" , event ) ; try { Integer handlerId = event . getHandlerId ( ) ; XoaEventKind eventKind = event . getEvent ( ) ; if ( LOG . isLoggable ( Level . FINEST ) ) { LOG . finest ( "XOA --> SOA: " + handlerId + " event: " + eventKind . name ( ) ) ; } BridgeDelegate handler = xoaObjectMap . get ( handlerId ) ; if ( handler == null ) { if ( LOG . isLoggable ( Level . FINEST ) ) { LOG . finest ( "No handler for handler id: " + handlerId ) ; } return ; } /* Allow only one bridge crossing per handler at a time */ synchronized ( handler ) { // dispatch to SOA Object [ ] args = { handlerId , eventKind . toString ( ) , event . getParams ( ) } ; firePropertyChange ( XOP_MESSAGE , null , args ) ; } } catch ( Exception e ) { LOG . log ( Level . FINE , "While dispatching event: " + e . getMessage ( ) , e ) ; throw new IllegalStateException ( "Unable to dispatch an event from the cross origin proxy" , e ) ; } }
Dispatch an event to Source Origin
287
6
138,282
public void setVariance ( int dx , int dy ) { if ( ( dx < 0 ) || ( dy < 0 ) || ( ( dx == 0 ) && ( dy == 0 ) ) ) { throw new IllegalArgumentException ( "Variance values must be positive, and at least one must be non-zero." ) ; } else { _dx = dx ; _dy = dy ; } }
Set the variance of bobblin in each direction .
84
11
138,283
protected boolean updatePositionTo ( Pathable pable , int x , int y ) { if ( ( pable . getX ( ) == x ) && ( pable . getY ( ) == y ) ) { return false ; } else { pable . setLocation ( x , y ) ; return true ; } }
Update the position of the pathable or return false if it s already there .
67
16
138,284
public static DisplayMode getDisplayMode ( GraphicsDevice gd , int width , int height , int desiredDepth , int minimumDepth ) { DisplayMode [ ] modes = gd . getDisplayModes ( ) ; final int ddepth = desiredDepth ; // we sort modes in order of desirability Comparator < DisplayMode > mcomp = new Comparator < DisplayMode > ( ) { public int compare ( DisplayMode m1 , DisplayMode m2 ) { int bd1 = m1 . getBitDepth ( ) , bd2 = m2 . getBitDepth ( ) ; int rr1 = m1 . getRefreshRate ( ) , rr2 = m2 . getRefreshRate ( ) ; // prefer the desired depth if ( bd1 == ddepth && bd2 != ddepth ) { return - 1 ; } else if ( bd2 == ddepth && bd1 != ddepth ) { return 1 ; } // otherwise prefer higher depths if ( bd1 != bd2 ) { return bd2 - bd1 ; } // for same bitrates, prefer higher refresh rates return rr2 - rr1 ; } } ; // but we only add modes that meet our minimum requirements TreeSet < DisplayMode > mset = new TreeSet < DisplayMode > ( mcomp ) ; for ( DisplayMode mode : modes ) { if ( mode . getWidth ( ) == width && mode . getHeight ( ) == height && mode . getBitDepth ( ) >= minimumDepth && mode . getRefreshRate ( ) <= 75 ) { mset . add ( mode ) ; } } return ( mset . size ( ) > 0 ) ? mset . first ( ) : null ; }
Gets a display mode that matches the specified parameters . The screen resolution must match the specified resolution exactly the specified desired depth will be used if it is available and if not the highest depth greater than or equal to the specified minimum depth is used . The highest refresh rate available for the desired mode is also used .
365
62
138,285
public static CharacterDescriptor getRandomDescriptor ( ComponentRepository crepo , String gender , String [ ] COMP_CLASSES , ColorPository cpos , String [ ] COLOR_CLASSES ) { // get all available classes ArrayList < ComponentClass > classes = Lists . newArrayList ( ) ; for ( String element : COMP_CLASSES ) { String cname = gender + "/" + element ; ComponentClass cclass = crepo . getComponentClass ( cname ) ; // make sure the component class exists if ( cclass == null ) { log . warning ( "Missing definition for component class" , "class" , cname ) ; continue ; } // make sure there are some components in this class Iterator < Integer > iter = crepo . enumerateComponentIds ( cclass ) ; if ( ! iter . hasNext ( ) ) { log . info ( "Skipping class for which we have no components" , "class" , cclass ) ; continue ; } classes . add ( cclass ) ; } // select the components int [ ] components = new int [ classes . size ( ) ] ; Colorization [ ] [ ] zations = new Colorization [ components . length ] [ ] ; for ( int ii = 0 ; ii < components . length ; ii ++ ) { ComponentClass cclass = classes . get ( ii ) ; // get the components available for this class ArrayList < Integer > choices = Lists . newArrayList ( ) ; Iterators . addAll ( choices , crepo . enumerateComponentIds ( cclass ) ) ; // each of our components has up to four colorizations: two "global" skin colorizations // and potentially a primary and secondary clothing colorization; in a real system one // would probably keep a separate database of which character component required which // colorizations, but here we just assume everything could have any of the four // colorizations; it *usually* doesn't hose an image if you apply a recoloring that it // does not support, but it can match stray colors unnecessarily zations [ ii ] = new Colorization [ COLOR_CLASSES . length ] ; for ( int zz = 0 ; zz < COLOR_CLASSES . length ; zz ++ ) { zations [ ii ] [ zz ] = cpos . getRandomStartingColor ( COLOR_CLASSES [ zz ] ) . getColorization ( ) ; } // choose a random component if ( choices . size ( ) > 0 ) { int idx = RandomUtil . getInt ( choices . size ( ) ) ; components [ ii ] = choices . get ( idx ) . intValue ( ) ; } else { log . info ( "Have no components in class" , "class" , cclass ) ; } } return new CharacterDescriptor ( components , zations ) ; }
Returns a new character descriptor populated with a random set of components .
600
13
138,286
public CompletableFuture < NewFile > run ( ) { LOG . log ( Level . FINE , "starting optimized file creation for {0} files" , files . size ( ) ) ; CompletableFuture < NewFile > fileCreation = new CompletableFuture <> ( ) ; final List < TSData > fjpFiles = this . files ; // We clear out files below, which makes createTmpFile see an empty map if we don't use a separate variable. TASK_POOL . execute ( ( ) -> createTmpFile ( fileCreation , destDir , fjpFiles , getCompression ( ) ) ) ; synchronized ( OUTSTANDING ) { OUTSTANDING . add ( fileCreation ) ; } this . files = new LinkedList <> ( ) ; // Do not use clear! This instance is now shared with the createTmpFile task. return fileCreation ; }
Start creating the optimized file . This operation resets the state of the optimizer task so it can be re - used for subsequent invocations .
198
29
138,287
private static void createTmpFile ( CompletableFuture < NewFile > fileCreation , Path destDir , List < TSData > files , Compression compression ) { LOG . log ( Level . FINE , "starting temporary file creation..." ) ; try { Collections . sort ( files , Comparator . comparing ( TSData :: getBegin ) ) ; final FileChannel fd = FileUtil . createTempFile ( destDir , "monsoon-" , ".optimize-tmp" ) ; try { final DateTime begin ; try ( ToXdrTables output = new ToXdrTables ( ) ) { while ( ! files . isEmpty ( ) ) { TSData tsdata = files . remove ( 0 ) ; if ( fileCreation . isCancelled ( ) ) throw new IOException ( "aborted due to canceled execution" ) ; output . addAll ( tsdata ) ; // Takes a long time. } if ( fileCreation . isCancelled ( ) ) throw new IOException ( "aborted due to canceled execution" ) ; begin = output . build ( fd , compression ) ; // Writing output takes a lot of time. } if ( fileCreation . isCancelled ( ) ) // Recheck after closing output. throw new IOException ( "aborted due to canceled execution" ) ; // Forward the temporary file to the installation, which will complete the operation. INSTALL_POOL . execute ( ( ) -> install ( fileCreation , destDir , fd , begin ) ) ; } catch ( Error | RuntimeException | IOException ex ) { try { fd . close ( ) ; } catch ( Error | RuntimeException | IOException ex1 ) { ex . addSuppressed ( ex1 ) ; } throw ex ; } } catch ( Error | RuntimeException | IOException ex ) { LOG . log ( Level . WARNING , "temporary file for optimization failure" , ex ) ; synchronized ( OUTSTANDING ) { OUTSTANDING . remove ( fileCreation ) ; } fileCreation . completeExceptionally ( ex ) ; // Propagate exceptions. } }
The fork - join task that creates a new file . This function creates a temporary file with the result contents then passes it on to the install thread which will put the final file in place .
448
38
138,288
private static void install ( CompletableFuture < NewFile > fileCreation , Path destDir , FileChannel tmpFile , DateTime begin ) { try { try { synchronized ( OUTSTANDING ) { OUTSTANDING . remove ( fileCreation ) ; } if ( fileCreation . isCancelled ( ) ) throw new IOException ( "Installation aborted, due to cancellation." ) ; final FileUtil . NamedFileChannel newFile = FileUtil . createNewFile ( destDir , prefixForTimestamp ( begin ) , ".optimized" ) ; try ( Releaseable < FileChannel > out = new Releaseable <> ( newFile . getFileChannel ( ) ) ) { final long fileSize = tmpFile . size ( ) ; LOG . log ( Level . INFO , "installing {0} ({1} MB)" , new Object [ ] { newFile . getFileName ( ) , fileSize / 1024.0 / 1024.0 } ) ; // Copy tmpFile to out. long offset = 0 ; while ( offset < fileSize ) offset += tmpFile . transferTo ( offset , fileSize - offset , out . get ( ) ) ; out . get ( ) . force ( true ) ; // Ensure new file is safely written to permanent storage. // Complete future with newly created file. fileCreation . complete ( new NewFile ( newFile . getFileName ( ) , new ReadonlyTableFile ( new GCCloseable <> ( out . release ( ) ) ) ) ) ; } catch ( Error | RuntimeException | IOException | OncRpcException ex ) { // Ensure new file gets destroyed if an error occurs during copying. try { Files . delete ( newFile . getFileName ( ) ) ; } catch ( Error | RuntimeException | IOException ex1 ) { ex . addSuppressed ( ex1 ) ; } throw ex ; } } finally { // Close tmp file that we got from fjpCreateTmpFile. tmpFile . close ( ) ; } } catch ( Error | RuntimeException | IOException | OncRpcException ex ) { LOG . log ( Level . WARNING , "unable to install new file" , ex ) ; fileCreation . completeExceptionally ( ex ) ; // Propagate error to future. } }
Installs the newly created file . This function runs on the install thread and essentially performs a copy - operation from the temporary file to the final file .
481
30
138,289
private static String prefixForTimestamp ( DateTime timestamp ) { return String . format ( "monsoon-%04d%02d%02d-%02d%02d" , timestamp . getYear ( ) , timestamp . getMonthOfYear ( ) , timestamp . getDayOfMonth ( ) , timestamp . getHourOfDay ( ) , timestamp . getMinuteOfHour ( ) ) ; }
Compute a prefix for a to - be - installed file .
86
13
138,290
public ErrorData getErrorData ( ) { return new ErrorData ( ( Throwable ) getRequest ( ) . getAttribute ( "javax.servlet.error.exception" ) , ( ( Integer ) getRequest ( ) . getAttribute ( "javax.servlet.error.status_code" ) ) . intValue ( ) , ( String ) getRequest ( ) . getAttribute ( "javax.servlet.error.request_uri" ) , ( String ) getRequest ( ) . getAttribute ( "javax.servlet.error.servlet_name" ) ) ; }
Provides convenient access to error information .
132
8
138,291
public static void storeLogs ( String sourceLogFileName , String destLogFileName ) throws Exception { // assumes eventmanager is running // store logs String tmpdir = System . getProperty ( "java.io.tmpdir" ) ; if ( tmpdir == null || tmpdir == "null" ) { tmpdir = "/tmp" ; } File tmpLogFile = new File ( tmpdir + File . separator + sourceLogFileName ) ; File destFile = new File ( current_log_dir + File . separator + destLogFileName ) ; Files . copy ( tmpLogFile , destFile ) ; }
Stores the specified log for this test
132
8
138,292
protected void setSelectedComponent ( int idx ) { int cid = _components . get ( idx ) . intValue ( ) ; _model . setSelectedComponent ( _cclass , cid ) ; }
Sets the selected component in the builder model for the component class associated with this editor to the component at the given index in this editor s list of available components .
48
33
138,293
public boolean isFlowActive ( ) { Object val = this . getArgument ( "active" ) ; if ( val instanceof Integer ) { return ( ( Integer ) val ) . intValue ( ) == 1 ; } else { throw new IllegalStateException ( "ChannelEvent does not contain the 'active' argument" ) ; } }
Returns For flow events returns true if flow is active
70
10
138,294
static void writeTracker ( JSONWriter writer , Tracker tracker ) throws JSONException { writer . key ( "id" ) ; writer . value ( tracker . getId ( ) ) ; writer . key ( "name" ) ; writer . value ( tracker . getName ( ) ) ; }
Writes a tracker .
59
5
138,295
public static void addFull ( JSONWriter writer , String field , Date value ) throws JSONException { final SimpleDateFormat format = RedmineDateUtils . FULL_DATE_FORMAT . get ( ) ; JsonOutput . add ( writer , field , value , format ) ; }
Adds a value to a writer .
60
7
138,296
private Optional < Data < Input , Output > > match_ ( Input input ) { return Optional . ofNullable ( recent_ . get ( ) ) . filter ( ( Data < Input , Output > data ) -> equality_ . test ( data . getInput ( ) , input ) ) ; }
Try to match an input against the most recent calculation .
61
11
138,297
private Data < Input , Output > derive_ ( Input input ) { Data < Input , Output > result = new Data <> ( input , fn_ . apply ( input ) ) ; recent_ . set ( result ) ; return result ; }
Derive and remember a calculation .
50
7
138,298
@ Override public Output apply ( Input input ) { if ( input == null ) return fn_ . apply ( input ) ; return match_ ( input ) . orElseGet ( ( ) -> derive_ ( input ) ) . getOutput ( ) ; }
Functional implementation .
53
4
138,299
public void setWarning ( float warnPercent , ResultListener < TimerView > warner ) { // This warning hasn't triggered yet _warned = false ; // Here are the details _warnPercent = warnPercent ; _warner = warner ; }
Setup a warning to trigger after the timer is warnPercent or more completed . If warner is non - null it will be called at that time .
53
30