idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
20,300
public static byte [ ] fromHexByteArray ( final byte [ ] buffer ) { final byte [ ] outputBuffer = new byte [ buffer . length >> 1 ] ; for ( int i = 0 ; i < buffer . length ; i += 2 ) { final int hi = FROM_HEX_DIGIT_TABLE [ buffer [ i ] ] << 4 ; final int lo = FROM_HEX_DIGIT_TABLE [ buffer [ i + 1 ] ] ; outputBuffer [ i >> 1 ] = ( byte ) ( hi | lo ) ; } return outputBuffer ; }
Generate a byte array from the hex representation of the given byte array .
20,301
public static byte [ ] toHexByteArray ( final byte [ ] buffer , final int offset , final int length ) { final byte [ ] outputBuffer = new byte [ length << 1 ] ; for ( int i = 0 ; i < ( length << 1 ) ; i += 2 ) { final byte b = buffer [ offset + ( i >> 1 ) ] ; outputBuffer [ i ] = HEX_DIGIT_TABLE [ ( b >> 4 ) & 0x0F ] ; outputBuffer [ i + 1 ] = HEX_DIGIT_TABLE [ b & 0x0F ] ; } return outputBuffer ; }
Generate a byte array that is a hex representation of a given byte array .
20,302
public static String toHex ( final byte [ ] buffer , final int offset , final int length ) { return new String ( toHexByteArray ( buffer , offset , length ) , UTF_8 ) ; }
Generate a string that is the hex representation of a given byte array .
20,303
public static boolean isAligned ( final long address , final int alignment ) { if ( ! BitUtil . isPowerOfTwo ( alignment ) ) { throw new IllegalArgumentException ( "alignment must be a power of 2: alignment=" + alignment ) ; } return ( address & ( alignment - 1 ) ) == 0 ; }
Is an address aligned on a boundary .
20,304
public long incrementOrdered ( ) { final long currentValue = UnsafeAccess . UNSAFE . getLong ( byteArray , addressOffset ) ; UnsafeAccess . UNSAFE . putOrderedLong ( byteArray , addressOffset , currentValue + 1 ) ; return currentValue ; }
Perform an atomic increment that is not safe across threads .
20,305
public long getAndAddOrdered ( final long increment ) { final long currentValue = UnsafeAccess . UNSAFE . getLong ( byteArray , addressOffset ) ; UnsafeAccess . UNSAFE . putOrderedLong ( byteArray , addressOffset , currentValue + increment ) ; return currentValue ; }
Add an increment to the counter with ordered store semantics .
20,306
public boolean compareAndSet ( final long expectedValue , final long updateValue ) { return UnsafeAccess . UNSAFE . compareAndSwapLong ( byteArray , addressOffset , expectedValue , updateValue ) ; }
Compare the current value to expected and if true then set to the update value atomically .
20,307
public static < K , V > V getOrDefault ( final Map < K , V > map , final K key , final Function < K , V > supplier ) { V value = map . get ( key ) ; if ( value == null ) { value = supplier . apply ( key ) ; map . put ( key , value ) ; } return value ; }
A getOrDefault that doesn t create garbage if its suppler is non - capturing .
20,308
public void wrap ( final long offset , final long length ) { if ( offset == addressOffset && length == capacity ) { return ; } wrap ( fileChannel , offset , length ) ; }
Remap the buffer using the existing file based on a new offset and length
20,309
public void wrap ( final FileChannel fileChannel , final long offset , final long length ) { unmap ( ) ; this . fileChannel = fileChannel ; map ( offset , length ) ; }
Remap the buffer based on a new file offset and a length
20,310
public void wrap ( final FileChannel fileChannel , final FileChannel . MapMode mapMode , final long offset , final long length ) { unmap ( ) ; this . fileChannel = fileChannel ; this . mapMode = mapMode ; map ( offset , length ) ; }
Remap the buffer based on a new file mapping mode offset and a length
20,311
public boolean record ( final Throwable observation ) { final long timestamp = clock . time ( ) ; DistinctObservation distinctObservation ; synchronized ( this ) { distinctObservation = find ( distinctObservations , observation ) ; if ( null == distinctObservation ) { distinctObservation = newObservation ( timestamp , observation ) ; if ( INSUFFICIENT_SPACE == distinctObservation ) { return false ; } } } final int offset = distinctObservation . offset ; buffer . getAndAddInt ( offset + OBSERVATION_COUNT_OFFSET , 1 ) ; buffer . putLongOrdered ( offset + LAST_OBSERVATION_TIMESTAMP_OFFSET , timestamp ) ; return true ; }
Record an observation of an error . If it is the first observation of this error type for a stack trace then a new entry will be created . For subsequent observations of the same error type and stack trace a counter and time of last observation will be updated .
20,312
public void forEach ( final IntObjConsumer < String > consumer ) { int counterId = 0 ; final AtomicBuffer metaDataBuffer = this . metaDataBuffer ; for ( int i = 0 , capacity = metaDataBuffer . capacity ( ) ; i < capacity ; i += METADATA_LENGTH ) { final int recordStatus = metaDataBuffer . getIntVolatile ( i ) ; if ( RECORD_ALLOCATED == recordStatus ) { consumer . accept ( counterId , labelValue ( metaDataBuffer , i ) ) ; } else if ( RECORD_UNUSED == recordStatus ) { break ; } counterId ++ ; } }
Iterate over all labels in the label buffer .
20,313
public void forEach ( final CounterConsumer consumer ) { int counterId = 0 ; final AtomicBuffer metaDataBuffer = this . metaDataBuffer ; final AtomicBuffer valuesBuffer = this . valuesBuffer ; for ( int i = 0 , capacity = metaDataBuffer . capacity ( ) ; i < capacity ; i += METADATA_LENGTH ) { final int recordStatus = metaDataBuffer . getIntVolatile ( i ) ; if ( RECORD_ALLOCATED == recordStatus ) { consumer . accept ( valuesBuffer . getLongVolatile ( counterOffset ( counterId ) ) , counterId , labelValue ( metaDataBuffer , i ) ) ; } else if ( RECORD_UNUSED == recordStatus ) { break ; } counterId ++ ; } }
Iterate over the counters and provide the value and basic metadata .
20,314
public void forEach ( final MetaData metaData ) { int counterId = 0 ; final AtomicBuffer metaDataBuffer = this . metaDataBuffer ; for ( int i = 0 , capacity = metaDataBuffer . capacity ( ) ; i < capacity ; i += METADATA_LENGTH ) { final int recordStatus = metaDataBuffer . getIntVolatile ( i ) ; if ( RECORD_ALLOCATED == recordStatus ) { final int typeId = metaDataBuffer . getInt ( i + TYPE_ID_OFFSET ) ; final String label = labelValue ( metaDataBuffer , i ) ; final DirectBuffer keyBuffer = new UnsafeBuffer ( metaDataBuffer , i + KEY_OFFSET , MAX_KEY_LENGTH ) ; metaData . accept ( counterId , typeId , keyBuffer , label ) ; } else if ( RECORD_UNUSED == recordStatus ) { break ; } counterId ++ ; } }
Iterate over all the metadata in the buffer .
20,315
public void wrap ( final MutableDirectBuffer buffer , final int offset ) { Objects . requireNonNull ( buffer , "Buffer must not be null" ) ; if ( ! buffer . isExpandable ( ) ) { throw new IllegalStateException ( "buffer must be expandable." ) ; } this . buffer = buffer ; this . offset = offset ; this . position = 0 ; }
Wrap a given buffer beginning at an offset .
20,316
public static void present ( final Map < ? , ? > map , final Object key , final String name ) { if ( null == map . get ( key ) ) { throw new IllegalStateException ( name + " not found in map for key: " + key ) ; } }
Verify that a map contains an entry for a given key .
20,317
public static long address ( final ByteBuffer buffer ) { if ( ! buffer . isDirect ( ) ) { throw new IllegalArgumentException ( "buffer.isDirect() must be true" ) ; } return UNSAFE . getLong ( buffer , BYTE_BUFFER_ADDRESS_FIELD_OFFSET ) ; }
Get the address at which the underlying buffer storage begins .
20,318
public void close ( ) { selector . wakeup ( ) ; try { selector . close ( ) ; } catch ( final IOException ex ) { LangUtil . rethrowUnchecked ( ex ) ; } }
Close NioSelector down . Returns immediately .
20,319
public void selectNowWithoutProcessing ( ) { try { selector . selectNow ( ) ; selectedKeySet . reset ( ) ; } catch ( final IOException ex ) { LangUtil . rethrowUnchecked ( ex ) ; } }
Explicit call to selectNow but without processing of selected keys .
20,320
public static < T > T [ ] add ( final T [ ] oldElements , final T elementToAdd ) { final int length = oldElements . length ; final T [ ] newElements = Arrays . copyOf ( oldElements , length + 1 ) ; newElements [ length ] = elementToAdd ; return newElements ; }
Add an element to an array resulting in a new array .
20,321
@ SuppressWarnings ( "unchecked" ) public static < T > T [ ] newArray ( final T [ ] oldElements , final int length ) { return ( T [ ] ) Array . newInstance ( oldElements . getClass ( ) . getComponentType ( ) , length ) ; }
Allocate a new array of the same type as another array .
20,322
public static < T > T [ ] ensureCapacity ( final T [ ] oldElements , final int requiredLength ) { T [ ] result = oldElements ; if ( oldElements . length < requiredLength ) { result = Arrays . copyOf ( oldElements , requiredLength ) ; } return result ; }
Ensure an array has the required capacity . Resizing only if needed .
20,323
public V put ( final Object key , final Object value ) { final Object val = mapNullValue ( value ) ; requireNonNull ( val , "value cannot be null" ) ; final Object [ ] entries = this . entries ; final int mask = entries . length - 1 ; int index = Hashing . evenHash ( key . hashCode ( ) , mask ) ; Object oldValue = null ; while ( entries [ index + 1 ] != null ) { if ( entries [ index ] == key || entries [ index ] . equals ( key ) ) { oldValue = entries [ index + 1 ] ; break ; } index = next ( index , mask ) ; } if ( oldValue == null ) { ++ size ; entries [ index ] = key ; } entries [ index + 1 ] = val ; increaseCapacity ( ) ; return unmapNullValue ( oldValue ) ; }
Put a key value pair into the map .
20,324
public static Thread startOnThread ( final AgentRunner runner , final ThreadFactory threadFactory ) { final Thread thread = threadFactory . newThread ( runner ) ; thread . setName ( runner . agent ( ) . roleName ( ) ) ; thread . start ( ) ; return thread ; }
Start the given agent runner on a new thread .
20,325
public static void checkCapacity ( final int capacity ) { if ( ! BitUtil . isPowerOfTwo ( capacity ) ) { final String msg = "capacity must be a positive power of 2 + TRAILER_LENGTH: capacity=" + capacity ; throw new IllegalStateException ( msg ) ; } }
Check the the buffer capacity is the correct size .
20,326
public void write ( final int b ) { if ( position == length ) { throw new IllegalStateException ( "position has reached the end of underlying buffer" ) ; } buffer . putByte ( offset + position , ( byte ) b ) ; ++ position ; }
Write a byte to buffer .
20,327
public boolean cancelTimer ( final long timerId ) { final int wheelIndex = tickForTimerId ( timerId ) ; final int arrayIndex = indexInTickArray ( timerId ) ; if ( wheelIndex < wheel . length ) { final long [ ] array = wheel [ wheelIndex ] ; if ( arrayIndex < array . length && NULL_TIMER != array [ arrayIndex ] ) { array [ arrayIndex ] = NULL_TIMER ; timerCount -- ; return true ; } } return false ; }
Cancel a previously scheduled timer .
20,328
public int poll ( final long now , final TimerHandler handler , final int maxTimersToExpire ) { int timersExpired = 0 ; if ( timerCount > 0 ) { final long [ ] array = wheel [ currentTick & wheelMask ] ; for ( int i = 0 , length = array . length ; i < length && maxTimersToExpire > timersExpired ; i ++ ) { final long deadline = array [ pollIndex ] ; if ( deadline <= now ) { array [ pollIndex ] = NULL_TIMER ; timerCount -- ; timersExpired ++ ; if ( ! handler . onTimerExpiry ( timeUnit , now , timerIdForSlot ( currentTick & wheelMask , pollIndex ) ) ) { array [ pollIndex ] = deadline ; timerCount ++ ; return timersExpired ; } } pollIndex = ( pollIndex + 1 ) >= length ? 0 : ( pollIndex + 1 ) ; } if ( maxTimersToExpire > timersExpired && currentTickTime ( ) <= now ) { currentTick ++ ; pollIndex = 0 ; } else if ( pollIndex >= array . length ) { pollIndex = 0 ; } } else if ( currentTickTime ( ) <= now ) { currentTick ++ ; pollIndex = 0 ; } return timersExpired ; }
Poll for timers expired by the deadline passing .
20,329
public void forEach ( final TimerConsumer consumer ) { long numTimersLeft = timerCount ; for ( int j = currentTick , end = currentTick + wheel . length ; j <= end ; j ++ ) { final long [ ] array = wheel [ j & wheelMask ] ; for ( int i = 0 , length = array . length ; i < length ; i ++ ) { final long deadline = array [ i ] ; if ( deadline != NULL_TIMER ) { consumer . accept ( deadline , timerIdForSlot ( j & wheelMask , i ) ) ; if ( -- numTimersLeft == 0 ) { return ; } } } } }
Iterate over wheel so all active timers can be consumed without expiring them .
20,330
public long deadline ( final long timerId ) { final int wheelIndex = tickForTimerId ( timerId ) ; final int arrayIndex = indexInTickArray ( timerId ) ; if ( wheelIndex < wheel . length ) { final long [ ] array = wheel [ wheelIndex ] ; if ( arrayIndex < array . length ) { return array [ arrayIndex ] ; } } return NULL_TIMER ; }
Return the deadline for the given timerId .
20,331
public AsciiSequenceView wrap ( final DirectBuffer buffer , final int offset , final int length ) { this . buffer = buffer ; this . offset = offset ; this . length = length ; return this ; }
Wrap a range of an existing buffer containing an ASCII sequence .
20,332
public static < K > int hash ( final K value , final int mask ) { final int hash = value . hashCode ( ) ; return hash & mask ; }
Generate a hash for a K value .
20,333
public static int hash ( final long value , final int mask ) { long hash = value * 31 ; hash = ( int ) hash ^ ( int ) ( hash >>> 32 ) ; return ( int ) hash & mask ; }
Generate a hash for a long value .
20,334
public static int evenHash ( final long value , final int mask ) { int hash = ( int ) value ^ ( int ) ( value >>> 32 ) ; hash = ( hash << 1 ) - ( hash << 8 ) ; return hash & mask ; }
Generate an even hash for a long value .
20,335
public void forEach ( final RecordHandler handler ) { int offset = endOfPositionField ; final int position = position ( ) ; while ( offset < position ) { if ( statusVolatile ( offset ) == COMMITTED ) { final int key = key ( offset ) ; handler . onRecord ( key , offset + SIZE_OF_RECORD_FRAME ) ; } offset += slotSize ; } }
Read each record out of the buffer in turn .
20,336
public int get ( final int key ) { int offset = endOfPositionField ; final int position = position ( ) ; while ( offset < position ) { if ( statusVolatile ( offset ) == COMMITTED && key == key ( offset ) ) { return offset + SIZE_OF_RECORD_FRAME ; } offset += slotSize ; } return DID_NOT_CLAIM_RECORD ; }
Search for the first record with the specified key .
20,337
public boolean withRecord ( final int key , final RecordWriter writer ) { final int claimedOffset = claimRecord ( key ) ; if ( claimedOffset == DID_NOT_CLAIM_RECORD ) { return false ; } try { writer . writeRecord ( claimedOffset ) ; } finally { commit ( claimedOffset ) ; } return true ; }
High level and safe way of writing a record to the buffer .
20,338
public int claimRecord ( final int key ) { int offset = endOfPositionField ; while ( offset < position ( ) ) { if ( key == key ( offset ) ) { if ( statusVolatile ( offset ) == PENDING ) { return DID_NOT_CLAIM_RECORD ; } else { compareAndSetStatus ( offset , COMMITTED , PENDING ) ; return offset + SIZE_OF_RECORD_FRAME ; } } offset += slotSize ; } if ( ( offset + slotSize ) > buffer . capacity ( ) ) { return DID_NOT_CLAIM_RECORD ; } final int claimOffset = movePosition ( slotSize ) ; compareAndSetStatus ( claimOffset , UNUSED , PENDING ) ; key ( claimOffset , key ) ; return claimOffset + SIZE_OF_RECORD_FRAME ; }
Claim a record in the buffer . Each record has a unique key .
20,339
public static int compose ( final int major , final int minor , final int patch ) { if ( major < 0 || major > 255 ) { throw new IllegalArgumentException ( "major must be 0-255: " + major ) ; } if ( minor < 0 || minor > 255 ) { throw new IllegalArgumentException ( "minor must be 0-255: " + minor ) ; } if ( patch < 0 || patch > 255 ) { throw new IllegalArgumentException ( "patch must be 0-255: " + patch ) ; } if ( major + minor + patch == 0 ) { throw new IllegalArgumentException ( "all parts cannot be zero" ) ; } return ( major << 16 ) | ( minor << 8 ) | patch ; }
Compose a 4 - byte integer with major minor and patch version stored in the least significant 3 bytes . The sum of the components must be greater than zero .
20,340
public int forEach ( final ToIntFunction < SelectionKey > function ) { int handledFrames = 0 ; final SelectionKey [ ] keys = this . keys ; for ( int i = size - 1 ; i >= 0 ; i -- ) { handledFrames += function . applyAsInt ( keys [ i ] ) ; } size = 0 ; return handledFrames ; }
Iterate over the key set and apply the given function .
20,341
public void compact ( ) { final int idealCapacity = ( int ) Math . round ( size ( ) * ( 1.0 / loadFactor ) ) ; rehash ( findNextPositivePowerOfTwo ( Math . max ( MIN_CAPACITY , idealCapacity ) ) ) ; }
Compact the backing arrays by rehashing with a capacity just larger than current size and giving consideration to the load factor .
20,342
public boolean await ( ) { System . out . format ( "%n%s (y/n): " , label ) . flush ( ) ; final Scanner in = new Scanner ( System . in ) ; final String line = in . nextLine ( ) ; return "y" . equalsIgnoreCase ( line ) ; }
Await for input that matches the provided command .
20,343
public void addInt ( final int index , final int element ) { checkIndexForAdd ( index ) ; final int requiredSize = size + 1 ; ensureCapacityPrivate ( requiredSize ) ; if ( index < size ) { System . arraycopy ( elements , index , elements , index + 1 , size - index ) ; } elements [ index ] = element ; size ++ ; }
Add a element without boxing at a given index .
20,344
public int setInt ( final int index , final int element ) { checkIndex ( index ) ; final int previous = elements [ index ] ; elements [ index ] = element ; return previous ; }
Set an element at a given index without boxing .
20,345
public Integer remove ( final int index ) { checkIndex ( index ) ; final int value = elements [ index ] ; final int moveCount = size - index - 1 ; if ( moveCount > 0 ) { System . arraycopy ( elements , index + 1 , elements , index , moveCount ) ; } size -- ; return value ; }
Remove at a given index .
20,346
public int fastUnorderedRemove ( final int index ) { checkIndex ( index ) ; final int value = elements [ index ] ; elements [ index ] = elements [ -- size ] ; return value ; }
Removes element at index but instead of copying all elements to the left it replaces the item in the slot with the last item in the list . This avoids the copy costs at the expense of preserving list order . If index is the last element it is just removed .
20,347
public boolean removeInt ( final int value ) { final int index = indexOf ( value ) ; if ( - 1 != index ) { remove ( index ) ; return true ; } return false ; }
Remove the first instance of a value if found in the list .
20,348
public boolean fastUnorderedRemoveInt ( final int value ) { final int index = indexOf ( value ) ; if ( - 1 != index ) { elements [ index ] = elements [ -- size ] ; return true ; } return false ; }
Remove the first instance of a value if found in the list and replaces it with the last item in the list . This saves a copy down of all items at the expense of not preserving list order .
20,349
public int [ ] toIntArray ( final int [ ] dst ) { if ( dst . length == size ) { System . arraycopy ( elements , 0 , dst , 0 , dst . length ) ; return dst ; } else { return Arrays . copyOf ( elements , size ) ; } }
Create a new array that is a copy of the elements .
20,350
public static int read ( final AtomicBuffer buffer , final ErrorConsumer consumer , final long sinceTimestamp ) { int entries = 0 ; int offset = 0 ; final int capacity = buffer . capacity ( ) ; while ( offset < capacity ) { final int length = buffer . getIntVolatile ( offset + LENGTH_OFFSET ) ; if ( 0 == length ) { break ; } final long lastObservationTimestamp = buffer . getLongVolatile ( offset + LAST_OBSERVATION_TIMESTAMP_OFFSET ) ; if ( lastObservationTimestamp >= sinceTimestamp ) { ++ entries ; consumer . accept ( buffer . getInt ( offset + OBSERVATION_COUNT_OFFSET ) , buffer . getLong ( offset + FIRST_OBSERVATION_TIMESTAMP_OFFSET ) , lastObservationTimestamp , buffer . getStringWithoutLengthUtf8 ( offset + ENCODED_ERROR_OFFSET , length - ENCODED_ERROR_OFFSET ) ) ; } offset += align ( length , RECORD_ALIGNMENT ) ; } return entries ; }
Read all the errors in a log since a given timestamp .
20,351
public static < T > void fastUnorderedRemove ( final ArrayList < T > list , final int index ) { final int lastIndex = list . size ( ) - 1 ; if ( index != lastIndex ) { list . set ( index , list . remove ( lastIndex ) ) ; } else { list . remove ( index ) ; } }
Removes element at index but instead of copying all elements to the left moves into the same slot the last element . This avoids the copy costs but spoils the list order . If index is the last element it is just removed .
20,352
public static < T > boolean fastUnorderedRemove ( final ArrayList < T > list , final T e ) { for ( int i = 0 , size = list . size ( ) ; i < size ; i ++ ) { if ( e == list . get ( i ) ) { fastUnorderedRemove ( list , i , size - 1 ) ; return true ; } } return false ; }
Removes element but instead of copying all elements to the left moves into the same slot the last element . This avoids the copy costs but spoils the list order . If element is the last element then it is just removed .
20,353
public static synchronized void enable ( ) { if ( null != thread ) { thread = new Thread ( HighResolutionTimer :: run ) ; thread . setDaemon ( true ) ; thread . setName ( "high-resolution-timer-hack" ) ; thread . start ( ) ; } }
Attempt to enable high resolution timers .
20,354
public synchronized void addGeoQueryDataEventListener ( final GeoQueryDataEventListener listener ) { if ( eventListeners . contains ( listener ) ) { throw new IllegalArgumentException ( "Added the same listener twice to a GeoQuery!" ) ; } eventListeners . add ( listener ) ; if ( this . queries == null ) { this . setupQueries ( ) ; } else { for ( final Map . Entry < String , LocationInfo > entry : this . locationInfos . entrySet ( ) ) { final String key = entry . getKey ( ) ; final LocationInfo info = entry . getValue ( ) ; if ( info . inGeoQuery ) { this . geoFire . raiseEvent ( new Runnable ( ) { public void run ( ) { listener . onDataEntered ( info . dataSnapshot , info . location ) ; } } ) ; } } if ( this . canFireReady ( ) ) { this . geoFire . raiseEvent ( new Runnable ( ) { public void run ( ) { listener . onGeoQueryReady ( ) ; } } ) ; } } }
Adds a new GeoQueryEventListener to this GeoQuery .
20,355
public synchronized void removeGeoQueryEventListener ( final GeoQueryDataEventListener listener ) { if ( ! eventListeners . contains ( listener ) ) { throw new IllegalArgumentException ( "Trying to remove listener that was removed or not added!" ) ; } eventListeners . remove ( listener ) ; if ( ! this . hasListeners ( ) ) { reset ( ) ; } }
Removes an event listener .
20,356
public void setLocation ( final String key , final GeoLocation location , final CompletionListener completionListener ) { if ( key == null ) { throw new NullPointerException ( ) ; } DatabaseReference keyRef = this . getDatabaseRefForKey ( key ) ; GeoHash geoHash = new GeoHash ( location ) ; Map < String , Object > updates = new HashMap < > ( ) ; updates . put ( "g" , geoHash . getGeoHashString ( ) ) ; updates . put ( "l" , Arrays . asList ( location . latitude , location . longitude ) ) ; if ( completionListener != null ) { keyRef . setValue ( updates , geoHash . getGeoHashString ( ) , new DatabaseReference . CompletionListener ( ) { public void onComplete ( DatabaseError databaseError , DatabaseReference databaseReference ) { completionListener . onComplete ( key , databaseError ) ; } } ) ; } else { keyRef . setValue ( updates , geoHash . getGeoHashString ( ) ) ; } }
Sets the location for a given key .
20,357
public void removeLocation ( final String key , final CompletionListener completionListener ) { if ( key == null ) { throw new NullPointerException ( ) ; } DatabaseReference keyRef = this . getDatabaseRefForKey ( key ) ; if ( completionListener != null ) { keyRef . setValue ( null , new DatabaseReference . CompletionListener ( ) { public void onComplete ( DatabaseError databaseError , DatabaseReference databaseReference ) { completionListener . onComplete ( key , databaseError ) ; } } ) ; } else { keyRef . setValue ( null ) ; } }
Removes the location for a key from this GeoFire .
20,358
public void getLocation ( String key , LocationCallback callback ) { DatabaseReference keyRef = this . getDatabaseRefForKey ( key ) ; LocationValueEventListener valueListener = new LocationValueEventListener ( callback ) ; keyRef . addListenerForSingleValueEvent ( valueListener ) ; }
Gets the current location for a key and calls the callback with the current value .
20,359
private void animateMarkerTo ( final Marker marker , final double lat , final double lng ) { final Handler handler = new Handler ( ) ; final long start = SystemClock . uptimeMillis ( ) ; final long DURATION_MS = 3000 ; final Interpolator interpolator = new AccelerateDecelerateInterpolator ( ) ; final LatLng startPosition = marker . getPosition ( ) ; handler . post ( new Runnable ( ) { public void run ( ) { float elapsed = SystemClock . uptimeMillis ( ) - start ; float t = elapsed / DURATION_MS ; float v = interpolator . getInterpolation ( t ) ; double currentLat = ( lat - startPosition . latitude ) * v + startPosition . latitude ; double currentLng = ( lng - startPosition . longitude ) * v + startPosition . longitude ; marker . setPosition ( new LatLng ( currentLat , currentLng ) ) ; if ( t < 1 ) { handler . postDelayed ( this , 16 ) ; } } } ) ; }
Animation handler for old APIs without animation support
20,360
public static Map < ModuleAdapter < ? > , Object > loadModules ( Loader loader , Object [ ] seedModulesOrClasses ) { Map < ModuleAdapter < ? > , Object > seedAdapters = new LinkedHashMap < ModuleAdapter < ? > , Object > ( seedModulesOrClasses . length ) ; for ( int i = 0 ; i < seedModulesOrClasses . length ; i ++ ) { if ( seedModulesOrClasses [ i ] instanceof Class < ? > ) { ModuleAdapter < ? > adapter = loader . getModuleAdapter ( ( Class < ? > ) seedModulesOrClasses [ i ] ) ; seedAdapters . put ( adapter , adapter . newModule ( ) ) ; } else { ModuleAdapter < ? > adapter = loader . getModuleAdapter ( seedModulesOrClasses [ i ] . getClass ( ) ) ; seedAdapters . put ( adapter , seedModulesOrClasses [ i ] ) ; } } Map < ModuleAdapter < ? > , Object > result = new LinkedHashMap < ModuleAdapter < ? > , Object > ( seedAdapters ) ; Map < Class < ? > , ModuleAdapter < ? > > transitiveInclusions = new LinkedHashMap < Class < ? > , ModuleAdapter < ? > > ( ) ; for ( ModuleAdapter < ? > adapter : seedAdapters . keySet ( ) ) { collectIncludedModulesRecursively ( loader , adapter , transitiveInclusions ) ; } for ( ModuleAdapter < ? > dependency : transitiveInclusions . values ( ) ) { if ( ! result . containsKey ( dependency ) ) { result . put ( dependency , dependency . newModule ( ) ) ; } } return result ; }
Returns a full set of module adapters including module adapters for included modules .
20,361
public void linkRequested ( ) { assertLockHeld ( ) ; Binding < ? > binding ; while ( ( binding = toLink . poll ( ) ) != null ) { if ( binding instanceof DeferredBinding ) { DeferredBinding deferred = ( DeferredBinding ) binding ; String key = deferred . deferredKey ; boolean mustHaveInjections = deferred . mustHaveInjections ; if ( bindings . containsKey ( key ) ) { continue ; } try { Binding < ? > resolvedBinding = createBinding ( key , binding . requiredBy , deferred . classLoader , mustHaveInjections ) ; resolvedBinding . setLibrary ( binding . library ( ) ) ; resolvedBinding . setDependedOn ( binding . dependedOn ( ) ) ; if ( ! key . equals ( resolvedBinding . provideKey ) && ! key . equals ( resolvedBinding . membersKey ) ) { throw new IllegalStateException ( "Unable to create binding for " + key ) ; } Binding < ? > scopedBinding = scope ( resolvedBinding ) ; toLink . add ( scopedBinding ) ; putBinding ( scopedBinding ) ; } catch ( InvalidBindingException e ) { addError ( e . type + " " + e . getMessage ( ) + " required by " + binding . requiredBy ) ; bindings . put ( key , Binding . UNRESOLVED ) ; } catch ( UnsupportedOperationException e ) { addError ( "Unsupported: " + e . getMessage ( ) + " required by " + binding . requiredBy ) ; bindings . put ( key , Binding . UNRESOLVED ) ; } catch ( IllegalArgumentException e ) { addError ( e . getMessage ( ) + " required by " + binding . requiredBy ) ; bindings . put ( key , Binding . UNRESOLVED ) ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } else { attachSuccess = true ; binding . attach ( this ) ; if ( attachSuccess ) { binding . setLinked ( ) ; } else { toLink . add ( binding ) ; } } } try { errorHandler . handleErrors ( errors ) ; } finally { errors . clear ( ) ; } }
Links all requested bindings plus their transitive dependencies . This creates JIT bindings as necessary to fill in the gaps .
20,362
static CodeBlock bindingTypeDocs ( TypeName type , boolean abstrakt , boolean members , boolean dependent ) { CodeBlock . Builder result = CodeBlock . builder ( ) . add ( "A {@code Binding<$T>} implementation which satisfies\n" , type ) . add ( "Dagger's infrastructure requirements including:\n" ) ; if ( dependent ) { result . add ( "\n" ) . add ( "Owning the dependency links between {@code $T} and its\n" , type ) . add ( "dependencies.\n" ) ; } if ( ! abstrakt ) { result . add ( "\n" ) . add ( "Being a {@code Provider<$T>} and handling creation and\n" , type ) . add ( "preparation of object instances.\n" ) ; } if ( members ) { result . add ( "\n" ) . add ( "Being a {@code MembersInjector<$T>} and handling injection\n" , type ) . add ( "of annotated fields.\n" ) ; } return result . build ( ) ; }
Creates an appropriate javadoc depending on aspects of the type in question .
20,363
public boolean add ( E e ) { if ( e == null ) throw new NullPointerException ( "e == null" ) ; elements [ tail ] = e ; if ( ( tail = ( tail + 1 ) & ( elements . length - 1 ) ) == head ) doubleCapacity ( ) ; return true ; }
Inserts the specified element at the end of this queue .
20,364
public E remove ( ) { E x = poll ( ) ; if ( x == null ) throw new NoSuchElementException ( ) ; return x ; }
Retrieves and removes the head of the queue represented by this queue .
20,365
private boolean delete ( int i ) { final Object [ ] elements = this . elements ; final int mask = elements . length - 1 ; final int h = head ; final int t = tail ; final int front = ( i - h ) & mask ; final int back = ( t - i ) & mask ; if ( front >= ( ( t - h ) & mask ) ) throw new ConcurrentModificationException ( ) ; if ( front < back ) { if ( h <= i ) { System . arraycopy ( elements , h , elements , h + 1 , front ) ; } else { System . arraycopy ( elements , 0 , elements , 1 , i ) ; elements [ 0 ] = elements [ mask ] ; System . arraycopy ( elements , h , elements , h + 1 , mask - h ) ; } elements [ h ] = null ; head = ( h + 1 ) & mask ; return false ; } else { if ( i < t ) { System . arraycopy ( elements , i + 1 , elements , i , back ) ; tail = t - 1 ; } else { System . arraycopy ( elements , i + 1 , elements , i , mask - i ) ; elements [ mask ] = elements [ 0 ] ; System . arraycopy ( elements , 1 , elements , 0 , t ) ; tail = ( t - 1 ) & mask ; } return true ; } }
Removes the element at the specified position in the elements array adjusting head and tail as necessary . This can result in motion of elements backwards or forwards in the array .
20,366
private void writeObject ( java . io . ObjectOutputStream s ) throws java . io . IOException { s . defaultWriteObject ( ) ; s . writeInt ( size ( ) ) ; int mask = elements . length - 1 ; for ( int i = head ; i != tail ; i = ( i + 1 ) & mask ) s . writeObject ( elements [ i ] ) ; }
Serialize this queue .
20,367
private void readObject ( java . io . ObjectInputStream s ) throws java . io . IOException , ClassNotFoundException { s . defaultReadObject ( ) ; int size = s . readInt ( ) ; allocateElements ( size ) ; head = 0 ; tail = size ; for ( int i = 0 ; i < size ; i ++ ) elements [ i ] = s . readObject ( ) ; }
Deserialize this queue .
20,368
private static TypeElement resolveType ( Elements elements , String className , StringBuilder sb , final int index ) { sb . setCharAt ( index , '.' ) ; int nextIndex = nextDollar ( className , sb , index + 1 ) ; TypeElement type = nextIndex == - 1 ? getTypeElement ( elements , sb ) : resolveType ( elements , className , sb , nextIndex ) ; if ( type != null ) { return type ; } sb . setCharAt ( index , '$' ) ; nextIndex = nextDollar ( className , sb , index + 1 ) ; return nextIndex == - 1 ? getTypeElement ( elements , sb ) : resolveType ( elements , className , sb , nextIndex ) ; }
Recursively explores the space of possible canonical names for a given binary class name .
20,369
public static List < PathElement > parse ( String key ) { if ( key . contains ( AT ) ) { return Arrays . < PathElement > asList ( new AtPathElement ( key ) ) ; } else if ( STAR . equals ( key ) ) { return Arrays . < PathElement > asList ( new StarAllPathElement ( key ) ) ; } else if ( key . contains ( STAR ) ) { if ( StringTools . countMatches ( key , STAR ) == 1 ) { return Arrays . < PathElement > asList ( new StarSinglePathElement ( key ) ) ; } else { return Arrays . < PathElement > asList ( new StarRegexPathElement ( key ) ) ; } } else { return Arrays . < PathElement > asList ( new LiteralPathElement ( key ) ) ; } }
once all the cardinalitytransform specific logic is extracted .
20,370
private static Set < Key > processSpec ( boolean parentIsArray , Map < String , Object > spec ) { Set < Key > result = new HashSet < > ( ) ; for ( String key : spec . keySet ( ) ) { Object subSpec = spec . get ( key ) ; if ( parentIsArray ) { result . add ( new ArrayKey ( key , subSpec ) ) ; } else { result . add ( new MapKey ( key , subSpec ) ) ; } } return result ; }
Recursively walk the spec input tree . Handle arrays by telling DefaultrKeys if they need to be ArrayKeys and to find the max default array length .
20,371
public void applyChildren ( Object defaultee ) { if ( defaultee == null ) { throw new TransformException ( "Defaultee should never be null when " + "passed to the applyChildren method." ) ; } if ( isArrayOutput ( ) && defaultee instanceof List ) { @ SuppressWarnings ( "unchecked" ) List < Object > defaultList = ( List < Object > ) defaultee ; for ( int index = defaultList . size ( ) - 1 ; index < getOutputArraySize ( ) ; index ++ ) { defaultList . add ( null ) ; } } ArrayList < Key > sortedChildren = new ArrayList < > ( ) ; sortedChildren . addAll ( children ) ; Collections . sort ( sortedChildren , keyComparator ) ; for ( Key childKey : sortedChildren ) { childKey . applyChild ( defaultee ) ; } }
This is the main recursive method . The defaultee should never be null because the defaultee wasn t null it was null and we created it OR there was a mismatch between the Defaultr Spec and the input and we didn t recurse .
20,372
public Object transform ( Object input , Map < String , Object > context ) { return doTransform ( transformsList , input , context ) ; }
Runs a series of Transforms on the input piping the inputs and outputs of the Transforms together .
20,373
public Object transform ( int from , int to , Object input , Map < String , Object > context ) { if ( from < 0 || to > transformsList . size ( ) || to <= from ) { throw new TransformException ( "JOLT Chainr : invalid from and to parameters : from=" + from + " to=" + to ) ; } return doTransform ( transformsList . subList ( from , to ) , input , context ) ; }
Have Chainr run a subset of the transforms in it s spec .
20,374
public Object transform ( Object input ) { rootSpec . apply ( ROOT_KEY , Optional . of ( input ) , new WalkedPath ( ) , null , null ) ; return input ; }
Applies the Cardinality transform .
20,375
public static Optional < ? extends Number > toNumber ( Object arg ) { if ( arg instanceof Number ) { return Optional . of ( ( ( Number ) arg ) ) ; } else if ( arg instanceof String ) { try { return Optional . of ( ( Number ) Integer . parseInt ( ( String ) arg ) ) ; } catch ( Exception ignored ) { } try { return Optional . of ( ( Number ) Long . parseLong ( ( String ) arg ) ) ; } catch ( Exception ignored ) { } try { return Optional . of ( ( Number ) Double . parseDouble ( ( String ) arg ) ) ; } catch ( Exception ignored ) { } return Optional . empty ( ) ; } else { return Optional . empty ( ) ; } }
Given any object returns if possible . its Java number equivalent wrapped in Optional Interprets String as Number
20,376
public static Optional < Integer > toInteger ( Object arg ) { if ( arg instanceof Number ) { return Optional . of ( ( ( Number ) arg ) . intValue ( ) ) ; } else if ( arg instanceof String ) { Optional < ? extends Number > optional = toNumber ( arg ) ; if ( optional . isPresent ( ) ) { return Optional . of ( optional . get ( ) . intValue ( ) ) ; } else { return Optional . empty ( ) ; } } else { return Optional . empty ( ) ; } }
Returns int value of argument if possible wrapped in Optional Interprets String as Number
20,377
public static Optional < Long > toLong ( Object arg ) { if ( arg instanceof Number ) { return Optional . of ( ( ( Number ) arg ) . longValue ( ) ) ; } else if ( arg instanceof String ) { Optional < ? extends Number > optional = toNumber ( arg ) ; if ( optional . isPresent ( ) ) { return Optional . of ( optional . get ( ) . longValue ( ) ) ; } else { return Optional . empty ( ) ; } } else { return Optional . empty ( ) ; } }
Returns long value of argument if possible wrapped in Optional Interprets String as Number
20,378
public static Optional < Double > toDouble ( Object arg ) { if ( arg instanceof Number ) { return Optional . of ( ( ( Number ) arg ) . doubleValue ( ) ) ; } else if ( arg instanceof String ) { Optional < ? extends Number > optional = toNumber ( arg ) ; if ( optional . isPresent ( ) ) { return Optional . of ( optional . get ( ) . doubleValue ( ) ) ; } else { return Optional . empty ( ) ; } } else { return Optional . empty ( ) ; } }
Returns double value of argument if possible wrapped in Optional Interprets String as Number
20,379
public static Optional < Boolean > toBoolean ( Object arg ) { if ( arg instanceof Boolean ) { return Optional . of ( ( Boolean ) arg ) ; } else if ( arg instanceof String ) { if ( "true" . equalsIgnoreCase ( ( String ) arg ) ) { return Optional . of ( Boolean . TRUE ) ; } else if ( "false" . equalsIgnoreCase ( ( String ) arg ) ) { return Optional . of ( Boolean . FALSE ) ; } } return Optional . empty ( ) ; }
Returns boolean value of argument if possible wrapped in Optional Interprets Strings true & false as boolean
20,380
public static void squashNulls ( Object input ) { if ( input instanceof List ) { List inputList = ( List ) input ; inputList . removeIf ( java . util . Objects :: isNull ) ; } else if ( input instanceof Map ) { Map < String , Object > inputMap = ( Map < String , Object > ) input ; List < String > keysToNuke = new ArrayList < > ( ) ; for ( Map . Entry < String , Object > entry : inputMap . entrySet ( ) ) { if ( entry . getValue ( ) == null ) { keysToNuke . add ( entry . getKey ( ) ) ; } } inputMap . keySet ( ) . removeAll ( keysToNuke ) ; } }
Squashes nulls in a list or map .
20,381
public static void recursivelySquashNulls ( Object input ) { Objects . squashNulls ( input ) ; if ( input instanceof List ) { List inputList = ( List ) input ; inputList . forEach ( i -> recursivelySquashNulls ( i ) ) ; } else if ( input instanceof Map ) { Map < String , Object > inputMap = ( Map < String , Object > ) input ; for ( Map . Entry < String , Object > entry : inputMap . entrySet ( ) ) { recursivelySquashNulls ( entry . getValue ( ) ) ; } } }
Recursively squash nulls in maps and lists .
20,382
public static Optional < Number > max ( List < Object > args ) { if ( args == null || args . size ( ) == 0 ) { return Optional . empty ( ) ; } Integer maxInt = Integer . MIN_VALUE ; Double maxDouble = - ( Double . MAX_VALUE ) ; Long maxLong = Long . MIN_VALUE ; boolean found = false ; for ( Object arg : args ) { if ( arg instanceof Integer ) { maxInt = java . lang . Math . max ( maxInt , ( Integer ) arg ) ; found = true ; } else if ( arg instanceof Double ) { maxDouble = java . lang . Math . max ( maxDouble , ( Double ) arg ) ; found = true ; } else if ( arg instanceof Long ) { maxLong = java . lang . Math . max ( maxLong , ( Long ) arg ) ; found = true ; } else if ( arg instanceof String ) { Optional < ? > optional = Objects . toNumber ( arg ) ; if ( optional . isPresent ( ) ) { arg = optional . get ( ) ; if ( arg instanceof Integer ) { maxInt = java . lang . Math . max ( maxInt , ( Integer ) arg ) ; found = true ; } else if ( arg instanceof Double ) { maxDouble = java . lang . Math . max ( maxDouble , ( Double ) arg ) ; found = true ; } else if ( arg instanceof Long ) { maxLong = java . lang . Math . max ( maxLong , ( Long ) arg ) ; found = true ; } } } } if ( ! found ) { return Optional . empty ( ) ; } if ( maxInt . longValue ( ) >= maxDouble . longValue ( ) && maxInt . longValue ( ) >= maxLong ) { return Optional . < Number > of ( maxInt ) ; } else if ( maxLong >= maxDouble . longValue ( ) ) { return Optional . < Number > of ( maxLong ) ; } else { return Optional . < Number > of ( maxDouble ) ; } }
Given a list of objects returns the max value in its appropriate type also interprets String as Number and returns appropriately
20,383
public static Optional < Number > min ( List < Object > args ) { if ( args == null || args . size ( ) == 0 ) { return Optional . empty ( ) ; } Integer minInt = Integer . MAX_VALUE ; Double minDouble = Double . MAX_VALUE ; Long minLong = Long . MAX_VALUE ; boolean found = false ; for ( Object arg : args ) { if ( arg instanceof Integer ) { minInt = java . lang . Math . min ( minInt , ( Integer ) arg ) ; found = true ; } else if ( arg instanceof Double ) { minDouble = java . lang . Math . min ( minDouble , ( Double ) arg ) ; found = true ; } else if ( arg instanceof Long ) { minLong = java . lang . Math . min ( minLong , ( Long ) arg ) ; found = true ; } else if ( arg instanceof String ) { Optional < ? > optional = Objects . toNumber ( arg ) ; if ( optional . isPresent ( ) ) { arg = optional . get ( ) ; if ( arg instanceof Integer ) { minInt = java . lang . Math . min ( minInt , ( Integer ) arg ) ; found = true ; } else if ( arg instanceof Double ) { minDouble = java . lang . Math . min ( minDouble , ( Double ) arg ) ; found = true ; } else if ( arg instanceof Long ) { minLong = java . lang . Math . min ( minLong , ( Long ) arg ) ; found = true ; } } } } if ( ! found ) { return Optional . empty ( ) ; } if ( minInt . longValue ( ) <= minDouble . longValue ( ) && minInt . longValue ( ) <= minLong ) { return Optional . < Number > of ( minInt ) ; } else if ( minLong <= minDouble . longValue ( ) ) { return Optional . < Number > of ( minLong ) ; } else { return Optional . < Number > of ( minDouble ) ; } }
Given a list of objects returns the min value in its appropriate type also interprets String as Number and returns appropriately
20,384
public static Optional < Number > abs ( Object arg ) { if ( arg instanceof Integer ) { return Optional . < Number > of ( java . lang . Math . abs ( ( Integer ) arg ) ) ; } else if ( arg instanceof Double ) { return Optional . < Number > of ( java . lang . Math . abs ( ( Double ) arg ) ) ; } else if ( arg instanceof Long ) { return Optional . < Number > of ( java . lang . Math . abs ( ( Long ) arg ) ) ; } else if ( arg instanceof String ) { return abs ( Objects . toNumber ( arg ) . get ( ) ) ; } return Optional . empty ( ) ; }
Given any object returns if possible . its absolute value wrapped in Optional Interprets String as Number
20,385
public static Optional < Double > avg ( List < Object > args ) { double sum = 0d ; int count = 0 ; for ( Object arg : args ) { Optional < ? extends Number > numberOptional = Objects . toNumber ( arg ) ; if ( numberOptional . isPresent ( ) ) { sum = sum + numberOptional . get ( ) . doubleValue ( ) ; count = count + 1 ; } } return count == 0 ? Optional . < Double > empty ( ) : Optional . of ( sum / count ) ; }
Given a list of numbers returns their avg as double any value in the list that is not a valid number is ignored
20,386
public boolean applyCardinality ( String inputKey , Object input , WalkedPath walkedPath , Object parentContainer ) { MatchedElement thisLevel = getMatch ( inputKey , walkedPath ) ; if ( thisLevel == null ) { return false ; } performCardinalityAdjustment ( inputKey , input , walkedPath , ( Map ) parentContainer , thisLevel ) ; return true ; }
If this CardinalitySpec matches the inputkey then do the work of modifying the data and return true .
20,387
public List < String > applyToMap ( Map < String , Object > inputMap ) { if ( inputMap == null ) { return null ; } List < String > keysToBeRemoved = new LinkedList < > ( ) ; if ( pathElement instanceof LiteralPathElement ) { if ( inputMap . containsKey ( pathElement . getRawKey ( ) ) ) { keysToBeRemoved . add ( pathElement . getRawKey ( ) ) ; } } else if ( pathElement instanceof StarPathElement ) { StarPathElement star = ( StarPathElement ) pathElement ; for ( String key : inputMap . keySet ( ) ) { if ( star . stringMatch ( key ) ) { keysToBeRemoved . add ( key ) ; } } } return keysToBeRemoved ; }
Build a list of keys to remove from the input map using the pathElement from the Spec .
20,388
public Object transform ( Object input ) { if ( input == null ) { input = new HashMap ( ) ; } if ( input instanceof List ) { if ( arrayRoot == null ) { throw new TransformException ( "The Spec provided can not handle input that is a top level Json Array." ) ; } arrayRoot . applyChildren ( input ) ; } else { mapRoot . applyChildren ( input ) ; } return input ; }
Top level standalone Defaultr method .
20,389
public boolean apply ( String inputKey , Optional < Object > inputOptional , WalkedPath walkedPath , Map < String , Object > output , Map < String , Object > context ) { MatchedElement thisLevel = pathElement . match ( inputKey , walkedPath ) ; if ( thisLevel == null ) { return false ; } if ( pathElement instanceof TransposePathElement ) { TransposePathElement tpe = ( TransposePathElement ) this . pathElement ; Optional < Object > optional = tpe . objectEvaluate ( walkedPath ) ; if ( ! optional . isPresent ( ) ) { return false ; } inputOptional = optional ; } walkedPath . add ( inputOptional . get ( ) , thisLevel ) ; for ( ShiftrSpec subSpec : specialChildren ) { subSpec . apply ( inputKey , inputOptional , walkedPath , output , context ) ; } executionStrategy . process ( this , inputOptional , walkedPath , output , context ) ; walkedPath . removeLast ( ) ; walkedPath . lastElement ( ) . getMatchedElement ( ) . incrementHashCount ( ) ; return true ; }
If this Spec matches the inputKey then perform one step in the Shiftr parallel treewalk .
20,390
@ SuppressWarnings ( "unchecked" ) protected static void setData ( Object parent , MatchedElement matchedElement , Object value , OpMode opMode ) { if ( parent instanceof Map ) { Map source = ( Map ) parent ; String key = matchedElement . getRawKey ( ) ; if ( opMode . isApplicable ( source , key ) ) { source . put ( key , value ) ; } } else if ( parent instanceof List && matchedElement instanceof ArrayMatchedElement ) { List source = ( List ) parent ; int origSize = ( ( ArrayMatchedElement ) matchedElement ) . getOrigSize ( ) ; int reqIndex = ( ( ArrayMatchedElement ) matchedElement ) . getRawIndex ( ) ; if ( opMode . isApplicable ( source , reqIndex , origSize ) ) { source . set ( reqIndex , value ) ; } } else { throw new RuntimeException ( "Should not come here!" ) ; } }
Static utility method for facilitating writes on input object
20,391
public static boolean printJsonObject ( Object output , Boolean uglyPrint , boolean suppressOutput ) { try { if ( uglyPrint ) { printToStandardOut ( JsonUtils . toJsonString ( output ) , suppressOutput ) ; } else { printToStandardOut ( JsonUtils . toPrettyJsonString ( output ) , suppressOutput ) ; } } catch ( Exception e ) { printToStandardOut ( "An error occured while attempting to print the output." , suppressOutput ) ; return false ; } return true ; }
Prints the given json object to standard out accounting for pretty printing and suppressed output .
20,392
public static Object readJsonInput ( File file , boolean suppressOutput ) { Object jsonObject ; if ( file == null ) { try { jsonObject = JsonUtils . jsonToMap ( System . in ) ; } catch ( Exception e ) { printToStandardOut ( "Failed to process standard input." , suppressOutput ) ; return null ; } } else { jsonObject = createJsonObjectFromFile ( file , suppressOutput ) ; } return jsonObject ; }
This method will read in JSON either from the given file or from standard in if the file is null . An object contain the ingested input is returned .
20,393
public Optional < DataType > handleIntermediateGet ( TraversalStep traversalStep , Object tree , String key , TraversalStep . Operation op ) { Optional < Object > optSub = traversalStep . get ( tree , key ) ; Object sub = optSub . get ( ) ; if ( sub == null && op == TraversalStep . Operation . SET ) { sub = traversalStep . getChild ( ) . newContainer ( ) ; traversalStep . overwriteSet ( tree , key , sub ) ; } return Optional . of ( ( DataType ) sub ) ; }
Only make a new instance of a container object for SET if there is nothing there .
20,394
public static TransposePathElement parse ( String key ) { if ( key == null || key . length ( ) < 2 ) { throw new SpecException ( "'Transpose Input' key '@', can not be null or of length 1. Offending key : " + key ) ; } if ( '@' != key . charAt ( 0 ) ) { throw new SpecException ( "'Transpose Input' key must start with an '@'. Offending key : " + key ) ; } String meat = key . substring ( 1 ) ; if ( meat . contains ( "@" ) ) { throw new SpecException ( "@ pathElement can not contain a nested @. Was: " + meat ) ; } if ( meat . contains ( "*" ) || meat . contains ( "[]" ) ) { throw new SpecException ( "'Transpose Input' can not contain expansion wildcards (* and []). Offending key : " + key ) ; } if ( meat . startsWith ( "(" ) ) { if ( meat . endsWith ( ")" ) ) { meat = meat . substring ( 1 , meat . length ( ) - 1 ) ; } else { throw new SpecException ( "@ path element that starts with '(' must have a matching ')'. Offending key : " + key ) ; } } return innerParse ( key , meat ) ; }
Parse a text value from a Spec into a TransposePathElement .
20,395
private static TransposePathElement innerParse ( String originalKey , String meat ) { char first = meat . charAt ( 0 ) ; if ( Character . isDigit ( first ) ) { StringBuilder sb = new StringBuilder ( ) . append ( first ) ; for ( int index = 1 ; index < meat . length ( ) ; index ++ ) { char c = meat . charAt ( index ) ; if ( ',' == c ) { int upLevel ; try { upLevel = Integer . valueOf ( sb . toString ( ) ) ; } catch ( NumberFormatException nfe ) { throw new SpecException ( "@ path element with non/mixed numeric key is not valid, key=" + originalKey ) ; } return new TransposePathElement ( originalKey , upLevel , meat . substring ( index + 1 ) ) ; } else if ( Character . isDigit ( c ) ) { sb . append ( c ) ; } else { throw new SpecException ( "@ path element with non/mixed numeric key is not valid, key=" + originalKey ) ; } } return new TransposePathElement ( originalKey , Integer . valueOf ( sb . toString ( ) ) , null ) ; } else { return new TransposePathElement ( originalKey , 0 , meat ) ; } }
Parse the core of the TransposePathElement key once basic errors have been checked and syntax has been handled .
20,396
public Optional < Object > objectEvaluate ( WalkedPath walkedPath ) { PathStep pathStep = walkedPath . elementFromEnd ( upLevel ) ; if ( pathStep == null ) { return Optional . empty ( ) ; } Object treeRef = pathStep . getTreeRef ( ) ; if ( subPathReader == null ) { return Optional . of ( treeRef ) ; } else { return subPathReader . read ( treeRef , walkedPath ) ; } }
This method is used when the TransposePathElement is used on the LFH as data .
20,397
public boolean apply ( String inputKey , Optional < Object > inputOptional , WalkedPath walkedPath , Map < String , Object > output , Map < String , Object > context ) { Object input = inputOptional . get ( ) ; MatchedElement thisLevel = pathElement . match ( inputKey , walkedPath ) ; if ( thisLevel == null ) { return false ; } Object data ; boolean realChild = false ; if ( this . pathElement instanceof DollarPathElement || this . pathElement instanceof HashPathElement ) { data = thisLevel . getCanonicalForm ( ) ; } else if ( this . pathElement instanceof AtPathElement ) { data = input ; } else if ( this . pathElement instanceof TransposePathElement ) { TransposePathElement tpe = ( TransposePathElement ) this . pathElement ; Optional < Object > evaledData = tpe . objectEvaluate ( walkedPath ) ; if ( evaledData . isPresent ( ) ) { data = evaledData . get ( ) ; } else { return false ; } } else { data = input ; realChild = true ; } walkedPath . add ( input , thisLevel ) ; for ( PathEvaluatingTraversal outputPath : shiftrWriters ) { outputPath . write ( data , output , walkedPath ) ; } walkedPath . removeLast ( ) ; if ( realChild ) { walkedPath . lastElement ( ) . getMatchedElement ( ) . incrementHashCount ( ) ; } return realChild ; }
If this Spec matches the inputkey then do the work of outputting data and return true .
20,398
protected static boolean runJolt ( String [ ] args ) { ArgumentParser parser = ArgumentParsers . newArgumentParser ( "jolt" ) ; Subparsers subparsers = parser . addSubparsers ( ) . help ( "transform: given a Jolt transform spec, runs the specified transforms on the input data.\n" + "diffy: diff two JSON documents.\n" + "sort: sort a JSON document alphabetically for human readability." ) ; for ( Map . Entry < String , JoltCliProcessor > entry : JOLT_CLI_PROCESSOR_MAP . entrySet ( ) ) { entry . getValue ( ) . intializeSubCommand ( subparsers ) ; } Namespace ns ; try { ns = parser . parseArgs ( args ) ; } catch ( ArgumentParserException e ) { parser . handleError ( e ) ; return false ; } JoltCliProcessor joltToolProcessor = JOLT_CLI_PROCESSOR_MAP . get ( args [ 0 ] ) ; if ( joltToolProcessor != null ) { return joltToolProcessor . process ( ns ) ; } else { return false ; } }
The logic for running DiffyTool has been captured in a helper method that returns a boolean to facilitate unit testing . Since System . exit terminates the JVM it would not be practical to test the main method .
20,399
public void write ( Object data , Map < String , Object > output , WalkedPath walkedPath ) { List < String > evaledPaths = evaluate ( walkedPath ) ; if ( evaledPaths != null ) { traversr . set ( output , evaledPaths , data ) ; } }
Use the supplied WalkedPath in the evaluation of each of our PathElements to build a concrete output path . Then use that output path to write the given data to the output .